1mod fix;
4mod integrations;
5
6use std::net::TcpListener;
7use std::path::PathBuf;
8
9pub(super) const GREEN: &str = "\x1b[32m";
10const RED: &str = "\x1b[31m";
11pub(super) const BOLD: &str = "\x1b[1m";
12pub(super) const RST: &str = "\x1b[0m";
13pub(super) const DIM: &str = "\x1b[2m";
14pub(super) const WHITE: &str = "\x1b[97m";
15pub(super) const YELLOW: &str = "\x1b[33m";
16
17pub(super) struct Outcome {
18 pub ok: bool,
19 pub line: String,
20}
21
22fn print_check(outcome: &Outcome) {
23 let mark = if outcome.ok {
24 format!("{GREEN}✓{RST}")
25 } else {
26 format!("{RED}✗{RST}")
27 };
28 println!(" {mark} {}", outcome.line);
29}
30
31fn path_in_path_env() -> bool {
32 if let Ok(path) = std::env::var("PATH") {
33 for dir in std::env::split_paths(&path) {
34 if dir.join("lean-ctx").is_file() {
35 return true;
36 }
37 if cfg!(windows)
38 && (dir.join("lean-ctx.exe").is_file() || dir.join("lean-ctx.cmd").is_file())
39 {
40 return true;
41 }
42 }
43 }
44 false
45}
46
47pub(super) fn resolve_lean_ctx_binary() -> Option<PathBuf> {
48 if let Ok(path) = std::env::var("PATH") {
49 for dir in std::env::split_paths(&path) {
50 if cfg!(windows) {
51 let exe = dir.join("lean-ctx.exe");
52 if exe.is_file() {
53 return Some(exe);
54 }
55 let cmd = dir.join("lean-ctx.cmd");
56 if cmd.is_file() {
57 return Some(cmd);
58 }
59 } else {
60 let bin = dir.join("lean-ctx");
61 if bin.is_file() {
62 return Some(bin);
63 }
64 }
65 }
66 }
67 None
68}
69
70fn lean_ctx_version_from_path() -> Outcome {
71 let resolved = resolve_lean_ctx_binary();
72 let bin = resolved
73 .clone()
74 .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| "lean-ctx".into()));
75
76 let v = env!("CARGO_PKG_VERSION");
77 let note = match std::env::current_exe() {
78 Ok(exe) if exe == bin => format!("{DIM}(this binary){RST}"),
79 Ok(_) | Err(_) => format!("{DIM}(resolved: {}){RST}", bin.display()),
80 };
81 Outcome {
82 ok: true,
83 line: format!("{BOLD}lean-ctx version{RST} {WHITE}lean-ctx {v}{RST} {note}"),
84 }
85}
86
87fn rc_contains_lean_ctx(path: &PathBuf) -> bool {
88 match std::fs::read_to_string(path) {
89 Ok(s) => s.contains("lean-ctx"),
90 Err(_) => false,
91 }
92}
93
94fn has_pipe_guard_in_content(content: &str) -> bool {
95 content.contains("! -t 1")
96 || content.contains("isatty stdout")
97 || content.contains("IsOutputRedirected")
98}
99
100fn rc_references_shell_hook(content: &str) -> bool {
101 content.contains("lean-ctx/shell-hook.") || content.contains("lean-ctx\\shell-hook.")
102}
103
104fn rc_has_pipe_guard(path: &PathBuf) -> bool {
105 match std::fs::read_to_string(path) {
106 Ok(s) => {
107 if has_pipe_guard_in_content(&s) {
108 return true;
109 }
110 if rc_references_shell_hook(&s) {
111 let dirs_to_check = hook_dirs();
112 for dir in &dirs_to_check {
113 for ext in &["zsh", "bash", "fish", "ps1"] {
114 let hook = dir.join(format!("shell-hook.{ext}"));
115 if let Ok(h) = std::fs::read_to_string(&hook) {
116 if has_pipe_guard_in_content(&h) {
117 return true;
118 }
119 }
120 }
121 }
122 }
123 false
124 }
125 Err(_) => false,
126 }
127}
128
129fn hook_dirs() -> Vec<std::path::PathBuf> {
130 let mut dirs = Vec::new();
131 if let Ok(d) = crate::core::data_dir::lean_ctx_data_dir() {
132 dirs.push(d);
133 }
134 if let Some(home) = dirs::home_dir() {
135 let legacy = home.join(".lean-ctx");
136 if !dirs.iter().any(|d| d == &legacy) {
137 dirs.push(legacy);
138 }
139 let xdg = home.join(".config").join("lean-ctx");
140 if !dirs.iter().any(|d| d == &xdg) {
141 dirs.push(xdg);
142 }
143 }
144 dirs
145}
146
147fn is_active_shell_impl(rc_name: &str, shell: &str, is_windows: bool, is_powershell: bool) -> bool {
148 match rc_name {
149 "~/.zshrc" => shell.contains("zsh"),
150 "~/.bashrc" => {
151 if is_windows {
157 if is_powershell {
158 return false;
159 }
160 return std::env::var("BASH_VERSION").is_ok();
164 }
165 shell.contains("bash") || shell.is_empty()
166 }
167 "~/.config/fish/config.fish" => shell.contains("fish"),
168 _ => true,
169 }
170}
171
172fn is_powershell_session() -> bool {
177 std::env::var("PSModulePath").is_ok()
178}
179
180fn is_active_shell(rc_name: &str) -> bool {
181 let shell = std::env::var("SHELL").unwrap_or_default();
182 is_active_shell_impl(rc_name, &shell, cfg!(windows), is_powershell_session())
183}
184
185pub(super) fn shell_aliases_outcome() -> Outcome {
186 let Some(home) = dirs::home_dir() else {
187 return Outcome {
188 ok: false,
189 line: format!("{BOLD}Shell aliases{RST} {RED}could not resolve home directory{RST}"),
190 };
191 };
192
193 let mut parts = Vec::new();
194 let mut needs_update = Vec::new();
195
196 let zsh = home.join(".zshrc");
197 if rc_contains_lean_ctx(&zsh) {
198 parts.push(format!("{DIM}~/.zshrc{RST}"));
199 if !rc_has_pipe_guard(&zsh) && is_active_shell("~/.zshrc") {
200 needs_update.push("~/.zshrc");
201 }
202 }
203 let bash = home.join(".bashrc");
204 if rc_contains_lean_ctx(&bash) {
205 parts.push(format!("{DIM}~/.bashrc{RST}"));
206 if !rc_has_pipe_guard(&bash) && is_active_shell("~/.bashrc") {
207 needs_update.push("~/.bashrc");
208 }
209 }
210
211 let fish = home.join(".config").join("fish").join("config.fish");
212 if rc_contains_lean_ctx(&fish) {
213 parts.push(format!("{DIM}~/.config/fish/config.fish{RST}"));
214 if !rc_has_pipe_guard(&fish) && is_active_shell("~/.config/fish/config.fish") {
215 needs_update.push("~/.config/fish/config.fish");
216 }
217 }
218
219 #[cfg(windows)]
220 {
221 let ps_profile = home
222 .join("Documents")
223 .join("PowerShell")
224 .join("Microsoft.PowerShell_profile.ps1");
225 let ps_profile_legacy = home
226 .join("Documents")
227 .join("WindowsPowerShell")
228 .join("Microsoft.PowerShell_profile.ps1");
229 if rc_contains_lean_ctx(&ps_profile) {
230 parts.push(format!("{DIM}PowerShell profile{RST}"));
231 if !rc_has_pipe_guard(&ps_profile) {
232 needs_update.push("PowerShell profile");
233 }
234 } else if rc_contains_lean_ctx(&ps_profile_legacy) {
235 parts.push(format!("{DIM}WindowsPowerShell profile{RST}"));
236 if !rc_has_pipe_guard(&ps_profile_legacy) {
237 needs_update.push("WindowsPowerShell profile");
238 }
239 }
240 }
241
242 if parts.is_empty() {
243 let hint = if cfg!(windows) {
244 "no \"lean-ctx\" in PowerShell profile, ~/.zshrc or ~/.bashrc"
245 } else {
246 "no \"lean-ctx\" in ~/.zshrc, ~/.bashrc, or ~/.config/fish/config.fish"
247 };
248 Outcome {
249 ok: false,
250 line: format!("{BOLD}Shell aliases{RST} {RED}{hint}{RST}"),
251 }
252 } else if !needs_update.is_empty() {
253 Outcome {
254 ok: false,
255 line: format!(
256 "{BOLD}Shell aliases{RST} {YELLOW}outdated hook in {} — run {BOLD}lean-ctx init --global{RST}{YELLOW} to fix (pipe guard missing){RST}",
257 needs_update.join(", ")
258 ),
259 }
260 } else {
261 Outcome {
262 ok: true,
263 line: format!(
264 "{BOLD}Shell aliases{RST} {GREEN}lean-ctx referenced in {}{RST}",
265 parts.join(", ")
266 ),
267 }
268 }
269}
270
271struct McpLocation {
272 name: &'static str,
273 display: String,
274 path: PathBuf,
275}
276
277fn mcp_config_locations(home: &std::path::Path) -> Vec<McpLocation> {
278 let mut locations = vec![
279 McpLocation {
280 name: "Cursor",
281 display: "~/.cursor/mcp.json".into(),
282 path: home.join(".cursor").join("mcp.json"),
283 },
284 McpLocation {
285 name: "Claude Code",
286 display: format!(
287 "{}",
288 crate::core::editor_registry::claude_mcp_json_path(home).display()
289 ),
290 path: crate::core::editor_registry::claude_mcp_json_path(home),
291 },
292 McpLocation {
293 name: "Windsurf",
294 display: "~/.codeium/windsurf/mcp_config.json".into(),
295 path: home
296 .join(".codeium")
297 .join("windsurf")
298 .join("mcp_config.json"),
299 },
300 McpLocation {
301 name: "Codex",
302 display: {
303 let codex_dir =
304 crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
305 format!("{}/config.toml", codex_dir.display())
306 },
307 path: crate::core::home::resolve_codex_dir()
308 .unwrap_or_else(|| home.join(".codex"))
309 .join("config.toml"),
310 },
311 McpLocation {
312 name: "Gemini CLI",
313 display: "~/.gemini/settings.json".into(),
314 path: home.join(".gemini").join("settings.json"),
315 },
316 McpLocation {
317 name: "Antigravity",
318 display: "~/.gemini/antigravity/mcp_config.json".into(),
319 path: home
320 .join(".gemini")
321 .join("antigravity")
322 .join("mcp_config.json"),
323 },
324 ];
325
326 #[cfg(unix)]
327 {
328 let zed_cfg = home.join(".config").join("zed").join("settings.json");
329 locations.push(McpLocation {
330 name: "Zed",
331 display: "~/.config/zed/settings.json".into(),
332 path: zed_cfg,
333 });
334 }
335
336 locations.push(McpLocation {
337 name: "Qwen Code",
338 display: "~/.qwen/settings.json".into(),
339 path: home.join(".qwen").join("settings.json"),
340 });
341 locations.push(McpLocation {
342 name: "Trae",
343 display: "~/.trae/mcp.json".into(),
344 path: home.join(".trae").join("mcp.json"),
345 });
346 locations.push(McpLocation {
347 name: "Amazon Q",
348 display: "~/.aws/amazonq/default.json".into(),
349 path: home.join(".aws").join("amazonq").join("default.json"),
350 });
351 locations.push(McpLocation {
352 name: "JetBrains",
353 display: "~/.jb-mcp.json".into(),
354 path: home.join(".jb-mcp.json"),
355 });
356 locations.push(McpLocation {
357 name: "AWS Kiro",
358 display: "~/.kiro/settings/mcp.json".into(),
359 path: home.join(".kiro").join("settings").join("mcp.json"),
360 });
361 locations.push(McpLocation {
362 name: "Verdent",
363 display: "~/.verdent/mcp.json".into(),
364 path: home.join(".verdent").join("mcp.json"),
365 });
366 locations.push(McpLocation {
367 name: "Crush",
368 display: "~/.config/crush/crush.json".into(),
369 path: home.join(".config").join("crush").join("crush.json"),
370 });
371 locations.push(McpLocation {
372 name: "Pi",
373 display: "~/.pi/agent/mcp.json".into(),
374 path: home.join(".pi").join("agent").join("mcp.json"),
375 });
376 locations.push(McpLocation {
377 name: "Amp",
378 display: "~/.config/amp/settings.json".into(),
379 path: home.join(".config").join("amp").join("settings.json"),
380 });
381
382 {
383 #[cfg(unix)]
384 let opencode_cfg = home.join(".config").join("opencode").join("opencode.json");
385 #[cfg(unix)]
386 let opencode_display = "~/.config/opencode/opencode.json";
387
388 #[cfg(windows)]
389 let opencode_cfg = if let Ok(appdata) = std::env::var("APPDATA") {
390 std::path::PathBuf::from(appdata)
391 .join("opencode")
392 .join("opencode.json")
393 } else {
394 home.join(".config").join("opencode").join("opencode.json")
395 };
396 #[cfg(windows)]
397 let opencode_display = "%APPDATA%/opencode/opencode.json";
398
399 locations.push(McpLocation {
400 name: "OpenCode",
401 display: opencode_display.into(),
402 path: opencode_cfg,
403 });
404 }
405
406 #[cfg(target_os = "macos")]
407 {
408 let vscode_mcp = home.join("Library/Application Support/Code/User/mcp.json");
409 locations.push(McpLocation {
410 name: "VS Code",
411 display: "~/Library/Application Support/Code/User/mcp.json".into(),
412 path: vscode_mcp,
413 });
414 }
415 #[cfg(target_os = "linux")]
416 {
417 let vscode_mcp = home.join(".config/Code/User/mcp.json");
418 locations.push(McpLocation {
419 name: "VS Code",
420 display: "~/.config/Code/User/mcp.json".into(),
421 path: vscode_mcp,
422 });
423 }
424 #[cfg(target_os = "windows")]
425 {
426 if let Ok(appdata) = std::env::var("APPDATA") {
427 let vscode_mcp = std::path::PathBuf::from(appdata).join("Code/User/mcp.json");
428 locations.push(McpLocation {
429 name: "VS Code",
430 display: "%APPDATA%/Code/User/mcp.json".into(),
431 path: vscode_mcp,
432 });
433 }
434 }
435
436 locations.push(McpLocation {
437 name: "Copilot CLI",
438 display: "~/.copilot/mcp-config.json".into(),
439 path: home.join(".copilot/mcp-config.json"),
440 });
441
442 locations.push(McpLocation {
443 name: "Hermes Agent",
444 display: "~/.hermes/config.yaml".into(),
445 path: home.join(".hermes").join("config.yaml"),
446 });
447
448 {
449 let cline_path = crate::core::editor_registry::cline_mcp_path();
450 if cline_path.to_str().is_some_and(|s| s != "/nonexistent") {
451 locations.push(McpLocation {
452 name: "Cline",
453 display: cline_path.display().to_string(),
454 path: cline_path,
455 });
456 }
457 }
458 {
459 let roo_path = crate::core::editor_registry::roo_mcp_path();
460 if roo_path.to_str().is_some_and(|s| s != "/nonexistent") {
461 locations.push(McpLocation {
462 name: "Roo Code",
463 display: roo_path.display().to_string(),
464 path: roo_path,
465 });
466 }
467 }
468
469 locations
470}
471
472fn mcp_config_outcome() -> Outcome {
473 let Some(home) = dirs::home_dir() else {
474 return Outcome {
475 ok: false,
476 line: format!("{BOLD}MCP config{RST} {RED}could not resolve home directory{RST}"),
477 };
478 };
479
480 let locations = mcp_config_locations(&home);
481 let mut found: Vec<String> = Vec::new();
482 let mut exists_no_ref: Vec<String> = Vec::new();
483
484 for loc in &locations {
485 if let Ok(content) = std::fs::read_to_string(&loc.path) {
486 if has_lean_ctx_mcp_entry(&content) {
487 found.push(format!("{} {DIM}({}){RST}", loc.name, loc.display));
488 } else {
489 exists_no_ref.push(loc.name.to_string());
490 }
491 }
492 }
493
494 found.sort();
495 found.dedup();
496 exists_no_ref.sort();
497 exists_no_ref.dedup();
498
499 if !found.is_empty() {
500 Outcome {
501 ok: true,
502 line: format!(
503 "{BOLD}MCP config{RST} {GREEN}lean-ctx found in: {}{RST}",
504 found.join(", ")
505 ),
506 }
507 } else if !exists_no_ref.is_empty() {
508 let has_claude = exists_no_ref.iter().any(|n| n.starts_with("Claude Code"));
509 let cause = if has_claude {
510 format!("{DIM}(Claude Code may overwrite ~/.claude.json on startup — lean-ctx entry missing from mcpServers){RST}")
511 } else {
512 String::new()
513 };
514 let hint = if has_claude {
515 format!("{DIM}(run: lean-ctx doctor --fix OR lean-ctx init --agent claude){RST}")
516 } else {
517 format!("{DIM}(run: lean-ctx doctor --fix OR lean-ctx setup){RST}")
518 };
519 Outcome {
520 ok: false,
521 line: format!(
522 "{BOLD}MCP config{RST} {YELLOW}config exists for {} but mcpServers does not contain lean-ctx{RST} {cause} {hint}",
523 exists_no_ref.join(", "),
524 ),
525 }
526 } else {
527 Outcome {
528 ok: false,
529 line: format!(
530 "{BOLD}MCP config{RST} {YELLOW}no MCP config found{RST} {DIM}(run: lean-ctx setup){RST}"
531 ),
532 }
533 }
534}
535
536fn has_lean_ctx_mcp_entry(content: &str) -> bool {
537 if let Ok(json) = serde_json::from_str::<serde_json::Value>(content) {
538 if let Some(servers) = json.get("mcpServers").and_then(|v| v.as_object()) {
539 return servers.contains_key("lean-ctx");
540 }
541 if let Some(servers) = json
542 .get("mcp")
543 .and_then(|v| v.get("servers"))
544 .and_then(|v| v.as_object())
545 {
546 return servers.contains_key("lean-ctx");
547 }
548 }
549 content.contains("lean-ctx")
550}
551
552fn port_3333_outcome() -> Outcome {
553 match TcpListener::bind("127.0.0.1:3333") {
554 Ok(_listener) => Outcome {
555 ok: true,
556 line: format!("{BOLD}Dashboard port 3333{RST} {GREEN}available on 127.0.0.1{RST}"),
557 },
558 Err(e) => Outcome {
559 ok: false,
560 line: format!("{BOLD}Dashboard port 3333{RST} {RED}not available: {e}{RST}"),
561 },
562 }
563}
564
565fn pi_outcome() -> Option<Outcome> {
566 let pi_result = std::process::Command::new("pi").arg("--version").output();
567
568 match pi_result {
569 Ok(output) if output.status.success() => {
570 let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
571 let has_plugin = std::process::Command::new("pi")
572 .args(["list"])
573 .output()
574 .is_ok_and(|o| {
575 o.status.success() && String::from_utf8_lossy(&o.stdout).contains("pi-lean-ctx")
576 });
577
578 let has_mcp = dirs::home_dir()
579 .map(|h| h.join(".pi/agent/mcp.json"))
580 .and_then(|p| std::fs::read_to_string(p).ok())
581 .is_some_and(|c| c.contains("lean-ctx"));
582
583 if has_plugin && has_mcp {
584 Some(Outcome {
585 ok: true,
586 line: format!(
587 "{BOLD}Pi Coding Agent{RST} {GREEN}{version}, pi-lean-ctx + MCP configured{RST}"
588 ),
589 })
590 } else if has_plugin {
591 Some(Outcome {
592 ok: true,
593 line: format!(
594 "{BOLD}Pi Coding Agent{RST} {GREEN}{version}, pi-lean-ctx installed{RST} {DIM}(MCP not configured — embedded bridge active){RST}"
595 ),
596 })
597 } else {
598 Some(Outcome {
599 ok: false,
600 line: format!(
601 "{BOLD}Pi Coding Agent{RST} {YELLOW}{version}, but pi-lean-ctx not installed{RST} {DIM}(run: pi install npm:pi-lean-ctx){RST}"
602 ),
603 })
604 }
605 }
606 _ => None,
607 }
608}
609
610fn provider_outcome() -> Outcome {
611 let registry = crate::core::providers::global_registry();
612 let ids = registry.available_provider_ids();
613 if ids.is_empty() {
614 return Outcome {
615 ok: true,
616 line: format!(
617 "{BOLD}Providers{RST} {DIM}none configured (enable via [providers] in config.toml){RST}"
618 ),
619 };
620 }
621 let labels: Vec<String> = ids
622 .iter()
623 .map(|id| {
624 if let Some(p) = registry.get(id) {
625 if p.is_available() {
626 format!("{GREEN}{id}{RST}")
627 } else {
628 format!("{YELLOW}{id}(no auth){RST}")
629 }
630 } else {
631 format!("{RED}{id}(missing){RST}")
632 }
633 })
634 .collect();
635 Outcome {
636 ok: true,
637 line: format!("{BOLD}Providers{RST} {}", labels.join(", ")),
638 }
639}
640
641fn mcp_bridge_outcomes() -> Vec<Outcome> {
642 let cfg = crate::core::config::Config::load();
643 let bridges = &cfg.providers.mcp_bridges;
644 if bridges.is_empty() {
645 return Vec::new();
646 }
647
648 let mut results = Vec::new();
649
650 let auto_idx = if cfg.providers.auto_index {
651 format!("{GREEN}auto_index=true{RST}")
652 } else {
653 format!("{YELLOW}auto_index=false (provider data won't be indexed into BM25/Graph/Knowledge){RST}")
654 };
655 results.push(Outcome {
656 ok: cfg.providers.auto_index,
657 line: format!("{BOLD}Provider indexing{RST} {auto_idx}"),
658 });
659
660 for (name, entry) in bridges {
661 let url = entry.url.as_deref().unwrap_or("");
662 let cmd = entry.command.as_deref().unwrap_or("");
663 let source = if !url.is_empty() {
664 format!("url={url}")
665 } else if !cmd.is_empty() {
666 format!("cmd={cmd}")
667 } else {
668 "no url/command".to_string()
669 };
670
671 let ok = !url.is_empty() || !cmd.is_empty();
672 let status = if ok {
673 format!("{GREEN}configured{RST}")
674 } else {
675 format!("{RED}missing url/command{RST}")
676 };
677
678 results.push(Outcome {
679 ok,
680 line: format!("{BOLD}MCP Bridge{RST} mcp:{name} ({source}) [{status}]"),
681 });
682 }
683
684 results
685}
686
687fn plan_mode_outcomes() -> Vec<Outcome> {
688 let status = crate::core::editor_registry::plan_mode::check_plan_mode_status();
689 let mut results = Vec::new();
690
691 if let Some(configured) = status.vscode_configured {
692 if configured {
693 results.push(Outcome {
694 ok: true,
695 line: format!(
696 "{BOLD}Plan mode{RST} VS Code {GREEN}planAgent tools configured{RST}"
697 ),
698 });
699 } else {
700 results.push(Outcome {
701 ok: false,
702 line: format!(
703 "{BOLD}Plan mode{RST} VS Code {YELLOW}not configured{RST} {DIM}(run: lean-ctx setup){RST}"
704 ),
705 });
706 }
707 }
708
709 if let Some(configured) = status.claude_configured {
710 if configured {
711 results.push(Outcome {
712 ok: true,
713 line: format!("{BOLD}Plan mode{RST} Claude Code {GREEN}permissions present{RST}"),
714 });
715 } else {
716 results.push(Outcome {
717 ok: false,
718 line: format!(
719 "{BOLD}Plan mode{RST} Claude Code {YELLOW}not configured{RST} {DIM}(run: lean-ctx setup){RST}"
720 ),
721 });
722 }
723 }
724
725 results
726}
727
728fn session_state_outcome() -> Outcome {
729 use crate::core::session::SessionState;
730
731 match SessionState::load_latest() {
732 Some(session) => {
733 let root = session
734 .project_root
735 .as_deref()
736 .unwrap_or("(not set)");
737 let cwd = session
738 .shell_cwd
739 .as_deref()
740 .unwrap_or("(not tracked)");
741 Outcome {
742 ok: true,
743 line: format!(
744 "{BOLD}Session state{RST} {GREEN}active{RST} {DIM}root: {root}, cwd: {cwd}, v{}{RST}",
745 session.version
746 ),
747 }
748 }
749 None => Outcome {
750 ok: true,
751 line: format!(
752 "{BOLD}Session state{RST} {YELLOW}no active session{RST} {DIM}(will be created on first tool call){RST}"
753 ),
754 },
755 }
756}
757
758fn docker_env_outcomes() -> Vec<Outcome> {
759 if !crate::shell::is_container() {
760 return vec![];
761 }
762 let env_sh = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
763 |_| "/root/.lean-ctx/env.sh".to_string(),
764 |d| d.join("env.sh").to_string_lossy().to_string(),
765 );
766
767 let mut outcomes = vec![];
768
769 let shell_name = std::env::var("SHELL").unwrap_or_default();
770 let is_bash = shell_name.contains("bash") || shell_name.is_empty();
771
772 if is_bash {
773 let has_bash_env = std::env::var("BASH_ENV").is_ok();
774 outcomes.push(if has_bash_env {
775 Outcome {
776 ok: true,
777 line: format!(
778 "{BOLD}BASH_ENV{RST} {GREEN}set{RST} {DIM}({}){RST}",
779 std::env::var("BASH_ENV").unwrap_or_default()
780 ),
781 }
782 } else {
783 Outcome {
784 ok: false,
785 line: format!(
786 "{BOLD}BASH_ENV{RST} {RED}not set{RST} {YELLOW}(add to Dockerfile: ENV BASH_ENV=\"{env_sh}\"){RST}"
787 ),
788 }
789 });
790 }
791
792 let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
793 outcomes.push(if has_claude_env {
794 Outcome {
795 ok: true,
796 line: format!(
797 "{BOLD}CLAUDE_ENV_FILE{RST} {GREEN}set{RST} {DIM}({}){RST}",
798 std::env::var("CLAUDE_ENV_FILE").unwrap_or_default()
799 ),
800 }
801 } else {
802 Outcome {
803 ok: false,
804 line: format!(
805 "{BOLD}CLAUDE_ENV_FILE{RST} {RED}not set{RST} {YELLOW}(for Claude Code: ENV CLAUDE_ENV_FILE=\"{env_sh}\"){RST}"
806 ),
807 }
808 });
809
810 outcomes
811}
812
813pub fn run() {
815 let mut passed = 0u32;
816 let total = 10u32;
817
818 println!("{BOLD}{WHITE}lean-ctx doctor{RST} {DIM}diagnostics{RST}\n");
819
820 let path_bin = resolve_lean_ctx_binary();
822 let also_in_path_dirs = path_in_path_env();
823 let bin_ok = path_bin.is_some() || also_in_path_dirs;
824 if bin_ok {
825 passed += 1;
826 }
827 let bin_line = if let Some(p) = path_bin {
828 format!("{BOLD}lean-ctx in PATH{RST} {WHITE}{}{RST}", p.display())
829 } else if also_in_path_dirs {
830 format!(
831 "{BOLD}lean-ctx in PATH{RST} {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
832 )
833 } else {
834 format!("{BOLD}lean-ctx in PATH{RST} {RED}not found{RST}")
835 };
836 print_check(&Outcome {
837 ok: bin_ok,
838 line: bin_line,
839 });
840
841 let ver = if bin_ok {
843 lean_ctx_version_from_path()
844 } else {
845 Outcome {
846 ok: false,
847 line: format!("{BOLD}lean-ctx version{RST} {RED}skipped (binary not in PATH){RST}"),
848 }
849 };
850 if ver.ok {
851 passed += 1;
852 }
853 print_check(&ver);
854
855 let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
857 let dir_outcome = match &lean_dir {
858 Some(p) if p.is_dir() => {
859 passed += 1;
860 Outcome {
861 ok: true,
862 line: format!(
863 "{BOLD}data dir{RST} {GREEN}exists{RST} {DIM}{}{RST}",
864 p.display()
865 ),
866 }
867 }
868 Some(p) => Outcome {
869 ok: false,
870 line: format!(
871 "{BOLD}data dir{RST} {RED}missing or not a directory{RST} {DIM}{}{RST}",
872 p.display()
873 ),
874 },
875 None => Outcome {
876 ok: false,
877 line: format!("{BOLD}data dir{RST} {RED}could not resolve data directory{RST}"),
878 },
879 };
880 print_check(&dir_outcome);
881
882 let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
884 let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
885 Some(m) if m.is_file() => {
886 passed += 1;
887 let size = m.len();
888 let path_display = if let Some(p) = stats_path.as_ref() {
889 p.display().to_string()
890 } else {
891 String::new()
892 };
893 Outcome {
894 ok: true,
895 line: format!(
896 "{BOLD}stats.json{RST} {GREEN}exists{RST} {WHITE}{size} bytes{RST} {DIM}{path_display}{RST}",
897 ),
898 }
899 }
900 Some(_m) => {
901 let path_display = if let Some(p) = stats_path.as_ref() {
902 p.display().to_string()
903 } else {
904 String::new()
905 };
906 Outcome {
907 ok: false,
908 line: format!(
909 "{BOLD}stats.json{RST} {RED}not a file{RST} {DIM}{path_display}{RST}",
910 ),
911 }
912 }
913 None => {
914 passed += 1;
915 Outcome {
916 ok: true,
917 line: match &stats_path {
918 Some(p) => format!(
919 "{BOLD}stats.json{RST} {YELLOW}not yet created{RST} {DIM}(will appear after first use) {}{RST}",
920 p.display()
921 ),
922 None => format!("{BOLD}stats.json{RST} {RED}could not resolve path{RST}"),
923 },
924 }
925 }
926 };
927 print_check(&stats_outcome);
928
929 let split_dirs = crate::core::data_dir::all_data_dirs_with_stats();
930 if split_dirs.len() >= 2 {
931 let dirs_str = split_dirs
932 .iter()
933 .map(|d| d.display().to_string())
934 .collect::<Vec<_>>()
935 .join(", ");
936 print_check(&Outcome {
937 ok: false,
938 line: format!(
939 "{BOLD}data dir split{RST} {RED}stats.json found in {count} locations{RST}: {dirs_str} {DIM}(run: lean-ctx setup to auto-merge){RST}",
940 count = split_dirs.len(),
941 ),
942 });
943 }
944
945 let config_path = lean_dir.as_ref().map(|d| d.join("config.toml"));
947 let config_outcome = match &config_path {
948 Some(p) => match std::fs::metadata(p) {
949 Ok(m) if m.is_file() => {
950 passed += 1;
951 Outcome {
952 ok: true,
953 line: format!(
954 "{BOLD}config.toml{RST} {GREEN}exists{RST} {DIM}{}{RST}",
955 p.display()
956 ),
957 }
958 }
959 Ok(_) => Outcome {
960 ok: false,
961 line: format!(
962 "{BOLD}config.toml{RST} {RED}exists but is not a regular file{RST} {DIM}{}{RST}",
963 p.display()
964 ),
965 },
966 Err(_) => {
967 passed += 1;
968 Outcome {
969 ok: true,
970 line: format!(
971 "{BOLD}config.toml{RST} {YELLOW}not found, using defaults{RST} {DIM}(expected at {}){RST}",
972 p.display()
973 ),
974 }
975 }
976 },
977 None => Outcome {
978 ok: false,
979 line: format!("{BOLD}config.toml{RST} {RED}could not resolve path{RST}"),
980 },
981 };
982 print_check(&config_outcome);
983
984 let proxy_outcome = proxy_upstream_outcome();
986 if proxy_outcome.ok {
987 passed += 1;
988 }
989 print_check(&proxy_outcome);
990
991 let aliases = shell_aliases_outcome();
993 if aliases.ok {
994 passed += 1;
995 }
996 print_check(&aliases);
997
998 let mcp = mcp_config_outcome();
1000 if mcp.ok {
1001 passed += 1;
1002 }
1003 print_check(&mcp);
1004
1005 let skill = skill_files_outcome();
1007 if skill.ok {
1008 passed += 1;
1009 }
1010 print_check(&skill);
1011
1012 let port = port_3333_outcome();
1014 if port.ok {
1015 passed += 1;
1016 }
1017 print_check(&port);
1018
1019 #[cfg(unix)]
1021 let daemon_outcome = if crate::daemon::is_daemon_running() {
1022 let pid_path = crate::daemon::daemon_pid_path();
1023 let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
1024 Outcome {
1025 ok: true,
1026 line: format!(
1027 "{BOLD}Daemon{RST} {GREEN}running (PID {}){RST}",
1028 pid_str.trim()
1029 ),
1030 }
1031 } else {
1032 Outcome {
1033 ok: true,
1034 line: format!(
1035 "{BOLD}Daemon{RST} {YELLOW}not running{RST} {DIM}(run: lean-ctx serve -d){RST}"
1036 ),
1037 }
1038 };
1039 #[cfg(not(unix))]
1040 let daemon_outcome = Outcome {
1041 ok: true,
1042 line: format!("{BOLD}Daemon{RST} {DIM}not supported on this platform{RST}"),
1043 };
1044 if daemon_outcome.ok {
1045 passed += 1;
1046 }
1047 print_check(&daemon_outcome);
1048
1049 let provider_outcome = provider_outcome();
1051 print_check(&provider_outcome);
1052
1053 let bridge_outcomes = mcp_bridge_outcomes();
1055 for bridge_check in &bridge_outcomes {
1056 print_check(bridge_check);
1057 }
1058
1059 let plan_outcomes = plan_mode_outcomes();
1061 for plan_check in &plan_outcomes {
1062 print_check(plan_check);
1063 }
1064
1065 let session_outcome = session_state_outcome();
1067 if session_outcome.ok {
1068 passed += 1;
1069 }
1070 print_check(&session_outcome);
1071
1072 let docker_outcomes = docker_env_outcomes();
1074 for docker_check in &docker_outcomes {
1075 if docker_check.ok {
1076 passed += 1;
1077 }
1078 print_check(docker_check);
1079 }
1080
1081 let pi = pi_outcome();
1083 if let Some(ref pi_check) = pi {
1084 if pi_check.ok {
1085 passed += 1;
1086 }
1087 print_check(pi_check);
1088 }
1089
1090 let integrity = crate::core::integrity::check();
1092 let integrity_ok = integrity.seed_ok && integrity.origin_ok;
1093 if integrity_ok {
1094 passed += 1;
1095 }
1096 let integrity_line = if integrity_ok {
1097 format!(
1098 "{BOLD}Build origin{RST} {GREEN}official{RST} {DIM}{}{RST}",
1099 integrity.repo
1100 )
1101 } else {
1102 format!(
1103 "{BOLD}Build origin{RST} {RED}MODIFIED REDISTRIBUTION{RST} {YELLOW}pkg={}, repo={}{RST}",
1104 integrity.pkg_name, integrity.repo
1105 )
1106 };
1107 print_check(&Outcome {
1108 ok: integrity_ok,
1109 line: integrity_line,
1110 });
1111
1112 let cache_safety = cache_safety_outcome();
1114 if cache_safety.ok {
1115 passed += 1;
1116 }
1117 print_check(&cache_safety);
1118
1119 let claude_truncation = claude_truncation_outcome();
1121 if let Some(ref ct) = claude_truncation {
1122 if ct.ok {
1123 passed += 1;
1124 }
1125 print_check(ct);
1126 }
1127
1128 let bm25_health = bm25_cache_health_outcome();
1130 if bm25_health.ok {
1131 passed += 1;
1132 }
1133 print_check(&bm25_health);
1134
1135 let mem_profile = memory_profile_outcome();
1137 passed += 1;
1138 print_check(&mem_profile);
1139
1140 let mem_cleanup = memory_cleanup_outcome();
1142 passed += 1;
1143 print_check(&mem_cleanup);
1144
1145 let ram_outcome = ram_guardian_outcome();
1147 if ram_outcome.ok {
1148 passed += 1;
1149 }
1150 print_check(&ram_outcome);
1151
1152 let proxy_health = proxy_health_outcome();
1154 if proxy_health.ok {
1155 passed += 1;
1156 }
1157 print_check(&proxy_health);
1158
1159 let stale_env = stale_proxy_env_outcome();
1161 if let Some(ref check) = stale_env {
1162 if check.ok {
1163 passed += 1;
1164 }
1165 print_check(check);
1166 }
1167
1168 println!("\n {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
1170 let lsp_outcomes = lsp_server_outcomes();
1171 for lsp_check in &lsp_outcomes {
1172 print_check(lsp_check);
1173 }
1174
1175 let mut effective_total = total + 9; effective_total += docker_outcomes.len() as u32;
1177 if pi.is_some() {
1178 effective_total += 1;
1179 }
1180 if claude_truncation.is_some() {
1181 effective_total += 1;
1182 }
1183 if stale_env.is_some() {
1184 effective_total += 1;
1185 }
1186 println!();
1187 println!(" {BOLD}{WHITE}Summary:{RST} {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
1188 println!(" {DIM}LSP servers are optional enhancements (not counted in score){RST}");
1189 println!(" {DIM}{}{RST}", crate::core::integrity::origin_line());
1190}
1191
1192fn skill_files_outcome() -> Outcome {
1193 let Some(home) = dirs::home_dir() else {
1194 return Outcome {
1195 ok: false,
1196 line: format!("{BOLD}SKILL.md{RST} {RED}could not resolve home directory{RST}"),
1197 };
1198 };
1199
1200 let candidates = [
1201 ("Claude Code", home.join(".claude/skills/lean-ctx/SKILL.md")),
1202 ("Cursor", home.join(".cursor/skills/lean-ctx/SKILL.md")),
1203 (
1204 "Codex CLI",
1205 crate::core::home::resolve_codex_dir()
1206 .unwrap_or_else(|| home.join(".codex"))
1207 .join("skills/lean-ctx/SKILL.md"),
1208 ),
1209 (
1210 "GitHub Copilot",
1211 home.join(".copilot/skills/lean-ctx/SKILL.md"),
1212 ),
1213 ];
1214
1215 let mut found: Vec<&str> = Vec::new();
1216 for (name, path) in &candidates {
1217 if path.exists() {
1218 found.push(name);
1219 }
1220 }
1221
1222 if found.is_empty() {
1223 Outcome {
1224 ok: false,
1225 line: format!(
1226 "{BOLD}SKILL.md{RST} {YELLOW}not installed{RST} {DIM}(run: lean-ctx setup){RST}"
1227 ),
1228 }
1229 } else {
1230 Outcome {
1231 ok: true,
1232 line: format!(
1233 "{BOLD}SKILL.md{RST} {GREEN}installed for {}{RST}",
1234 found.join(", ")
1235 ),
1236 }
1237 }
1238}
1239
1240fn proxy_health_outcome() -> Outcome {
1241 use crate::core::config::Config;
1242
1243 let cfg = Config::load();
1244 let port = crate::proxy_setup::default_port();
1245
1246 match cfg.proxy_enabled {
1247 Some(true) => {
1248 let installed = crate::proxy_autostart::is_installed();
1249 let reachable = std::net::TcpStream::connect_timeout(
1250 &format!("127.0.0.1:{port}")
1251 .parse()
1252 .expect("BUG: invalid hardcoded address"),
1253 std::time::Duration::from_millis(200),
1254 )
1255 .is_ok();
1256
1257 if installed && reachable {
1258 Outcome {
1259 ok: true,
1260 line: format!(
1261 "{BOLD}Proxy{RST} {GREEN}enabled, running on port {port}{RST}"
1262 ),
1263 }
1264 } else if installed && !reachable {
1265 Outcome {
1266 ok: false,
1267 line: format!(
1268 "{BOLD}Proxy{RST} {RED}enabled but not reachable on port {port}{RST} {YELLOW}fix: lean-ctx proxy start{RST}"
1269 ),
1270 }
1271 } else {
1272 Outcome {
1273 ok: false,
1274 line: format!(
1275 "{BOLD}Proxy{RST} {RED}enabled but autostart not installed{RST} {YELLOW}fix: lean-ctx proxy enable{RST}"
1276 ),
1277 }
1278 }
1279 }
1280 Some(false) => Outcome {
1281 ok: true,
1282 line: format!(
1283 "{BOLD}Proxy{RST} {DIM}disabled (optional feature){RST} {DIM}enable: lean-ctx proxy enable{RST}"
1284 ),
1285 },
1286 None => Outcome {
1287 ok: true,
1288 line: format!(
1289 "{BOLD}Proxy{RST} {DIM}not configured{RST} {DIM}enable: lean-ctx proxy enable{RST}"
1290 ),
1291 },
1292 }
1293}
1294
1295fn stale_proxy_env_outcome() -> Option<Outcome> {
1299 use crate::core::config::Config;
1300
1301 let home = dirs::home_dir()?;
1302 let cfg = Config::load();
1303 let port = crate::proxy_setup::default_port();
1304
1305 if cfg.proxy_enabled == Some(true) {
1306 return None;
1307 }
1308
1309 let settings_dir = crate::core::editor_registry::claude_state_dir(&home);
1310 let settings_path = settings_dir.join("settings.json");
1311 let content = std::fs::read_to_string(&settings_path).ok()?;
1312 let doc: serde_json::Value = serde_json::from_str(&content).ok()?;
1313
1314 let base_url = doc
1315 .get("env")
1316 .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
1317 .and_then(|v| v.as_str())
1318 .unwrap_or("");
1319
1320 if base_url.is_empty() {
1321 return None;
1322 }
1323
1324 let local_proxy = format!("http://127.0.0.1:{port}");
1325 let is_local = base_url == local_proxy
1326 || base_url == format!("http://localhost:{port}")
1327 || base_url.starts_with("http://127.0.0.1:")
1328 || base_url.starts_with("http://localhost:");
1329
1330 if !is_local {
1331 return None;
1332 }
1333
1334 let state = if cfg.proxy_enabled == Some(false) {
1335 "disabled"
1336 } else {
1337 "not configured"
1338 };
1339
1340 Some(Outcome {
1341 ok: false,
1342 line: format!(
1343 "{BOLD}Proxy env{RST} {RED}ANTHROPIC_BASE_URL → {base_url} but proxy is {state}{RST}\n\
1344 {DIM} Claude Code routes API traffic to lean-ctx, but lean-ctx proxy is {state}.{RST}\n\
1345 {DIM} This causes 401 auth failures. Fix:{RST}\n\
1346 {YELLOW} lean-ctx proxy cleanup {DIM}(remove stale URL){RST}\n\
1347 {YELLOW} lean-ctx proxy enable {DIM}(enable the proxy){RST}"
1348 ),
1349 })
1350}
1351
1352fn proxy_upstream_outcome() -> Outcome {
1353 use crate::core::config::{is_local_proxy_url, Config, ProxyProvider};
1354
1355 let cfg = Config::load();
1356 let checks = [
1357 (
1358 "Anthropic",
1359 "proxy.anthropic_upstream",
1360 cfg.proxy.resolve_upstream(ProxyProvider::Anthropic),
1361 ),
1362 (
1363 "OpenAI",
1364 "proxy.openai_upstream",
1365 cfg.proxy.resolve_upstream(ProxyProvider::OpenAi),
1366 ),
1367 (
1368 "Gemini",
1369 "proxy.gemini_upstream",
1370 cfg.proxy.resolve_upstream(ProxyProvider::Gemini),
1371 ),
1372 ];
1373
1374 let mut custom = Vec::new();
1375 for (label, key, resolved) in &checks {
1376 if is_local_proxy_url(resolved) {
1377 return Outcome {
1378 ok: false,
1379 line: format!(
1380 "{BOLD}Proxy upstream{RST} {RED}{label} upstream points back to local proxy{RST} {YELLOW}run: lean-ctx config set {key} <url>{RST}"
1381 ),
1382 };
1383 }
1384 if !resolved.starts_with("http://") && !resolved.starts_with("https://") {
1385 return Outcome {
1386 ok: false,
1387 line: format!(
1388 "{BOLD}Proxy upstream{RST} {RED}invalid {label} upstream{RST} {YELLOW}set {key} to an http(s) URL{RST}"
1389 ),
1390 };
1391 }
1392 let is_default = matches!(
1393 *label,
1394 "Anthropic" if resolved == "https://api.anthropic.com"
1395 ) || matches!(
1396 *label,
1397 "OpenAI" if resolved == "https://api.openai.com"
1398 ) || matches!(
1399 *label,
1400 "Gemini" if resolved == "https://generativelanguage.googleapis.com"
1401 );
1402 if !is_default {
1403 custom.push(format!("{label}={resolved}"));
1404 }
1405 }
1406
1407 if custom.is_empty() {
1408 Outcome {
1409 ok: true,
1410 line: format!("{BOLD}Proxy upstream{RST} {GREEN}provider defaults{RST}"),
1411 }
1412 } else {
1413 Outcome {
1414 ok: true,
1415 line: format!(
1416 "{BOLD}Proxy upstream{RST} {GREEN}custom: {}{RST}",
1417 custom.join(", ")
1418 ),
1419 }
1420 }
1421}
1422
1423fn cache_safety_outcome() -> Outcome {
1424 use crate::core::neural::cache_alignment::CacheAlignedOutput;
1425 use crate::core::provider_cache::ProviderCacheState;
1426
1427 let mut issues = Vec::new();
1428
1429 let mut aligned = CacheAlignedOutput::new();
1430 aligned.add_stable_block("test", "stable content".into(), 1);
1431 aligned.add_variable_block("test_var", "variable content".into(), 1);
1432 let rendered = aligned.render();
1433 if rendered.find("stable content").unwrap_or(usize::MAX)
1434 > rendered.find("variable content").unwrap_or(0)
1435 {
1436 issues.push("cache_alignment: stable blocks not ordered first");
1437 }
1438
1439 let mut state = ProviderCacheState::new();
1440 let section = crate::core::provider_cache::CacheableSection::new(
1441 "doctor_test",
1442 "test content".into(),
1443 crate::core::provider_cache::SectionPriority::System,
1444 true,
1445 );
1446 state.mark_sent(§ion);
1447 if state.needs_update(§ion) {
1448 issues.push("provider_cache: hash tracking broken");
1449 }
1450
1451 if issues.is_empty() {
1452 Outcome {
1453 ok: true,
1454 line: format!(
1455 "{BOLD}Cache safety{RST} {GREEN}cache_alignment + provider_cache operational{RST}"
1456 ),
1457 }
1458 } else {
1459 Outcome {
1460 ok: false,
1461 line: format!("{BOLD}Cache safety{RST} {RED}{}{RST}", issues.join("; ")),
1462 }
1463 }
1464}
1465
1466pub(super) fn claude_binary_exists() -> bool {
1467 #[cfg(unix)]
1468 {
1469 std::process::Command::new("which")
1470 .arg("claude")
1471 .output()
1472 .is_ok_and(|o| o.status.success())
1473 }
1474 #[cfg(windows)]
1475 {
1476 std::process::Command::new("where")
1477 .arg("claude")
1478 .output()
1479 .is_ok_and(|o| o.status.success())
1480 }
1481}
1482
1483fn claude_truncation_outcome() -> Option<Outcome> {
1484 let home = dirs::home_dir()?;
1485 let claude_detected = crate::core::editor_registry::claude_mcp_json_path(&home).exists()
1486 || crate::core::editor_registry::claude_state_dir(&home).exists()
1487 || claude_binary_exists();
1488
1489 if !claude_detected {
1490 return None;
1491 }
1492
1493 let rules_path = crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md");
1494 let skill_path = home.join(".claude/skills/lean-ctx/SKILL.md");
1495
1496 let has_rules = rules_path.exists();
1497 let has_skill = skill_path.exists();
1498
1499 if has_rules && has_skill {
1500 Some(Outcome {
1501 ok: true,
1502 line: format!(
1503 "{BOLD}Claude Code instructions{RST} {GREEN}rules + skill installed{RST} {DIM}(MCP instructions capped at 2048 chars — full content via rules file){RST}"
1504 ),
1505 })
1506 } else if has_rules {
1507 Some(Outcome {
1508 ok: true,
1509 line: format!(
1510 "{BOLD}Claude Code instructions{RST} {GREEN}rules file installed{RST} {DIM}(MCP instructions capped at 2048 chars — full content via rules file){RST}"
1511 ),
1512 })
1513 } else {
1514 Some(Outcome {
1515 ok: false,
1516 line: format!(
1517 "{BOLD}Claude Code instructions{RST} {YELLOW}MCP instructions truncated at 2048 chars, no rules file found{RST} {DIM}(run: lean-ctx init --agent claude){RST}"
1518 ),
1519 })
1520 }
1521}
1522
1523fn bm25_cache_health_outcome() -> Outcome {
1524 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1525 return Outcome {
1526 ok: true,
1527 line: format!("{BOLD}BM25 cache{RST} {DIM}skipped (no data dir){RST}"),
1528 };
1529 };
1530
1531 let vectors_dir = data_dir.join("vectors");
1532 let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
1533 return Outcome {
1534 ok: true,
1535 line: format!("{BOLD}BM25 cache{RST} {GREEN}no vector dirs{RST}"),
1536 };
1537 };
1538
1539 let max_bytes = crate::core::config::Config::load().bm25_max_cache_mb * 1024 * 1024;
1540 let warn_bytes = 100 * 1024 * 1024; let mut total_dirs = 0u32;
1542 let mut total_bytes = 0u64;
1543 let mut oversized: Vec<(String, u64)> = Vec::new();
1544 let mut warnings: Vec<(String, u64)> = Vec::new();
1545 let mut quarantined_count = 0u32;
1546
1547 for entry in entries.flatten() {
1548 let dir = entry.path();
1549 if !dir.is_dir() {
1550 continue;
1551 }
1552 total_dirs += 1;
1553
1554 if dir.join("bm25_index.json.quarantined").exists()
1555 || dir.join("bm25_index.bin.quarantined").exists()
1556 || dir.join("bm25_index.bin.zst.quarantined").exists()
1557 {
1558 quarantined_count += 1;
1559 }
1560
1561 let index_path = if dir.join("bm25_index.bin.zst").exists() {
1562 dir.join("bm25_index.bin.zst")
1563 } else if dir.join("bm25_index.bin").exists() {
1564 dir.join("bm25_index.bin")
1565 } else {
1566 dir.join("bm25_index.json")
1567 };
1568 if let Ok(meta) = std::fs::metadata(&index_path) {
1569 let size = meta.len();
1570 total_bytes += size;
1571 let display = index_path.display().to_string();
1572 if size > max_bytes {
1573 oversized.push((display, size));
1574 } else if size > warn_bytes {
1575 warnings.push((display, size));
1576 }
1577 }
1578 }
1579
1580 if !oversized.is_empty() {
1581 let details: Vec<String> = oversized
1582 .iter()
1583 .map(|(p, s)| format!("{p} ({:.1} GB)", *s as f64 / 1_073_741_824.0))
1584 .collect();
1585 return Outcome {
1586 ok: false,
1587 line: format!(
1588 "{BOLD}BM25 cache{RST} {RED}{} index(es) exceed limit ({:.0} MB){RST}: {} {DIM}(run: lean-ctx cache prune){RST}",
1589 oversized.len(),
1590 max_bytes / (1024 * 1024),
1591 details.join(", ")
1592 ),
1593 };
1594 }
1595
1596 if !warnings.is_empty() {
1597 let details: Vec<String> = warnings
1598 .iter()
1599 .map(|(p, s)| format!("{p} ({:.0} MB)", *s as f64 / 1_048_576.0))
1600 .collect();
1601 return Outcome {
1602 ok: true,
1603 line: format!(
1604 "{BOLD}BM25 cache{RST} {YELLOW}{} large index(es) (>100 MB){RST}: {} {DIM}(consider extra_ignore_patterns){RST}",
1605 warnings.len(),
1606 details.join(", ")
1607 ),
1608 };
1609 }
1610
1611 let quarantine_note = if quarantined_count > 0 {
1612 format!(" {YELLOW}{quarantined_count} quarantined (run: lean-ctx cache prune){RST}")
1613 } else {
1614 String::new()
1615 };
1616
1617 Outcome {
1618 ok: true,
1619 line: format!(
1620 "{BOLD}BM25 cache{RST} {GREEN}{total_dirs} index(es), {:.1} MB total{RST}{quarantine_note}",
1621 total_bytes as f64 / 1_048_576.0
1622 ),
1623 }
1624}
1625
1626pub fn run_compact() {
1627 let (passed, total) = compact_score();
1628 print_compact_status(passed, total);
1629}
1630
1631pub fn run_cli(args: &[String]) -> i32 {
1632 let (sub, rest) = match args.first().map(String::as_str) {
1633 Some("integrations") => ("integrations", &args[1..]),
1634 _ => ("", args),
1635 };
1636
1637 let fix = rest.iter().any(|a| a == "--fix");
1638 let json = rest.iter().any(|a| a == "--json");
1639 let help = rest.iter().any(|a| a == "--help" || a == "-h");
1640
1641 if help {
1642 println!("Usage:");
1643 println!(" lean-ctx doctor");
1644 println!(" lean-ctx doctor integrations [--json]");
1645 println!(" lean-ctx doctor --fix [--json]");
1646 return 0;
1647 }
1648
1649 if sub == "integrations" {
1650 if fix {
1651 let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
1652 }
1653 return integrations::run_integrations(&integrations::IntegrationsOptions { json });
1654 }
1655
1656 if !fix {
1657 run();
1658 return 0;
1659 }
1660
1661 match fix::run_fix(&fix::DoctorFixOptions { json }) {
1662 Ok(code) => code,
1663 Err(e) => {
1664 tracing::error!("doctor --fix failed: {e}");
1665 2
1666 }
1667 }
1668}
1669
1670pub fn compact_score() -> (u32, u32) {
1671 let mut passed = 0u32;
1672 let total = 6u32;
1673
1674 if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
1675 passed += 1;
1676 }
1677 let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
1678 if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
1679 passed += 1;
1680 }
1681 if lean_dir
1682 .as_ref()
1683 .map(|d| d.join("stats.json"))
1684 .and_then(|p| std::fs::metadata(p).ok())
1685 .is_some_and(|m| m.is_file())
1686 {
1687 passed += 1;
1688 }
1689 if shell_aliases_outcome().ok {
1690 passed += 1;
1691 }
1692 if mcp_config_outcome().ok {
1693 passed += 1;
1694 }
1695 if skill_files_outcome().ok {
1696 passed += 1;
1697 }
1698
1699 (passed, total)
1700}
1701
1702pub(super) fn print_compact_status(passed: u32, total: u32) {
1703 let status = if passed == total {
1704 format!("{GREEN}✓ All {total} checks passed{RST}")
1705 } else {
1706 format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
1707 };
1708 println!(" {status}");
1709}
1710
1711fn memory_profile_outcome() -> Outcome {
1712 let cfg = crate::core::config::Config::load();
1713 let profile = crate::core::config::MemoryProfile::effective(&cfg);
1714 let (label, detail) = match profile {
1715 crate::core::config::MemoryProfile::Low => {
1716 ("low", "embeddings+semantic cache disabled, BM25 64 MB")
1717 }
1718 crate::core::config::MemoryProfile::Balanced => {
1719 ("balanced", "default — BM25 128 MB, single embedding engine")
1720 }
1721 crate::core::config::MemoryProfile::Performance => {
1722 ("performance", "full caches, BM25 512 MB")
1723 }
1724 };
1725 let source = if crate::core::config::MemoryProfile::from_env().is_some() {
1726 "env"
1727 } else if cfg.memory_profile != crate::core::config::MemoryProfile::default() {
1728 "config"
1729 } else {
1730 "default"
1731 };
1732 Outcome {
1733 ok: true,
1734 line: format!(
1735 "{BOLD}Memory profile{RST} {GREEN}{label}{RST} {DIM}({source}: {detail}){RST}"
1736 ),
1737 }
1738}
1739
1740fn memory_cleanup_outcome() -> Outcome {
1741 let cfg = crate::core::config::Config::load();
1742 let cleanup = crate::core::config::MemoryCleanup::effective(&cfg);
1743 let (label, detail) = match cleanup {
1744 crate::core::config::MemoryCleanup::Aggressive => (
1745 "aggressive",
1746 "cache cleared after 5 min idle, single-IDE optimized",
1747 ),
1748 crate::core::config::MemoryCleanup::Shared => (
1749 "shared",
1750 "cache retained 30 min, multi-IDE/multi-model optimized",
1751 ),
1752 };
1753 let source = if crate::core::config::MemoryCleanup::from_env().is_some() {
1754 "env"
1755 } else if cfg.memory_cleanup != crate::core::config::MemoryCleanup::default() {
1756 "config"
1757 } else {
1758 "default"
1759 };
1760 Outcome {
1761 ok: true,
1762 line: format!(
1763 "{BOLD}Memory cleanup{RST} {GREEN}{label}{RST} {DIM}({source}: {detail}){RST}"
1764 ),
1765 }
1766}
1767
1768fn ram_guardian_outcome() -> Outcome {
1769 let Some(snap) = crate::core::memory_guard::MemorySnapshot::capture() else {
1770 return Outcome {
1771 ok: true,
1772 line: format!(
1773 "{BOLD}RAM Guardian{RST} {YELLOW}not available{RST} {DIM}(platform unsupported){RST}"
1774 ),
1775 };
1776 };
1777 let allocator = if cfg!(all(feature = "jemalloc", not(windows))) {
1778 "jemalloc"
1779 } else {
1780 "system"
1781 };
1782 let ok = snap.pressure_level == crate::core::memory_guard::PressureLevel::Normal;
1783 let color = if ok { GREEN } else { RED };
1784 Outcome {
1785 ok,
1786 line: format!(
1787 "{BOLD}RAM Guardian{RST} {color}{:.0} MB{RST} / {:.1} GB system ({:.1}%) {DIM}limit: {:.0} MB ({allocator}){RST}",
1788 snap.rss_bytes as f64 / 1_048_576.0,
1789 snap.system_ram_bytes as f64 / 1_073_741_824.0,
1790 snap.rss_percent,
1791 snap.rss_limit_bytes as f64 / 1_048_576.0,
1792 ),
1793 }
1794}
1795
1796fn lsp_server_outcomes() -> Vec<Outcome> {
1797 use crate::lsp::config::{find_binary_in_path, KNOWN_SERVERS};
1798
1799 KNOWN_SERVERS
1800 .iter()
1801 .map(|info| {
1802 let found = find_binary_in_path(info.binary);
1803 match found {
1804 Some(path) => Outcome {
1805 ok: true,
1806 line: format!(
1807 "{BOLD}{}{RST} {GREEN}✓ {}{RST} {DIM}{}{RST}",
1808 info.language,
1809 info.binary,
1810 path.display()
1811 ),
1812 },
1813 None => Outcome {
1814 ok: false,
1815 line: format!(
1816 "{BOLD}{}{RST} {DIM}not installed{RST} {YELLOW}{}{RST}",
1817 info.language, info.install_hint
1818 ),
1819 },
1820 }
1821 })
1822 .collect()
1823}
1824
1825#[cfg(test)]
1826mod tests {
1827 use super::is_active_shell_impl;
1828
1829 #[test]
1830 fn bashrc_active_on_non_windows_when_shell_empty() {
1831 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1832 }
1833
1834 #[test]
1835 fn bashrc_not_active_on_windows_when_shell_empty() {
1836 assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
1837 }
1838
1839 #[test]
1840 fn bashrc_active_when_shell_contains_bash_on_linux() {
1841 assert!(is_active_shell_impl(
1842 "~/.bashrc",
1843 "/usr/bin/bash",
1844 false,
1845 false
1846 ));
1847 }
1848
1849 #[test]
1850 fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
1851 std::env::remove_var("BASH_VERSION");
1854 assert!(!is_active_shell_impl(
1855 "~/.bashrc",
1856 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1857 true,
1858 false,
1859 ));
1860 }
1861
1862 #[test]
1863 fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
1864 assert!(!is_active_shell_impl(
1865 "~/.bashrc",
1866 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1867 true,
1868 true,
1869 ));
1870 }
1871
1872 #[test]
1873 fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
1874 assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
1875 }
1876
1877 #[test]
1878 fn zshrc_unaffected_by_powershell_flag() {
1879 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
1880 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
1881 }
1882
1883 #[test]
1884 fn bashrc_not_active_on_windows_without_powershell_detection() {
1885 std::env::remove_var("BASH_VERSION");
1888 assert!(!is_active_shell_impl(
1889 "~/.bashrc",
1890 "/usr/bin/bash",
1891 true,
1892 false,
1893 ));
1894 }
1895
1896 #[test]
1897 fn bashrc_active_on_linux() {
1898 assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
1899 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1900 }
1901}