macro_rules! println {
() => {
::std::println!()
};
($($arg:tt)*) => {
$crate::doctor::emit_line(&::std::format!($($arg)*))
};
}
mod checks;
mod common;
mod deprecations;
mod fix;
mod integrations;
mod lint_context;
mod migrate;
mod overhead;
mod report;
mod workspace_scope;
#[allow(clippy::wildcard_imports)]
use checks::*;
pub(crate) use checks::{
configured_host_coverage, empty_session_lines, shadow_hosts, shadow_status,
};
#[allow(clippy::wildcard_imports)]
use common::*;
pub use report::{HealthCheck, HealthLevel, HealthReport, health_report};
pub fn run_fix_report() -> Result<lean_ctx::core::setup_report::SetupReport, String> {
fix::fix_report()
}
pub(super) const GREEN: &str = "\x1b[32m";
pub(super) const RED: &str = "\x1b[31m";
pub(super) const BOLD: &str = "\x1b[1m";
pub(super) const RST: &str = "\x1b[0m";
pub(super) const DIM: &str = "\x1b[2m";
pub(super) const WHITE: &str = "\x1b[97m";
pub(super) const YELLOW: &str = "\x1b[33m";
pub(super) struct Outcome {
pub ok: bool,
pub line: String,
}
enum DaemonAutostart {
Unsupported,
Off,
On(Option<std::path::PathBuf>),
}
fn unrecorded_services_outcome(lines: Option<(String, String)>) -> Option<Outcome> {
let (what, how) = lines?;
Some(Outcome {
ok: true,
line: format!("{BOLD}Unrecorded services{RST} {YELLOW}{what}{RST} {DIM}{how}{RST}"),
})
}
fn daemon_outcome(running_pid: Option<u32>, autostart: &DaemonAutostart) -> Outcome {
let autostart_tag = match autostart {
DaemonAutostart::On(Some(p)) => format!(" {DIM}[autostart: on — {}]{RST}", p.display()),
DaemonAutostart::On(None) => format!(" {DIM}[autostart: on]{RST}"),
DaemonAutostart::Off | DaemonAutostart::Unsupported => String::new(),
};
let line = if let Some(pid) = running_pid {
format!("{BOLD}Daemon{RST} {GREEN}running (PID {pid}){RST}{autostart_tag}")
} else {
let hint = match autostart {
DaemonAutostart::On(_) => format!("{DIM}(autostart enabled, will restart){RST}"),
DaemonAutostart::Off => {
format!("{DIM}(run: lean-ctx daemon start or: lean-ctx daemon enable){RST}")
}
DaemonAutostart::Unsupported => {
format!("{DIM}(run: lean-ctx daemon start — editors also start it on demand){RST}")
}
};
format!("{BOLD}Daemon{RST} {YELLOW}not running{RST} {hint}")
};
Outcome { ok: true, line }
}
fn cloud_sync_outcome(cloud_connected: bool, autostart: &DaemonAutostart) -> Option<Outcome> {
if !cloud_connected {
return None;
}
match autostart {
DaemonAutostart::On(_) => Some(Outcome {
ok: true,
line: format!(
"{BOLD}LeanCTX Cloud sync{RST} {GREEN}in the background (supervised daemon){RST}"
),
}),
DaemonAutostart::Off => Some(Outcome {
ok: false,
line: format!(
"{BOLD}LeanCTX Cloud sync{RST} {YELLOW}needs a supervised daemon{RST} {DIM}(run: lean-ctx daemon enable){RST}"
),
}),
DaemonAutostart::Unsupported => None,
}
}
#[derive(Default)]
struct Scoreboard {
json_mode: bool,
entries: Vec<JsonCheck>,
}
#[derive(Default, serde::Serialize)]
struct JsonCheck {
ok: bool,
name: String,
scored: bool,
needs_attention: bool,
#[serde(skip_serializing_if = "Option::is_none")]
advice: Option<Advice>,
}
impl JsonCheck {
fn new(ok: bool, name: String, scored: bool) -> Self {
Self {
ok,
name,
scored,
needs_attention: scored && !ok,
advice: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub(crate) struct Advice {
pub id: &'static str,
pub title: String,
pub severity: Severity,
pub detail: String,
pub actions: Vec<FixAction>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub(crate) struct FixAction {
pub label: String,
pub changes: String,
pub commands: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Summary {
passed: u32,
total: u32,
needs_attention: u32,
optional: u32,
}
fn summarize(entries: &[JsonCheck]) -> Summary {
let count = |keep: fn(&JsonCheck) -> bool| {
u32::try_from(entries.iter().filter(|entry| keep(entry)).count()).unwrap_or(u32::MAX)
};
Summary {
passed: count(|entry| entry.scored && entry.ok),
total: count(|entry| entry.scored),
needs_attention: count(|entry| entry.needs_attention),
optional: count(|entry| !entry.scored && !entry.ok),
}
}
fn strip_ansi(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut in_escape = false;
for c in s.chars() {
if c == '\x1b' {
in_escape = true;
} else if in_escape {
if c.is_ascii_alphabetic() {
in_escape = false;
}
} else {
result.push(c);
}
}
result
}
pub(crate) fn emit_line(line: &str) {
if lean_ctx::core::theme::no_color() {
::std::println!("{}", strip_ansi(line));
} else {
::std::println!("{line}");
}
}
impl Scoreboard {
fn new(json_mode: bool) -> Self {
Self {
json_mode,
entries: Vec::new(),
}
}
fn check(&mut self, outcome: &Outcome) {
self.entries
.push(JsonCheck::new(outcome.ok, strip_ansi(&outcome.line), true));
if !self.json_mode {
print_check(outcome, true);
}
}
fn check_advised(&mut self, outcome: &Outcome, advice: Option<Advice>) {
if !self.json_mode {
print_check(outcome, true);
if let Some(advice) = &advice {
print_advice(advice);
}
}
let mut entry = JsonCheck::new(outcome.ok, strip_ansi(&outcome.line), true);
entry.advice = advice;
self.entries.push(entry);
}
fn info(&mut self, outcome: &Outcome) {
self.entries
.push(JsonCheck::new(outcome.ok, strip_ansi(&outcome.line), false));
if !self.json_mode {
print_check(outcome, false);
}
}
fn note(&mut self, outcome: &Outcome) {
self.entries.push(JsonCheck::new(
outcome.ok,
strip_ansi(outcome.line.trim()),
false,
));
if !self.json_mode {
println!("{}", outcome.line);
}
}
fn summary(&self) -> Summary {
summarize(&self.entries)
}
fn report_json(&self) -> serde_json::Value {
let summary = self.summary();
serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
"build": lean_ctx::core::integrity::build().to_json(),
"passed": summary.passed,
"total": summary.total,
"needs_attention": summary.needs_attention,
"optional": summary.optional,
"checks": self.entries,
})
}
fn summary_lines(&self) -> Vec<String> {
let Summary {
passed,
total,
needs_attention,
optional,
} = self.summary();
let mut lines = vec![format!(
" {BOLD}{WHITE}Summary:{RST} {GREEN}{passed}{RST}{DIM}/{total}{RST} checks passed"
)];
if needs_attention > 0 {
lines.push(format!(
" {YELLOW}{needs_attention} check(s) need attention.{RST} Auto-repair what's fixable: {BOLD}lean-ctx doctor --fix{RST}"
));
} else {
lines.push(format!(" {GREEN}Everything looks good.{RST}"));
}
if optional > 0 {
lines.push(format!(
" {DIM}{optional} optional item(s) marked – are not set up (not counted in score){RST}"
));
}
lines
}
}
const STUCK_REQUEST_AFTER: std::time::Duration = std::time::Duration::from_secs(30);
fn request_ledger_outcomes(
snapshots: &[lean_ctx::core::request_ledger::RequestLedgerSnapshot],
now_ms: u64,
) -> Vec<Outcome> {
snapshots
.iter()
.map(|snapshot| {
let stuck = snapshot
.oldest_pending_age(now_ms)
.is_some_and(|age| age >= STUCK_REQUEST_AFTER);
let colour = if stuck { YELLOW } else { DIM };
Outcome {
ok: !stuck,
line: format!(
"{BOLD}Requests{RST} {colour}{}{RST}",
snapshot.render(now_ms)
),
}
})
.collect()
}
fn daemon_diagnostic_notes() -> Vec<Outcome> {
let mut notes = Vec::new();
#[cfg(target_os = "linux")]
if lean_ctx::daemon_autostart::controls_user_services() {
if let Ok(o) = std::process::Command::new("systemctl")
.args(["--user", "is-active", "lean-ctx-daemon.service"])
.output()
{
let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
if state != "active" {
notes.push(Outcome {
ok: false,
line: format!(
" {DIM} systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
),
});
}
}
let username = std::env::var("USER")
.or_else(|_| std::env::var("LOGNAME"))
.unwrap_or_else(|_| "$(whoami)".to_string());
if let Ok(o) = std::process::Command::new("loginctl")
.args(["show-user", &username, "-p", "Linger", "--value"])
.output()
{
let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
if val != "yes" {
notes.push(Outcome {
ok: false,
line: format!(
" {YELLOW}⚠{RST} Linger not enabled — daemon won't start at boot without login\n {DIM}Fix: loginctl enable-linger {username}{RST}"
),
});
}
}
}
if let Some(log_path) = lean_ctx::core::startup_guard::crash_loop_log_path(
lean_ctx::core::startup_guard::MCP_PROCESS_NAME,
) && log_path.exists()
&& let Ok(contents) = std::fs::read_to_string(&log_path)
{
let lines: Vec<&str> = contents.lines().collect();
if lines.len() >= 5 {
notes.push(Outcome {
ok: false,
line: format!(
" {YELLOW}⚠{RST} Crash-loop log: {} recent restarts {DIM}({}){RST}",
lines.len(),
display_user_path(&log_path)
),
});
}
}
notes
}
pub fn run() -> u32 {
run_inner(false)
}
pub fn run_json() -> u32 {
run_inner(true)
}
fn run_inner(json: bool) -> u32 {
let mut board = Scoreboard::new(json);
if !json {
println!("{BOLD}{WHITE}lean-ctx doctor{RST} {DIM}diagnostics{RST}\n");
}
let path_bin = resolve_lean_ctx_binary();
let also_in_path_dirs = path_in_path_env();
let bin_ok = path_bin.is_some() || also_in_path_dirs;
let bin_line = if let Some(p) = path_bin {
format!("{BOLD}lean-ctx in PATH{RST} {WHITE}{}{RST}", p.display())
} else if also_in_path_dirs {
format!(
"{BOLD}lean-ctx in PATH{RST} {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
)
} else {
format!("{BOLD}lean-ctx in PATH{RST} {RED}not found{RST}")
};
board.check(&Outcome {
ok: bin_ok,
line: bin_line,
});
let ver = if bin_ok {
lean_ctx_version_from_path()
} else {
Outcome {
ok: false,
line: format!("{BOLD}lean-ctx version{RST} {RED}skipped (binary not in PATH){RST}"),
}
};
board.check(&ver);
let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
let dir_outcome = match &lean_dir {
Some(p) if p.is_dir() => Outcome {
ok: true,
line: format!(
"{BOLD}data dir{RST} {GREEN}exists{RST} {DIM}{}{RST}",
p.display()
),
},
Some(p) if !p.exists() => Outcome {
ok: true,
line: format!(
"{BOLD}data dir{RST} {WHITE}not yet created{RST} {DIM}(will appear after first use) {}{RST}",
p.display()
),
},
Some(p) => Outcome {
ok: false,
line: format!(
"{BOLD}data dir{RST} {RED}not a directory{RST} {DIM}{}{RST}",
p.display()
),
},
None => Outcome {
ok: false,
line: format!("{BOLD}data dir{RST} {RED}could not resolve data directory{RST}"),
},
};
board.check(&dir_outcome);
let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
Some(m) if m.is_file() => {
let size = m.len();
let path_display = if let Some(p) = stats_path.as_ref() {
p.display().to_string()
} else {
String::new()
};
Outcome {
ok: true,
line: format!(
"{BOLD}stats.json{RST} {GREEN}exists{RST} {WHITE}{size} bytes{RST} {DIM}{path_display}{RST}",
),
}
}
Some(_m) => {
let path_display = if let Some(p) = stats_path.as_ref() {
p.display().to_string()
} else {
String::new()
};
Outcome {
ok: false,
line: format!(
"{BOLD}stats.json{RST} {RED}not a file{RST} {DIM}{path_display}{RST}",
),
}
}
None => Outcome {
ok: true,
line: match &stats_path {
Some(p) => format!(
"{BOLD}stats.json{RST} {WHITE}not yet created{RST} {DIM}(will appear after first use) {}{RST}",
p.display()
),
None => format!("{BOLD}stats.json{RST} {RED}could not resolve path{RST}"),
},
},
};
board.check(&stats_outcome);
let split_dirs = lean_ctx::core::data_dir::all_data_dirs_with_stats();
if split_dirs.len() >= 2 {
let dirs_str = split_dirs
.iter()
.map(|d| d.display().to_string())
.collect::<Vec<_>>()
.join(", ");
board.check(&Outcome {
ok: false,
line: format!(
"{BOLD}data dir split{RST} {RED}stats.json found in {count} locations{RST}: {dirs_str} {DIM}(run: lean-ctx doctor --fix to merge){RST}",
count = split_dirs.len(),
),
});
}
if let Some((src, n)) = lean_ctx::core::xdg_migrate::pending() {
board.check(&Outcome {
ok: false,
line: format!(
"{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}",
src.display()
),
});
}
if let Some(stray) = lean_ctx::core::config_heal::pending() {
board.check(&Outcome {
ok: false,
line: format!(
"{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}",
stray.display()
),
});
}
{
let pinned = lean_ctx::core::layout_pin::is_xdg_pinned();
let residual = lean_ctx::core::xdg_migrate::residual_legacy_present();
let line = if pinned && residual {
format!(
"{BOLD}layout{RST} {GREEN}xdg-pinned{RST} {YELLOW}residual ~/.lean-ctx present{RST} {DIM}(auto-reclaimed on next start){RST}"
)
} else if pinned {
format!(
"{BOLD}layout{RST} {GREEN}xdg-pinned{RST} {DIM}(~/.lean-ctx can no longer hijack this install){RST}"
)
} else {
format!(
"{BOLD}layout{RST} {WHITE}single-dir / legacy{RST} {DIM}(run: lean-ctx doctor --fix to commit to XDG){RST}"
)
};
board.check(&Outcome { ok: true, line });
}
let config_path = lean_ctx::core::config::Config::path();
let config_outcome = match &config_path {
Some(p) => match std::fs::metadata(p) {
Ok(m) if m.is_file() => Outcome {
ok: true,
line: format!(
"{BOLD}config.toml{RST} {GREEN}exists{RST} {DIM}{}{RST}",
p.display()
),
},
Ok(_) => Outcome {
ok: false,
line: format!(
"{BOLD}config.toml{RST} {RED}exists but is not a regular file{RST} {DIM}{}{RST}",
p.display()
),
},
Err(_) => Outcome {
ok: true,
line: format!(
"{BOLD}config.toml{RST} {WHITE}not found, using defaults{RST} {DIM}(expected at {}){RST}",
p.display()
),
},
},
None => Outcome {
ok: false,
line: format!("{BOLD}config.toml{RST} {RED}could not resolve path{RST}"),
},
};
board.check(&config_outcome);
if let Some(outcome) = config_path
.as_deref()
.and_then(config_migration_pause_outcome)
{
board.check(&outcome);
}
board.check(&config_parity_outcome());
board.check(&project_pin_outcome());
let allowlist_outcome = shell_allowlist_outcome();
board.check(&allowlist_outcome);
if let Some(upgrade) = shell_allowlist_upgrade_advisory_outcome() {
board.check(&upgrade);
}
if let Some(shadowing) = shell_allowlist_shadowing_outcome() {
board.check(&shadowing);
}
let path_jail = path_jail_outcome();
board.check(&path_jail);
let workspace_trust = workspace_trust_outcome();
board.check(&workspace_trust);
let secret_detection = secret_detection_outcome();
board.check(&secret_detection);
let context_gateway = context_gateway_outcome();
board.check(&context_gateway);
if let Some(managed_bins) = managed_addon_binaries_outcome() {
board.check(&managed_bins);
}
if let Some(managed_ort) = managed_ort_outcome() {
board.check(&managed_ort);
}
let cognition = cognition_activity_outcome();
board.check(&cognition);
let passthrough_outcome = compact_format_passthrough_outcome();
board.check(&passthrough_outcome);
let perm_inherit_outcome = permission_inheritance_outcome();
board.check(&perm_inherit_outcome);
let proxy_outcome = proxy_upstream_outcome();
board.check(&proxy_outcome);
let setup_pending = dirs::home_dir().is_some_and(|home| {
lean_ctx_mcp_location_names(&home).is_empty()
&& checks::configured_host_coverage(&home).is_empty()
});
if setup_pending && !json {
println!(
" {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}"
);
}
let setup_item = |board: &mut Scoreboard, outcome: &Outcome| {
if setup_pending {
board.info(outcome);
} else {
board.check(outcome);
}
};
let aliases = shell_aliases_outcome();
setup_item(&mut board, &aliases);
let agent_aliases = skip_agent_aliases_outcome();
board.check(&agent_aliases);
let mcp = mcp_config_outcome();
setup_item(&mut board, &mcp);
if let Some(tools) = lean_ctx::core::home::resolve_home_dir()
.and_then(|home| checks::claude_tool_access_outcome(&home))
{
board.check(&tools);
}
let user_scope_mcp_locations = dirs::home_dir()
.map(|home| lean_ctx_mcp_location_names(&home))
.unwrap_or_default();
if let Some(wsl_hint) = wsl_vscode_mcp_outcome() {
board.check(&wsl_hint);
}
let workspace_scope = workspace_scope::workspace_scope_outcome(&user_scope_mcp_locations);
if let Some(ref ws) = workspace_scope {
board.check(ws);
}
let skill = skill_files_outcome();
setup_item(&mut board, &skill);
board.check(&overhead::rules_channels_outcome());
if let Some(claude_mod) = checks::claude_mod_outcome() {
board.check(&claude_mod);
}
if let Some(code_mode) = checks::claude_code_mode_outcome() {
board.info(&code_mode);
}
if let Some(cloud_policy) = checks::cloud_policy_outcome() {
board.info(&cloud_policy);
}
let output_triage = output_triage_outcome();
board.check(&output_triage);
let port = port_3333_outcome();
board.check(&port);
let daemon_autostart = if lean_ctx::daemon_autostart::is_supported()
&& lean_ctx::daemon_autostart::controls_user_services()
{
if lean_ctx::daemon_autostart::is_installed() {
DaemonAutostart::On(lean_ctx::daemon_autostart::service_file_path())
} else {
DaemonAutostart::Off
}
} else {
DaemonAutostart::Unsupported
};
let daemon_pid = lean_ctx::daemon::verified_daemon().map(|daemon| daemon.pid);
board.check(&daemon_outcome(daemon_pid, &daemon_autostart));
let cloud_connected = lean_ctx_cloud::CloudStore::open()
.is_ok_and(|store| matches!(store.instance(), Ok(Some(_))));
if let Some(sync) = cloud_sync_outcome(cloud_connected, &daemon_autostart) {
board.check(&sync);
}
if let Some(unrecorded) =
unrecorded_services_outcome(lean_ctx::daemon::unrecorded_services_warning())
{
board.info(&unrecorded);
}
for note in daemon_diagnostic_notes() {
board.note(¬e);
}
for outcome in request_ledger_outcomes(
&lean_ctx::core::request_ledger::published_snapshots(),
lean_ctx::core::request_ledger::epoch_ms(),
) {
board.info(&outcome);
}
let provider_outcome = provider_outcome();
board.info(&provider_outcome);
let bridge_outcomes = mcp_bridge_outcomes();
for bridge_check in &bridge_outcomes {
board.info(bridge_check);
}
let skew_outcomes = version_skew_outcomes();
for (skew_check, advice) in skew_outcomes {
board.check_advised(&skew_check, advice);
}
let plan_outcomes = plan_mode_outcomes();
for plan_check in &plan_outcomes {
board.info(plan_check);
}
let session_outcome = session_state_outcome();
board.check(&session_outcome);
let docker_outcomes = docker_env_outcomes();
for docker_check in &docker_outcomes {
board.check(docker_check);
}
let pi = pi_outcome();
if let Some(ref pi_check) = pi {
board.check(pi_check);
}
let integrity = lean_ctx::core::integrity::check();
let integrity_ok = integrity.seed_ok && integrity.origin_ok;
let integrity_line = if integrity_ok && integrity.build.is_official() {
format!(
"{BOLD}Build origin{RST} {GREEN}official{RST} {DIM}{}{RST}",
integrity.repo
)
} else if integrity_ok {
format!(
"{BOLD}Build origin{RST} {YELLOW}{}{RST} {DIM}not a release build, {}{RST}",
integrity.build.label(),
integrity.repo
)
} else {
format!(
"{BOLD}Build origin{RST} {RED}MODIFIED REDISTRIBUTION{RST} {YELLOW}pkg={}, repo={}{RST}",
integrity.pkg_name, integrity.repo
)
};
board.check(&Outcome {
ok: integrity_ok,
line: integrity_line,
});
let cache_safety = cache_safety_outcome();
board.check(&cache_safety);
let claude_truncation = claude_truncation_outcome();
if let Some(ref ct) = claude_truncation {
record_client_item(&mut board, ct, "Claude Code", &user_scope_mcp_locations);
}
let codebuddy_truncation = codebuddy_truncation_outcome();
if let Some(ref cbt) = codebuddy_truncation {
record_client_item(&mut board, cbt, "CodeBuddy", &user_scope_mcp_locations);
}
for check in empty_session_outcomes() {
board.info(&check);
}
if let Some(ref addons) = addons_loaded_outcome() {
board.check(addons);
}
let bm25_health = bm25_cache_health_outcome();
board.check(&bm25_health);
let stats_quarantine = stats_quarantine_outcome();
board.check(&stats_quarantine);
for check in search_index_outcomes() {
board.check(&check);
}
let archive_footprint = archive_footprint_outcome();
board.check(&archive_footprint);
let mem_profile = memory_profile_outcome();
board.check(&mem_profile);
let mem_cleanup = memory_cleanup_outcome();
board.check(&mem_cleanup);
let ram_outcome = ram_guardian_outcome();
board.check(&ram_outcome);
let cap_warnings = capacity_warnings();
for cw in &cap_warnings {
board.check(cw);
}
let orphan_outcome = orphaned_knowledge_outcome();
board.check(&orphan_outcome);
let proxy_health = proxy_health_outcome();
board.check(&proxy_health);
let upstream_drift = proxy_upstream_drift_outcome();
if let Some(ref check) = upstream_drift {
board.check(check);
}
let stale_env = stale_proxy_env_outcome();
if let Some(ref check) = stale_env {
board.check(check);
}
if let Some((check, advice)) = proxy_subscription_conflict_outcome() {
board.check_advised(&check, Some(advice));
}
if let Some(ref check) = removed_routing_tiers_outcome() {
board.check(check);
}
let coverage_check = gateway_coverage_outcome();
board.check(&coverage_check);
let deprecation_check = deprecations::deprecations_outcome();
board.check(&deprecation_check);
let mcp_cwd = mcp_server_cwd_outcome();
board.check(&mcp_cwd);
if !json {
println!(
"\n {BOLD}{WHITE}Semantic intelligence (optional — LSP references + verified graph edges):{RST}"
);
}
board.info(&semantic_mode_outcome());
let lsp_outcomes = lsp_server_outcomes();
for lsp_check in &lsp_outcomes {
board.info(lsp_check);
}
for coverage in semantic_coverage_outcomes() {
board.info(&coverage);
}
let cfg = lean_ctx::core::config::Config::load();
let shell_mode = std::env::var("LEAN_CTX_SHELL_HOOK_MODE")
.ok()
.filter(|v| !v.trim().is_empty())
.or_else(|| cfg.shell_hook_mode.clone())
.unwrap_or_default();
let shell_desc = if shell_mode.trim().eq_ignore_ascii_case("deny") {
format!("{GREEN}deny{RST} {DIM}(all shell via ctx_shell){RST}")
} else {
format!(
"{YELLOW}rewrite{RST} {DIM}(unknown commands pass through raw — shell_hook_mode=deny closes this){RST}"
)
};
let shadow_hosts = dirs::home_dir()
.map(|home| checks::shadow_hosts(&home))
.unwrap_or_default();
let (shadow_state, shadow_detail) = checks::shadow_status(cfg.shadow_mode, &shadow_hosts);
let state_color = if shadow_state == "active" { GREEN } else { DIM };
let shadow_line = if shadow_state == "not active" || shadow_state == "disabled" {
format!(
"{BOLD}Shadow mode{RST} {state_color}{shadow_state}{RST} {DIM}{shadow_detail}{RST}"
)
} else {
format!(
"{BOLD}Shadow mode{RST} {state_color}{shadow_state}{RST} {DIM}{shadow_detail}{RST} shell: {shell_desc}"
)
};
if !json {
println!(" {shadow_line}");
}
let tool_profile_line = if lean_ctx_server::server::tool_visibility::explicit_profile(&cfg) {
let profile = lean_ctx::core::tool_profiles::ToolProfile::from_config(&cfg);
format!(
"{BOLD}Tool profile{RST} {WHITE}{profile}{RST} {DIM}{} + ctx_call gateway{RST}",
profile.description()
)
} else {
let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
format!(
"{BOLD}Tool profile{RST} {WHITE}lean (default){RST} {DIM}{lazy_count} lazy-core tools advertised + ctx_call gateway{RST}"
)
};
if !json {
println!(" {tool_profile_line}");
}
let cep = &lean_ctx::core::stats::load().cep;
let hit_ratio = if cep.total_cache_reads > 0 {
(cep.total_cache_hits as f64 / cep.total_cache_reads as f64) * 100.0
} else {
0.0
};
if !json {
println!(
" {BOLD}Session cache{RST} {WHITE}{} sessions{RST} {DIM}{}/{} reads cached ({hit_ratio:.0}% hit) · prove: lean-ctx verify-cache{RST}",
cep.sessions, cep.total_cache_hits, cep.total_cache_reads
);
println!(
" {BOLD}Usage{RST} {WHITE}{}{RST}",
lean_ctx::core::stats::display_calls_saved_line()
);
}
let needs_attention = board.summary().needs_attention;
if json {
println!(
"{}",
serde_json::to_string_pretty(&board.report_json()).unwrap_or_default()
);
} else {
println!();
for line in board.summary_lines() {
println!("{line}");
}
println!(" {DIM}LSP servers are optional enhancements (not counted in score){RST}");
println!(" {DIM}{}{RST}", lean_ctx::core::integrity::origin_line());
lean_ctx::core::version_check::check_background();
if let Some(banner) = lean_ctx::core::version_check::get_update_banner() {
println!();
println!("{banner}");
}
}
needs_attention
}
pub fn run_compact() {
let (passed, total) = compact_score();
print_compact_status(passed, total);
}
pub fn run_cli(args: &[String]) -> i32 {
let (sub, rest) = match args.first().map(String::as_str) {
Some("integrations") => ("integrations", &args[1..]),
Some("overhead") => ("overhead", &args[1..]),
Some("lint-context") => ("lint-context", &args[1..]),
_ => ("", args),
};
let fix = rest.iter().any(|a| a == "--fix");
let json = rest.iter().any(|a| a == "--json");
let gate = rest.iter().any(|a| a == "--gate");
let migrate_check = rest.iter().any(|a| a == "--migrate-check");
let help = rest.iter().any(|a| a == "--help" || a == "-h");
if help {
println!("Usage:");
println!(" lean-ctx doctor");
println!(
" lean-ctx doctor overhead [--json] [--gate] Fixed context cost per session (--gate: non-zero exit when over [context] budget_tokens)"
);
println!(
" lean-ctx doctor lint-context [--json] Lint injected context for low-signal/dup lines"
);
println!(" lean-ctx doctor integrations [--json]");
println!(" lean-ctx doctor --fix [--json]");
println!(" lean-ctx doctor --migrate-check [--json]");
println!();
println!(
"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."
);
return 0;
}
if sub == "overhead" {
return overhead::run_overhead(json, gate);
}
if sub == "lint-context" {
return lint_context::run_lint_context(json);
}
if migrate_check {
return migrate::run_migrate_check(json);
}
if sub == "integrations" {
if fix {
let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
}
return integrations::run_integrations(&integrations::IntegrationsOptions { json });
}
if !fix {
let needs = if json { run_json() } else { run() };
return i32::from(needs > 0);
}
match fix::run_fix(&fix::DoctorFixOptions { json }) {
Ok(code) => code,
Err(e) => {
tracing::error!("doctor --fix failed: {e}");
2
}
}
}
pub fn compact_score() -> (u32, u32) {
let mut passed = 0u32;
let total = 6u32;
if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
passed += 1;
}
let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
passed += 1;
}
if lean_dir
.as_ref()
.map(|d| d.join("stats.json"))
.and_then(|p| std::fs::metadata(p).ok())
.is_some_and(|m| m.is_file())
{
passed += 1;
}
if shell_aliases_outcome().ok {
passed += 1;
}
if mcp_config_outcome().ok {
passed += 1;
}
if skill_files_outcome().ok {
passed += 1;
}
(passed, total)
}
pub(super) fn print_compact_status(passed: u32, total: u32) {
let status = if passed == total {
format!("{GREEN}✓ All {total} checks passed{RST}")
} else {
format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
};
println!(" {status}");
}
fn config_migration_pause_outcome(config: &std::path::Path) -> Option<Outcome> {
let pause = lean_ctx::core::config::config_migration_pause_status(config)?;
Some(Outcome {
ok: false,
line: format!(
"{BOLD}config migration{RST} {YELLOW}paused ({}){RST} {DIM}{} · {}{RST} {DIM}({}){RST}",
pause.label,
pause.backup.display(),
pause.receipt.display(),
pause.action
),
})
}
fn record_client_item(
board: &mut Scoreboard,
outcome: &Outcome,
client: &str,
configured: &std::collections::BTreeSet<&'static str>,
) {
if configured.contains(client) {
board.check(outcome);
} else {
board.info(outcome);
}
}
#[cfg(test)]
mod tests {
use super::is_active_shell_impl;
use super::{DaemonAutostart, cloud_sync_outcome, daemon_outcome, unrecorded_services_outcome};
use super::{request_ledger_outcomes, strip_ansi};
#[test]
fn doctor_summary_counts_are_counts_of_the_emitted_checks() {
use super::{Outcome, Scoreboard};
let outcome = |ok: bool, line: &str| Outcome {
ok,
line: line.to_owned(),
};
let mut board = Scoreboard::new(true);
board.check(&outcome(true, "Version ok"));
board.check(&outcome(false, "Capacity [gateway receipts] CRIT"));
board.check(&outcome(false, "Claude auth"));
board.info(&outcome(false, "Plan mode VS Code not configured"));
board.info(&outcome(true, "LSP rust-analyzer"));
board.note(&outcome(true, " daemon note "));
let document = board.report_json();
let checks = document["checks"].as_array().expect("checks array");
let count = |keep: &dyn Fn(&serde_json::Value) -> bool| {
checks.iter().filter(|entry| keep(entry)).count() as u64
};
let flag = |entry: &serde_json::Value, key: &str| entry[key].as_bool().expect(key);
let scored = count(&|e| flag(e, "scored"));
let passed = count(&|e| flag(e, "scored") && flag(e, "ok"));
let attention = count(&|e| flag(e, "needs_attention"));
let optional = count(&|e| !flag(e, "scored") && !flag(e, "ok"));
assert_eq!(document["total"], scored, "{document}");
assert_eq!(document["passed"], passed, "{document}");
assert_eq!(document["needs_attention"], attention, "{document}");
assert_eq!(document["optional"], optional, "{document}");
assert_eq!((scored, passed, attention, optional), (3, 1, 2, 1));
assert_eq!(count(&|e| !flag(e, "ok")), attention + optional);
for entry in checks {
assert_eq!(
flag(entry, "needs_attention"),
flag(entry, "scored") && !flag(entry, "ok"),
"{entry}"
);
}
let text = board.summary_lines().join("\n");
let plain = strip_ansi(&text);
assert!(plain.contains("1/3 checks passed"), "{plain}");
assert!(plain.contains("2 check(s) need attention"), "{plain}");
assert!(plain.contains("1 optional item(s)"), "{plain}");
}
#[test]
fn doctor_json_carries_advice_for_the_claude_auth_and_bridge_findings() {
use super::checks::{Bridge, bridge_version_outcome, subscription_conflict};
use super::{Outcome, Scoreboard};
let mut board = Scoreboard::new(true);
board.check(&Outcome {
ok: true,
line: "Version ok".to_owned(),
});
let (auth, auth_advice) = subscription_conflict();
board.check_advised(&auth, Some(auth_advice));
let (pi, pi_advice) = bridge_version_outcome(Bridge::Pi, "3.11.2", "3.12.7");
board.check_advised(&pi, pi_advice);
let (cursor, cursor_advice) = bridge_version_outcome(Bridge::Cursor, "0.4.0", "3.12.7");
assert!(cursor.ok && cursor_advice.is_none());
board.check_advised(&cursor, cursor_advice);
let (pi_now, pi_now_advice) = bridge_version_outcome(Bridge::Pi, "3.12.7", "3.12.7");
assert!(pi_now.ok && pi_now_advice.is_none());
let document = board.report_json();
let checks = document["checks"].as_array().expect("checks array");
assert_eq!(document["needs_attention"], 2, "{document}");
for plain in [&checks[0], &checks[3]] {
let keys: Vec<&str> = plain
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
assert_eq!(keys.len(), 4, "{plain}");
assert!(plain.get("advice").is_none(), "{plain}");
}
let auth = &checks[1]["advice"];
assert_eq!(auth["id"], "claude_subscription_via_proxy");
assert_eq!(auth["title"], "Claude subscription goes through the proxy");
assert_eq!(auth["severity"], "error");
assert!(auth["detail"].as_str().unwrap().ends_with('.'), "{auth}");
let actions = auth["actions"].as_array().unwrap();
assert_eq!(actions.len(), 2, "{auth}");
assert_eq!(actions[0]["label"], "Turn off the proxy");
assert_eq!(actions[0]["commands"][0], "lean-ctx proxy disable");
assert!(
actions[0]["changes"].as_str().unwrap().contains("Codex"),
"proxy disable turns it off for every client: {auth}"
);
assert_eq!(
actions[1]["commands"].as_array().unwrap().len(),
1,
"{auth}"
);
assert_eq!(actions[1]["commands"][0], "lean-ctx proxy enable");
assert!(
actions[1]["changes"]
.as_str()
.unwrap()
.contains("ANTHROPIC_API_KEY"),
"{auth}"
);
let name = checks[1]["name"].as_str().unwrap();
assert_eq!(
name,
"Claude auth Claude subscription goes through the proxy"
);
let pi = &checks[2]["advice"];
assert_eq!(pi["id"], "bridge_version_pi");
assert_eq!(pi["severity"], "warning");
let detail = pi["detail"].as_str().unwrap();
assert!(
detail.contains("3.11.2") && detail.contains("3.12.7"),
"{pi}"
);
assert_eq!(pi["actions"][0]["label"], "Update pi-lean-ctx");
assert_eq!(
pi["actions"][0]["commands"][0],
"pi install npm:pi-lean-ctx@latest"
);
for entry in checks {
if let Some(advice) = entry.get("advice") {
for action in advice["actions"].as_array().unwrap() {
assert!(
action["changes"].as_str().unwrap().ends_with('.'),
"{action}"
);
}
}
}
}
#[test]
fn doctor_text_prints_advice_as_sentence_fixes_and_commands() {
use super::checks::subscription_conflict;
use super::common::advice_lines;
let (_, advice) = subscription_conflict();
let plain: Vec<String> = advice_lines(&advice)
.iter()
.map(|l| strip_ansi(l))
.collect();
assert!(
plain[0]
.trim()
.starts_with("Claude Code sends its requests"),
"{plain:?}"
);
assert_eq!(plain[1].trim(), "Fix it one of these ways:");
assert!(
plain[2]
.trim()
.starts_with("Turn off the proxy The proxy goes off for every client"),
"{plain:?}"
);
assert_eq!(plain[3].trim(), "$ lean-ctx proxy disable");
assert!(
plain.iter().any(|l| l.trim() == "$ lean-ctx proxy enable"),
"{plain:?}"
);
}
#[test]
fn doctor_text_prints_a_single_fix_and_a_fix_without_commands() {
use super::checks::{Bridge, bridge_version_outcome};
use super::common::advice_lines;
use super::{Advice, FixAction, Severity};
let (_, advice) = bridge_version_outcome(Bridge::Pi, "3.11.2", "3.12.7");
let plain: Vec<String> = advice_lines(&advice.expect("pi is out of step"))
.iter()
.map(|l| strip_ansi(l))
.collect();
assert_eq!(plain.len(), 3, "{plain:?}");
assert!(
plain.iter().all(|l| !l.contains("one of these ways")),
"{plain:?}"
);
assert!(
plain[1].trim().starts_with("Update pi-lean-ctx "),
"{plain:?}"
);
assert_eq!(plain[2].trim(), "$ pi install npm:pi-lean-ctx@latest");
let words_only = Advice {
id: "words_only",
title: "A step without commands".to_string(),
severity: Severity::Warning,
detail: "Only words.".to_string(),
actions: vec![FixAction {
label: "Do it by hand".to_string(),
changes: "Nothing to type.".to_string(),
commands: Vec::new(),
}],
};
let plain: Vec<String> = advice_lines(&words_only)
.iter()
.map(|l| strip_ansi(l))
.collect();
assert_eq!(plain.len(), 2, "{plain:?}");
assert!(
plain.iter().all(|l| !l.trim().starts_with('$')),
"{plain:?}"
);
}
#[test]
fn client_instructions_count_only_for_a_client_configured_with_lean_ctx() {
use super::{Outcome, Scoreboard, record_client_item};
let missing = Outcome {
ok: false,
line: "Claude Code instructions no CLAUDE.md block".to_owned(),
};
let scored = |configured: &[&'static str]| {
let mut board = Scoreboard::new(true);
record_client_item(
&mut board,
&missing,
"Claude Code",
&configured.iter().copied().collect(),
);
board.report_json()["checks"][0]["scored"].clone()
};
assert_eq!(scored(&[]), serde_json::json!(false));
assert_eq!(scored(&["Cursor"]), serde_json::json!(false));
assert_eq!(scored(&["Claude Code"]), serde_json::json!(true));
}
#[test]
fn cloud_sync_needs_a_supervised_daemon_when_connected() {
assert!(cloud_sync_outcome(false, &DaemonAutostart::Off).is_none());
assert!(cloud_sync_outcome(true, &DaemonAutostart::Unsupported).is_none());
let off = cloud_sync_outcome(true, &DaemonAutostart::Off).unwrap();
assert!(!off.ok);
assert!(off.line.contains("lean-ctx daemon enable"), "{}", off.line);
assert!(
cloud_sync_outcome(true, &DaemonAutostart::On(None))
.unwrap()
.ok
);
}
#[test]
fn request_ledger_lines_show_counters_oldest_pending_and_last_completion() {
use lean_ctx::core::request_ledger::{
CompletionRecord, Outcome as RequestOutcome, PendingRequest, RequestLedgerSnapshot,
Stage,
};
let now = 1_000_000_000;
let snapshot = RequestLedgerSnapshot {
pid: 4242,
kind: "http".into(),
generation: "gen".into(),
started_at_ms: now - 600_000,
snapshot_at_ms: now - 1_000,
admitted: 40,
completed: 36,
errored: 1,
refused: 2,
abandoned: 1,
pending: 2,
untracked_pending: 0,
oldest_pending: Some(PendingRequest {
method: "tools/call:ctx_read".into(),
stage: Stage::Handler,
admitted_at_ms: now - 74_000,
age_ms: None,
}),
last_tool_completion: Some(CompletionRecord {
method: "tools/call:ctx_search".into(),
outcome: RequestOutcome::Completed,
finished_at_ms: now - 3_000,
duration_ms: 12,
age_ms: None,
}),
last_initialize: None,
current_phase: None,
observations: lean_ctx::core::events::DetachedObservationStats::default(),
};
let lines = request_ledger_outcomes(std::slice::from_ref(&snapshot), now);
assert_eq!(lines.len(), 1);
let line = strip_ansi(&lines[0].line);
assert!(!lines[0].ok, "a 74 s pending request is flagged: {line}");
assert!(line.contains("pid 4242 (http), up 10m"), "{line}");
assert!(
line.contains(
"admitted 40 · completed 36 · errored 1 · refused 2 · abandoned 1 · pending 2"
),
"{line}"
);
assert!(
line.contains("oldest pending tools/call:ctx_read 74s in handler"),
"{line}"
);
assert!(
line.contains("last tool completion 3s ago (completed, 12ms)"),
"{line}"
);
assert!(line.contains("last initialize none yet"), "{line}");
let idle = RequestLedgerSnapshot {
pending: 0,
oldest_pending: None,
..snapshot
};
let lines = request_ledger_outcomes(&[idle], now);
assert!(lines[0].ok);
assert!(strip_ansi(&lines[0].line).contains("oldest pending none"));
}
#[test]
fn daemon_unrecorded_services_line_lists_pids_and_the_stop_command() {
assert!(unrecorded_services_outcome(None).is_none());
let outcome = unrecorded_services_outcome(Some((
"Still running, not started by this instance (left alone): proxy (PID 913).".into(),
"Stop them with: kill 913".into(),
)))
.expect("listed");
assert!(outcome.ok);
assert!(outcome.line.contains("proxy (PID 913)"), "{}", outcome.line);
assert!(outcome.line.contains("kill 913"), "{}", outcome.line);
}
#[test]
fn daemon_line_reports_real_state_without_autostart_service() {
let running = daemon_outcome(Some(36492), &DaemonAutostart::Unsupported);
assert!(running.ok);
assert!(
running.line.contains("running (PID 36492)"),
"{}",
running.line
);
assert!(!running.line.contains("not supported"));
assert!(!running.line.contains("autostart"));
let stopped = daemon_outcome(None, &DaemonAutostart::Unsupported);
assert!(stopped.line.contains("not running"), "{}", stopped.line);
assert!(stopped.line.contains("lean-ctx daemon start"));
assert!(!stopped.line.contains("daemon enable"), "{}", stopped.line);
assert!(!stopped.line.contains("not supported"));
}
#[test]
fn daemon_line_keeps_autostart_details_where_supported() {
let path = std::path::PathBuf::from("/x/com.leanctx.daemon.plist");
let on = daemon_outcome(Some(7), &DaemonAutostart::On(Some(path)));
assert!(on.line.contains("running (PID 7)"));
assert!(
on.line
.contains("autostart: on — /x/com.leanctx.daemon.plist")
);
let restarting = daemon_outcome(None, &DaemonAutostart::On(None));
assert!(restarting.line.contains("autostart enabled, will restart"));
let off = daemon_outcome(None, &DaemonAutostart::Off);
assert!(off.line.contains("lean-ctx daemon enable"));
}
#[test]
fn doctor_reports_a_paused_config_migration_with_files_and_action() {
let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
let path = lean_ctx::core::config::Config::path().expect("isolated config path");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
"# doctor paused-migration test\nterse_agent = \"full\"\n",
)
.unwrap();
assert!(super::config_migration_pause_outcome(&path).is_none());
let backup = path.with_file_name("config.toml.v4-migration.bak");
let receipt = path.with_file_name("config.toml.v4-migration.json");
std::fs::write(&backup, "tampered = true\n").unwrap();
std::fs::write(&receipt, "{ not json").unwrap();
let _ = lean_ctx::core::config::Config::load();
let outcome =
super::config_migration_pause_outcome(&path).expect("doctor reports the pause");
assert!(!outcome.ok);
assert!(
outcome.line.contains("receipt-unverifiable"),
"{}",
outcome.line
);
assert!(
outcome.line.contains("config.toml.v4-migration.bak"),
"{}",
outcome.line
);
assert!(
outcome.line.contains("config.toml.v4-migration.json"),
"{}",
outcome.line
);
assert!(
outcome.line.contains("move both out of"),
"{}",
outcome.line
);
}
fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
if limit == 0 {
return None;
}
let pct = (current as f64 / limit as f64 * 100.0) as u32;
if pct > 100 {
Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
} else if pct >= 80 {
Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
} else {
None
}
}
#[test]
fn capacity_below_80_no_warning() {
assert!(make_capacity_check("facts", 100, 200).is_none());
assert!(make_capacity_check("facts", 159, 200).is_none());
}
#[test]
fn capacity_at_80_yellow_warning() {
let result = make_capacity_check("facts", 160, 200);
assert!(result.is_some());
let (critical, msg) = result.unwrap();
assert!(!critical);
assert!(msg.contains("160/200"));
assert!(msg.contains("80%"));
}
#[test]
fn capacity_at_92_yellow_warning() {
let result = make_capacity_check("facts", 185, 200);
assert!(result.is_some());
let (critical, msg) = result.unwrap();
assert!(!critical);
assert!(msg.contains("185/200"));
assert!(msg.contains("92%"));
}
#[test]
fn capacity_at_95_is_warning_not_critical() {
let result = make_capacity_check("facts", 190, 200);
assert!(result.is_some());
let (critical, msg) = result.unwrap();
assert!(!critical, "95% is full-but-healthy, not over cap");
assert!(msg.contains("190/200"));
assert!(msg.contains("95%"));
}
#[test]
fn capacity_at_100_is_warning_not_critical() {
let result = make_capacity_check("facts", 200, 200);
assert!(result.is_some());
let (critical, _) = result.unwrap();
assert!(!critical);
}
#[test]
fn capacity_over_100_is_critical() {
let result = make_capacity_check("facts", 206, 200);
assert!(result.is_some());
let (critical, msg) = result.unwrap();
assert!(critical);
assert!(msg.contains("206/200"));
assert!(msg.contains("103%"));
}
#[test]
fn capacity_zero_limit_skipped() {
assert!(make_capacity_check("facts", 50, 0).is_none());
}
#[test]
fn bashrc_active_on_non_windows_when_shell_empty() {
assert!(is_active_shell_impl("~/.bashrc", "", false, false));
}
#[test]
fn bashrc_not_active_on_windows_when_shell_empty() {
assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
}
#[test]
fn bashrc_active_when_shell_contains_bash_on_linux() {
assert!(is_active_shell_impl(
"~/.bashrc",
"/usr/bin/bash",
false,
false
));
}
#[test]
fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
let _env_lock = lean_ctx::core::data_dir::test_env_lock();
lean_ctx::test_env::remove_var("BASH_VERSION");
assert!(!is_active_shell_impl(
"~/.bashrc",
"C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
true,
false,
));
}
#[test]
fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
assert!(!is_active_shell_impl(
"~/.bashrc",
"C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
true,
true,
));
}
#[test]
fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
}
#[test]
fn zshrc_unaffected_by_powershell_flag() {
assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
}
#[test]
fn bashrc_not_active_on_windows_without_powershell_detection() {
let _env_lock = lean_ctx::core::data_dir::test_env_lock();
lean_ctx::test_env::remove_var("BASH_VERSION");
assert!(!is_active_shell_impl(
"~/.bashrc",
"/usr/bin/bash",
true,
false,
));
}
#[test]
fn bashrc_active_on_linux() {
assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
assert!(is_active_shell_impl("~/.bashrc", "", false, false));
}
}