lean-ctx 3.8.8

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
// Auto-split from the former monolithic doctor/mod.rs.

use super::{BOLD, DIM, GREEN, Outcome, RED, RST, WHITE};
use std::path::PathBuf;

/// Human-readable byte size for doctor output (MB / KB / B).
pub(super) fn human_bytes(bytes: u64) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1} MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{bytes} B")
    }
}

/// Abbreviate the user's `$HOME` to `~` wherever it appears in `text` (#437).
/// Doctor output otherwise mixes `/home/<user>/…` and `~/…`, which is noisy and
/// forces users to redact their username before pasting a report. Matches both
/// the native and the forward-slash spelling of the home prefix; non-home
/// absolute paths (e.g. `/usr/local/bin`) are left untouched.
pub(super) fn tildify_home(text: &str) -> String {
    let Some(home) = dirs::home_dir() else {
        return text.to_string();
    };
    let home_str = home.to_string_lossy();
    let home_trimmed = home_str.trim_end_matches(['/', '\\']);
    if home_trimmed.is_empty() {
        return text.to_string();
    }
    let mut out = text.replace(home_trimmed, "~");
    let home_fwd = crate::core::protocol::display_path(home_trimmed);
    if home_fwd != home_trimmed {
        out = out.replace(&home_fwd, "~");
    }
    out
}

/// Render a single path for doctor output: `~` for `$HOME`, forward slashes, and
/// the home prefix matched only on a component boundary (so `/home/foo` never
/// turns `/home/foobar` into `~bar`). (#437)
pub(super) fn display_user_path(path: &std::path::Path) -> String {
    let normalized = crate::core::protocol::display_path(&path.to_string_lossy());
    let Some(home) = dirs::home_dir() else {
        return normalized;
    };
    let home_norm = crate::core::protocol::display_path(&home.to_string_lossy());
    let home_trimmed = home_norm.trim_end_matches('/');
    if home_trimmed.is_empty() {
        return normalized;
    }
    if normalized == home_trimmed {
        return "~".to_string();
    }
    match normalized.strip_prefix(home_trimmed) {
        Some(rest) if rest.starts_with('/') => format!("~{rest}"),
        _ => normalized,
    }
}

pub(super) fn print_check(outcome: &Outcome) {
    let mark = if outcome.ok {
        format!("{GREEN}{RST}")
    } else {
        format!("{RED}{RST}")
    };
    println!("  {mark}  {}", tildify_home(&outcome.line));
}

pub(super) fn path_in_path_env() -> bool {
    if let Ok(path) = std::env::var("PATH") {
        for dir in std::env::split_paths(&path) {
            if dir.join("lean-ctx").is_file() {
                return true;
            }
            if cfg!(windows)
                && (dir.join("lean-ctx.exe").is_file() || dir.join("lean-ctx.cmd").is_file())
            {
                return true;
            }
        }
    }
    false
}

pub(super) fn resolve_lean_ctx_binary() -> Option<PathBuf> {
    if let Ok(path) = std::env::var("PATH") {
        for dir in std::env::split_paths(&path) {
            if cfg!(windows) {
                let exe = dir.join("lean-ctx.exe");
                if exe.is_file() {
                    return Some(exe);
                }
                let cmd = dir.join("lean-ctx.cmd");
                if cmd.is_file() {
                    return Some(cmd);
                }
            } else {
                let bin = dir.join("lean-ctx");
                if bin.is_file() {
                    return Some(bin);
                }
            }
        }
    }
    None
}

pub(super) fn lean_ctx_version_from_path() -> Outcome {
    let resolved = resolve_lean_ctx_binary();
    let bin = resolved
        .clone()
        .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| "lean-ctx".into()));

    let v = env!("CARGO_PKG_VERSION");
    let note = match std::env::current_exe() {
        Ok(exe) if exe == bin => format!("{DIM}(this binary){RST}"),
        Ok(_) | Err(_) => format!("{DIM}(resolved: {}){RST}", bin.display()),
    };
    Outcome {
        ok: true,
        line: format!("{BOLD}lean-ctx version{RST}  {WHITE}lean-ctx {v}{RST}  {note}"),
    }
}

pub(super) fn rc_contains_lean_ctx(path: &PathBuf) -> bool {
    match std::fs::read_to_string(path) {
        Ok(s) => s.contains("lean-ctx"),
        Err(_) => false,
    }
}

pub(super) fn has_pipe_guard_in_content(content: &str) -> bool {
    content.contains("! -t 1")
        || content.contains("isatty stdout")
        || content.contains("IsOutputRedirected")
}

pub(super) fn rc_references_shell_hook(content: &str) -> bool {
    content.contains("lean-ctx/shell-hook.") || content.contains("lean-ctx\\shell-hook.")
}

pub(super) fn rc_has_pipe_guard(path: &PathBuf) -> bool {
    match std::fs::read_to_string(path) {
        Ok(s) => {
            if has_pipe_guard_in_content(&s) {
                return true;
            }
            if rc_references_shell_hook(&s) {
                let dirs_to_check = hook_dirs();
                for dir in &dirs_to_check {
                    for ext in &["zsh", "bash", "fish", "ps1"] {
                        let hook = dir.join(format!("shell-hook.{ext}"));
                        if let Ok(h) = std::fs::read_to_string(&hook)
                            && has_pipe_guard_in_content(&h)
                        {
                            return true;
                        }
                    }
                }
            }
            false
        }
        Err(_) => false,
    }
}

pub(super) fn hook_dirs() -> Vec<std::path::PathBuf> {
    let mut dirs = Vec::new();
    if let Ok(d) = crate::core::data_dir::lean_ctx_data_dir() {
        dirs.push(d);
    }
    if let Some(home) = dirs::home_dir() {
        let legacy = home.join(".lean-ctx");
        if !dirs.iter().any(|d| d == &legacy) {
            dirs.push(legacy);
        }
        let xdg = home.join(".config").join("lean-ctx");
        if !dirs.iter().any(|d| d == &xdg) {
            dirs.push(xdg);
        }
    }
    dirs
}

pub(super) fn is_active_shell_impl(
    rc_name: &str,
    shell: &str,
    is_windows: bool,
    is_powershell: bool,
) -> bool {
    match rc_name {
        "~/.zshrc" => shell.contains("zsh"),
        "~/.bashrc" => {
            // On Windows, .bashrc is only relevant when explicitly running
            // inside Git Bash (not PowerShell, cmd, or other Windows shells).
            // Git Bash sets $SHELL to bash.exe system-wide, which makes $SHELL
            // unreliable on Windows. We also check that the user is NOT in
            // PowerShell (PSModulePath) and NOT in plain cmd (PROMPT).
            if is_windows {
                if is_powershell {
                    return false;
                }
                // Even without PSModulePath, $SHELL containing "bash" on Windows
                // is unreliable (Git Bash sets it globally). Only flag if running
                // from an actual bash interactive session (BASH_VERSION is set).
                return std::env::var("BASH_VERSION").is_ok();
            }
            shell.contains("bash") || shell.is_empty()
        }
        "~/.config/fish/config.fish" => shell.contains("fish"),
        _ => true,
    }
}

/// Detect whether we are running inside a PowerShell session on Windows.
/// Git Bash may set `$SHELL` to bash.exe system-wide, so `$SHELL` alone
/// is not sufficient — we also need to rule out PowerShell as the actual
/// running host process.
pub(super) fn is_powershell_session() -> bool {
    std::env::var("PSModulePath").is_ok()
}

pub(super) fn is_active_shell(rc_name: &str) -> bool {
    let shell = std::env::var("SHELL").unwrap_or_default();
    is_active_shell_impl(rc_name, &shell, cfg!(windows), is_powershell_session())
}

pub(super) struct McpLocation {
    pub(super) name: &'static str,
    pub(super) display: String,
    pub(super) path: PathBuf,
}

pub(super) fn mcp_config_locations(home: &std::path::Path) -> Vec<McpLocation> {
    let mut locations = vec![
        McpLocation {
            name: "Cursor",
            display: "~/.cursor/mcp.json".into(),
            path: home.join(".cursor").join("mcp.json"),
        },
        McpLocation {
            name: "Claude Code",
            display: format!(
                "{}",
                crate::core::editor_registry::claude_mcp_json_path(home).display()
            ),
            path: crate::core::editor_registry::claude_mcp_json_path(home),
        },
        McpLocation {
            name: "CodeBuddy",
            display: format!(
                "{}",
                crate::core::editor_registry::codebuddy_mcp_json_path(home).display()
            ),
            path: crate::core::editor_registry::codebuddy_mcp_json_path(home),
        },
        McpLocation {
            name: "Windsurf",
            display: "~/.codeium/windsurf/mcp_config.json".into(),
            path: home
                .join(".codeium")
                .join("windsurf")
                .join("mcp_config.json"),
        },
        McpLocation {
            name: "Codex",
            display: {
                let codex_dir =
                    crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
                format!("{}/config.toml", codex_dir.display())
            },
            path: crate::core::home::resolve_codex_dir()
                .unwrap_or_else(|| home.join(".codex"))
                .join("config.toml"),
        },
        McpLocation {
            name: "Gemini CLI",
            display: "~/.gemini/settings.json".into(),
            path: home.join(".gemini").join("settings.json"),
        },
        McpLocation {
            name: "Antigravity",
            display: "~/.gemini/antigravity/mcp_config.json".into(),
            path: home
                .join(".gemini")
                .join("antigravity")
                .join("mcp_config.json"),
        },
        McpLocation {
            name: "Antigravity CLI",
            display: "~/.gemini/antigravity-cli/mcp_config.json".into(),
            path: home
                .join(".gemini")
                .join("antigravity-cli")
                .join("mcp_config.json"),
        },
    ];

    #[cfg(unix)]
    {
        let zed_cfg = home.join(".config").join("zed").join("settings.json");
        locations.push(McpLocation {
            name: "Zed",
            display: "~/.config/zed/settings.json".into(),
            path: zed_cfg,
        });
    }

    locations.push(McpLocation {
        name: "Qwen Code",
        display: "~/.qwen/settings.json".into(),
        path: home.join(".qwen").join("settings.json"),
    });
    locations.push(McpLocation {
        name: "Trae",
        display: "~/.trae/mcp.json".into(),
        path: home.join(".trae").join("mcp.json"),
    });
    locations.push(McpLocation {
        name: "Amazon Q",
        display: "~/.aws/amazonq/default.json".into(),
        path: home.join(".aws").join("amazonq").join("default.json"),
    });
    locations.push(McpLocation {
        name: "JetBrains",
        display: "~/.jb-mcp.json".into(),
        path: home.join(".jb-mcp.json"),
    });
    locations.push(McpLocation {
        name: "AWS Kiro",
        display: "~/.kiro/settings/mcp.json".into(),
        path: home.join(".kiro").join("settings").join("mcp.json"),
    });
    locations.push(McpLocation {
        name: "Verdent",
        display: "~/.verdent/mcp.json".into(),
        path: home.join(".verdent").join("mcp.json"),
    });
    locations.push(McpLocation {
        name: "Crush",
        display: "~/.config/crush/crush.json".into(),
        path: home.join(".config").join("crush").join("crush.json"),
    });
    locations.push(McpLocation {
        name: "Pi",
        display: "~/.pi/agent/mcp.json".into(),
        path: home.join(".pi").join("agent").join("mcp.json"),
    });
    locations.push(McpLocation {
        name: "Amp",
        display: "~/.config/amp/settings.json".into(),
        path: home.join(".config").join("amp").join("settings.json"),
    });

    {
        #[cfg(unix)]
        let opencode_cfg = home.join(".config").join("opencode").join("opencode.json");
        #[cfg(unix)]
        let opencode_display = "~/.config/opencode/opencode.json";

        #[cfg(windows)]
        let opencode_cfg = if let Ok(appdata) = std::env::var("APPDATA") {
            std::path::PathBuf::from(appdata)
                .join("opencode")
                .join("opencode.json")
        } else {
            home.join(".config").join("opencode").join("opencode.json")
        };
        #[cfg(windows)]
        let opencode_display = "%APPDATA%/opencode/opencode.json";

        locations.push(McpLocation {
            name: "OpenCode",
            display: opencode_display.into(),
            path: opencode_cfg,
        });
    }

    #[cfg(target_os = "macos")]
    {
        let vscode_mcp = home.join("Library/Application Support/Code/User/mcp.json");
        locations.push(McpLocation {
            name: "VS Code",
            display: "~/Library/Application Support/Code/User/mcp.json".into(),
            path: vscode_mcp,
        });
    }
    #[cfg(target_os = "linux")]
    {
        let user_dirs = [
            home.join(".config/Code/User"),
            home.join(".config/Code - Insiders/User"),
            home.join(".vscode-server/data/User"),
        ];
        let user_dir = user_dirs
            .iter()
            .find(|p| p.exists())
            .cloned()
            .unwrap_or_else(|| user_dirs[0].clone());
        let vscode_mcp = user_dir.join("mcp.json");
        let display = vscode_mcp.strip_prefix(home).unwrap_or(&vscode_mcp);
        let display_str = format!("~/{}", display.display());
        locations.push(McpLocation {
            name: "VS Code",
            display: display_str,
            path: vscode_mcp,
        });
    }
    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            let vscode_mcp = std::path::PathBuf::from(appdata).join("Code/User/mcp.json");
            locations.push(McpLocation {
                name: "VS Code",
                display: "%APPDATA%/Code/User/mcp.json".into(),
                path: vscode_mcp,
            });
        }
    }

    locations.push(McpLocation {
        name: "Copilot CLI",
        display: "~/.copilot/mcp-config.json".into(),
        path: home.join(".copilot/mcp-config.json"),
    });

    locations.push(McpLocation {
        name: "Hermes Agent",
        display: "~/.hermes/config.yaml".into(),
        path: home.join(".hermes").join("config.yaml"),
    });

    {
        let cline_path = crate::core::editor_registry::cline_mcp_path();
        if cline_path.to_str().is_some_and(|s| s != "/nonexistent") {
            locations.push(McpLocation {
                name: "Cline",
                display: cline_path.display().to_string(),
                path: cline_path,
            });
        }
    }
    {
        let roo_path = crate::core::editor_registry::roo_mcp_path();
        if roo_path.to_str().is_some_and(|s| s != "/nonexistent") {
            locations.push(McpLocation {
                name: "Roo Code",
                display: roo_path.display().to_string(),
                path: roo_path,
            });
        }
    }

    locations
}

pub(super) fn has_lean_ctx_mcp_entry(content: &str) -> bool {
    // Parse as JSONC: editor config files (VS Code settings.json / mcp.json,
    // Cursor, Windsurf, …) commonly contain comments and trailing commas which
    // strict JSON rejects. See issue #311.
    if let Ok(json) = crate::core::jsonc::parse_jsonc(content) {
        // Known container keys across editors that hold a map of MCP servers:
        //   mcpServers       — most agents (Cursor, Claude, Windsurf, …)
        //   servers          — VS Code mcp.json
        //   context_servers  — Zed settings.json
        for key in ["mcpServers", "servers", "context_servers"] {
            if let Some(servers) = json.get(key).and_then(|v| v.as_object())
                && servers.contains_key("lean-ctx")
            {
                return true;
            }
        }
        // mcp.servers.lean-ctx (OpenCode et al.)
        if let Some(servers) = json
            .get("mcp")
            .and_then(|v| v.get("servers"))
            .and_then(|v| v.as_object())
            && servers.contains_key("lean-ctx")
        {
            return true;
        }
        // Parsed cleanly but no lean-ctx entry under any known key.
        return false;
    }
    // Unparseable even as JSONC: fall back to a substring heuristic.
    content.contains("lean-ctx")
}

pub(super) fn proxy_auth_probe(port: u16) -> bool {
    use std::io::{Read, Write};
    use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};

    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
    let token = crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN");

    let Ok(mut stream) = TcpStream::connect_timeout(&addr, crate::proxy_setup::proxy_timeout())
    else {
        return false;
    };
    let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(3)));

    let req = format!(
        "GET /health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nAuthorization: Bearer {token}\r\nConnection: close\r\n\r\n"
    );
    if stream.write_all(req.as_bytes()).is_err() {
        return false;
    }

    let mut buf = [0u8; 128];
    let Ok(n) = stream.read(&mut buf) else {
        return false;
    };
    let response = String::from_utf8_lossy(&buf[..n]);
    response.contains("200") || response.contains("ok")
}

/// How Claude Code currently receives the full lean-ctx instructions.
///
/// Single source of truth for the main doctor check *and* `doctor integrations`
/// (GH #396: both previously demanded the retired `~/.claude/rules/lean-ctx.md`,
/// which `setup` deletes since the v3 layout — GL #555).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ClaudeInstructionsState {
    /// rules_scope=project: global instructions are intentionally absent.
    ProjectScope,
    /// rules_injection=off: user opted out of instructions entirely (GH #361).
    InjectionOff,
    /// rules_injection=dedicated: SessionStart hook injects, skill on disk.
    DedicatedWithSkill,
    /// rules_injection=dedicated but the skill is missing.
    DedicatedMissingSkill,
    /// CLAUDE.md block + on-demand skill (post-3.8 default layout).
    BlockAndSkill,
    /// CLAUDE.md block present, skill missing (still functional).
    BlockOnly,
    /// Legacy rules file from a pre-3.8 install (works until next setup).
    LegacyRules,
    /// Nothing installed — Claude only sees the 2048-char-capped MCP instructions.
    Missing,
}

impl ClaudeInstructionsState {
    pub(super) fn ok(self) -> bool {
        !matches!(self, Self::DedicatedMissingSkill | Self::Missing)
    }
}

pub(super) fn claude_instructions_state(
    home: &std::path::Path,
    scope: crate::core::config::RulesScope,
    injection: crate::core::config::RulesInjection,
) -> ClaudeInstructionsState {
    use ClaudeInstructionsState as S;

    if scope == crate::core::config::RulesScope::Project {
        return S::ProjectScope;
    }
    if injection == crate::core::config::RulesInjection::Off {
        return S::InjectionOff;
    }

    let has_skill = home.join(".claude/skills/lean-ctx/SKILL.md").exists();

    if injection == crate::core::config::RulesInjection::Dedicated {
        return if has_skill {
            S::DedicatedWithSkill
        } else {
            S::DedicatedMissingSkill
        };
    }

    let claude_md = crate::core::editor_registry::claude_state_dir(home).join("CLAUDE.md");
    let has_block = std::fs::read_to_string(&claude_md)
        .is_ok_and(|c| c.contains(crate::hooks::agents::CLAUDE_MD_BLOCK_START));
    if has_block {
        return if has_skill {
            S::BlockAndSkill
        } else {
            S::BlockOnly
        };
    }

    let has_rules = crate::core::editor_registry::claude_rules_dir(home)
        .join("lean-ctx.md")
        .exists();
    if has_rules {
        return S::LegacyRules;
    }

    S::Missing
}

/// CodeBuddy instructions state — mirrors `claude_instructions_state` since
/// CodeBuddy uses the same CODEBUDDY.md block + skill pattern as Claude Code.
pub(super) fn codebuddy_instructions_state(
    home: &std::path::Path,
    scope: crate::core::config::RulesScope,
    injection: crate::core::config::RulesInjection,
) -> ClaudeInstructionsState {
    use ClaudeInstructionsState as S;

    if scope == crate::core::config::RulesScope::Project {
        return S::ProjectScope;
    }
    if injection == crate::core::config::RulesInjection::Off {
        return S::InjectionOff;
    }

    let has_skill = home.join(".codebuddy/skills/lean-ctx/SKILL.md").exists();

    if injection == crate::core::config::RulesInjection::Dedicated {
        return if has_skill {
            S::DedicatedWithSkill
        } else {
            S::DedicatedMissingSkill
        };
    }

    let codebuddy_md = crate::core::editor_registry::codebuddy_state_dir(home).join("CODEBUDDY.md");
    let has_block = std::fs::read_to_string(&codebuddy_md)
        .is_ok_and(|c| c.contains(crate::hooks::agents::CODEBUDDY_MD_BLOCK_START));
    if has_block {
        return if has_skill {
            S::BlockAndSkill
        } else {
            S::BlockOnly
        };
    }

    let has_rules = crate::core::editor_registry::codebuddy_rules_dir(home)
        .join("lean-ctx.md")
        .exists();
    if has_rules {
        return S::LegacyRules;
    }

    S::Missing
}

pub(super) fn claude_binary_exists() -> bool {
    #[cfg(unix)]
    {
        std::process::Command::new("which")
            .arg("claude")
            .output()
            .is_ok_and(|o| o.status.success())
    }
    #[cfg(windows)]
    {
        std::process::Command::new("where")
            .arg("claude")
            .output()
            .is_ok_and(|o| o.status.success())
    }
}

pub(super) fn codebuddy_binary_exists() -> bool {
    #[cfg(unix)]
    {
        std::process::Command::new("which")
            .arg("codebuddy")
            .output()
            .is_ok_and(|o| o.status.success())
    }
    #[cfg(windows)]
    {
        std::process::Command::new("where")
            .arg("codebuddy")
            .output()
            .is_ok_and(|o| o.status.success())
    }
}

#[cfg(test)]
mod tests {
    use super::{display_user_path, tildify_home};
    use std::path::Path;

    #[test]
    fn display_user_path_abbreviates_home() {
        if let Some(home) = dirs::home_dir() {
            let shown = display_user_path(&home.join(".cursor").join("mcp.json"));
            assert_eq!(shown, "~/.cursor/mcp.json");
            assert_eq!(display_user_path(&home), "~");
        }
    }

    #[test]
    fn display_user_path_leaves_non_home_paths() {
        assert_eq!(
            display_user_path(Path::new("/opt/leanctx/bin")),
            "/opt/leanctx/bin"
        );
    }

    #[test]
    fn display_user_path_normalizes_separators() {
        assert_eq!(
            display_user_path(Path::new("rel\\sub\\file")),
            "rel/sub/file"
        );
    }

    #[test]
    fn display_user_path_respects_component_boundary() {
        // `/home/foo` must never turn `/home/foo-sibling/...` into `~-sibling/...`.
        if let Some(home) = dirs::home_dir()
            && let (Some(parent), Some(name)) = (home.parent(), home.file_name())
        {
            let sibling = parent
                .join(format!("{}-sibling", name.to_string_lossy()))
                .join("x");
            assert!(!display_user_path(&sibling).starts_with('~'));
        }
    }

    #[test]
    fn tildify_home_replaces_home_in_formatted_text() {
        if let Some(home) = dirs::home_dir() {
            let line = format!("ok ({}/.config/x)", home.display());
            let shown = tildify_home(&line);
            assert!(shown.contains("~/.config/x"), "got: {shown}");
            assert!(
                !shown.contains(&home.display().to_string()),
                "home leaked: {shown}"
            );
        }
    }
}