Skip to main content

lean_ctx/hooks/
mod.rs

1use std::path::PathBuf;
2
3pub mod agents;
4mod support;
5
6/// Controls how hooks instruct agents to access lean-ctx functionality.
7///
8/// * `Mcp` — MCP server only (extension/plugin-based agents without reliable shell).
9/// * `Hybrid` — MCP server + shell hooks for command compression (best of both).
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum HookMode {
13    #[default]
14    Mcp,
15    Hybrid,
16}
17
18impl std::fmt::Display for HookMode {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            Self::Mcp => write!(f, "MCP"),
22            Self::Hybrid => write!(f, "Hybrid"),
23        }
24    }
25}
26
27impl HookMode {
28    pub fn from_str_loose(s: &str) -> Option<Self> {
29        match s.to_lowercase().replace('-', "").as_str() {
30            "mcp" => Some(Self::Mcp),
31            "hybrid" => Some(Self::Hybrid),
32            _ => None,
33        }
34    }
35
36    pub fn description(&self) -> &'static str {
37        match self {
38            Self::Mcp => "MCP server only (extension/plugin-based agents without reliable shell)",
39            Self::Hybrid => "MCP server + shell hooks for command compression (best of both)",
40        }
41    }
42}
43
44/// Auto-detect the best hook mode for a given agent key based on its shell capabilities.
45///
46/// Criteria (verified against provider docs May 2026):
47///   Hybrid — MCP server (full Context OS) + shell hooks where available.
48///            Read/Search via MCP (reliable, cached). Shell via hooks (zero overhead).
49///   Mcp    — agent has no reliable direct shell tool (e.g. IDE plugin only)
50/// Agents that get the Hybrid integration (MCP for reads/search + shell hooks
51/// or rules for command compression). Kept as a single data list so it is
52/// testable and so `refresh_installed_hooks` can prove it covers every one of
53/// them (see `refresh_covers_every_hybrid_agent`).
54pub const HYBRID_AGENTS: &[&str] = &[
55    "cursor",
56    "gemini",
57    "codex",
58    "claude",
59    "claude-code",
60    "crush",
61    "hermes",
62    "opencode",
63    "openclaw",
64    "pi",
65    "qoder",
66    "windsurf",
67    "amp",
68    "cline",
69    "roo",
70    "copilot",
71    "kiro",
72    "qwen",
73    "trae",
74    "antigravity",
75    "antigravity-cli",
76    "amazonq",
77    "verdent",
78];
79
80pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
81    if HYBRID_AGENTS.contains(&agent_key) {
82        HookMode::Hybrid
83    } else {
84        // No reliable direct shell tool → MCP only.
85        HookMode::Mcp
86    }
87}
88use agents::{
89    install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
90    install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
91    install_claude_project_hooks, install_cline_rules, install_codex_hook, install_copilot_hook,
92    install_crush_hook_with_mode, install_cursor_hook_config, install_cursor_hook_scripts,
93    install_cursor_hook_with_mode, install_gemini_hook, install_gemini_hook_config,
94    install_gemini_hook_scripts, install_hermes_hook_with_mode, install_jetbrains_hook,
95    install_kiro_hook, install_openclaw_hook, install_opencode_hook_with_mode,
96    install_pi_hook_with_mode, install_qoder_hook, install_qoder_hook_with_mode,
97    install_windsurf_hooks, install_windsurf_rules,
98};
99use support::{
100    ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
101    upsert_lean_ctx_codex_hook_entries,
102};
103
104fn mcp_server_quiet_mode() -> bool {
105    std::env::var_os("LEAN_CTX_MCP_SERVER").is_some()
106        || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(value) if value.trim() == "1")
107}
108
109/// Agents whose global shell-hook artifacts embed the binary path / command
110/// and therefore must be re-rendered after an update or on MCP server start so
111/// they always point at the current binary. Each entry is gated on a detection
112/// marker (see `hooks_installed_for`) so we never install hooks for an agent
113/// the user never configured. The `refresh_covers_every_hybrid_agent` test
114/// proves this list plus `REFRESH_EXEMPT_HYBRID_AGENTS` accounts for every
115/// Hybrid agent, so a newly added agent can never silently regress.
116const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
117    "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder",
118];
119
120/// Hybrid agents intentionally NOT auto-refreshed, with the reason each is safe
121/// to skip. Refresh runs silently (including on every MCP server start), so it
122/// must never spawn subprocesses or write project/cwd-relative files. Used by
123/// the coverage test to prove every Hybrid agent has an explicit decision.
124#[cfg(test)]
125const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
126    // Alias of `claude` — same global files, already refreshed via "claude".
127    "claude-code",
128    // Installer shells out to `pi install` (subprocess) — unsafe on every start.
129    "pi",
130    // Write project/cwd-relative rules (.clinerules, .kiro/steering) — a silent
131    // server-start refresh must not create files in the user's working dir.
132    "cline",
133    "roo",
134    "kiro",
135    // MCP-config / rules wiring only (no global binary-embedding shell-hook
136    // script to keep current); refreshed by `setup --fix`, not on start.
137    "antigravity",
138    "antigravity-cli",
139    "amp",
140    "crush",
141    "hermes",
142    "opencode",
143    "openclaw",
144    "qwen",
145    "trae",
146    "amazonq",
147    "verdent",
148];
149
150/// Silently refresh all hook scripts for agents that are already configured.
151/// Called after updates and on MCP server start to ensure hooks match the
152/// current binary version. Registry-driven: every Hybrid agent with a global
153/// shell hook is covered (the rest are explicitly exempted, enforced by test).
154pub fn refresh_installed_hooks() {
155    let Some(home) = crate::core::home::resolve_home_dir() else {
156        return;
157    };
158    for agent in REFRESHABLE_HOOK_AGENTS {
159        if hooks_installed_for(agent, &home) {
160            refresh_agent_hooks(agent, &home);
161        }
162    }
163}
164
165/// True when `agent` already has lean-ctx hook artifacts on disk (global only).
166fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
167    match agent {
168        "claude" => {
169            let dir = crate::setup::claude_config_dir(home);
170            dir.join("hooks/lean-ctx-rewrite.sh").exists()
171                || file_contains_lean_ctx(&dir.join("settings.json"))
172        }
173        "cursor" => {
174            home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
175                || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
176        }
177        "gemini" => {
178            home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
179                .exists()
180                || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
181        }
182        "codex" => {
183            let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
184            dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
185                || file_contains_lean_ctx(&dir.join("hooks.json"))
186        }
187        "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
188        "copilot" => {
189            // User-level Copilot hooks live under ~/.copilot/hooks (#381);
190            // ~/.github/hooks is the pre-#381 legacy location.
191            file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
192                || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
193        }
194        "qoder" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
195        _ => false,
196    }
197}
198
199/// Re-render the hook artifacts for an already-configured agent. Only calls
200/// narrow, subprocess-free, global installers (never the full agent setup).
201fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
202    match agent {
203        "claude" => {
204            install_claude_hook_scripts(home);
205            install_claude_hook_config(home);
206        }
207        "cursor" => {
208            install_cursor_hook_scripts(home);
209            install_cursor_hook_config(home);
210        }
211        "gemini" => {
212            install_gemini_hook_scripts(home);
213            install_gemini_hook_config(home);
214        }
215        "codex" => install_codex_hook(),
216        "windsurf" => install_windsurf_hooks(home),
217        "copilot" => install_copilot_hook(true),
218        "qoder" => install_qoder_hook(),
219        _ => {}
220    }
221}
222
223fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
224    std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
225}
226
227/// Resolve the lean-ctx binary to an **absolute** path for generated hook
228/// commands and MCP server entries.
229///
230/// Agent hooks (Codex, Cursor, Claude, Gemini, Antigravity, …) are executed by
231/// the host under a plain non-login shell (`sh -c …`) whose `PATH` is not
232/// guaranteed to contain the install dir (e.g. `/usr/local/bin`). A bare
233/// `lean-ctx` therefore fails with exit code 127 (#367). Always emitting the
234/// resolved absolute path makes hook execution deterministic and matches what
235/// MCP setup (`setup/mcp.rs`) and `doctor` already do. Existing configs with a
236/// bare command are rewritten on the next `lean-ctx init` / `doctor` run.
237fn resolve_binary_path() -> String {
238    crate::core::portable_binary::resolve_portable_binary()
239}
240
241fn resolve_binary_path_for_bash() -> String {
242    let path = resolve_binary_path();
243    to_bash_compatible_path(&path)
244}
245
246pub fn to_bash_compatible_path(path: &str) -> String {
247    let path = match crate::core::pathutil::strip_verbatim_str(path) {
248        Some(stripped) => stripped,
249        None => path.replace('\\', "/"),
250    };
251    if path.len() >= 2 && path.as_bytes()[1] == b':' {
252        let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
253        format!("/{drive}{}", &path[2..])
254    } else {
255        path
256    }
257}
258
259/// Convert a Unix/MSYS-style path (`/c/Users/...`) back to native Windows
260/// format (`C:/Users/...`). No-op for paths that don't match the pattern.
261pub fn from_bash_to_native_path(path: &str) -> String {
262    crate::core::pathutil::normalize_tool_path(path)
263}
264
265/// Normalize paths from any client format to a consistent OS-native form.
266/// Delegates to `core::pathutil` so `core` crates do not depend on `hooks`.
267pub fn normalize_tool_path(path: &str) -> String {
268    crate::core::pathutil::normalize_tool_path(path)
269}
270
271pub fn generate_rewrite_script(binary: &str) -> String {
272    let case_pattern = crate::rewrite_registry::bash_case_pattern();
273    format!(
274        r#"#!/usr/bin/env bash
275# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
276set -euo pipefail
277
278LEAN_CTX_BIN="{binary}"
279
280INPUT=$(cat)
281TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
282
283case "$TOOL" in
284  Bash|bash|PowerShell|powershell) ;;
285  *) exit 0 ;;
286esac
287
288CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
289
290if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
291  exit 0
292fi
293
294case "$CMD" in
295  {case_pattern})
296    # Shell-escape then JSON-escape (two passes)
297    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
298    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
299    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
300    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
301    ;;
302  *) exit 0 ;;
303esac
304"#
305    )
306}
307
308pub fn generate_compact_rewrite_script(binary: &str) -> String {
309    let case_pattern = crate::rewrite_registry::bash_case_pattern();
310    format!(
311        r#"#!/usr/bin/env bash
312# lean-ctx hook — rewrites shell commands
313set -euo pipefail
314LEAN_CTX_BIN="{binary}"
315INPUT=$(cat)
316CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
317if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
318case "$CMD" in
319  {case_pattern})
320    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
321    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
322    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
323    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
324  *) exit 0 ;;
325esac
326"#
327    )
328}
329
330const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
331# lean-ctx PreToolUse hook — all native tools pass through
332# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
333# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
334exit 0
335";
336
337const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
338# lean-ctx hook — all native tools pass through
339exit 0
340";
341
342pub(crate) const HYBRID_RULES: &str = "\
343# lean-ctx — Hybrid Mode (MCP reads + CLI commands)
344
345Use MCP tools for reads (cache benefit), CLI commands for everything else (no schema overhead):
346
347## MCP tools (keep using):
348| Tool | Why MCP |
349|------|---------|
350| `ctx_read(path, mode)` | In-process cache, re-reads ~13 tokens |
351
352## CLI commands (via Shell/Bash):
353| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
354|---------------------|-------------------|-----|
355| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | No MCP schema overhead |
356| `lean-ctx grep <pattern> [path]` | `ctx_search` | No MCP schema overhead |
357| `lean-ctx ls [path]` | `ctx_tree` | No MCP schema overhead |
358
359## File editing:
360Use native Edit/StrReplace — lean-ctx only handles READ operations.
361Write, Delete, Glob → use normally.
362";
363
364pub fn install_project_rules() {
365    install_project_rules_for_agents(&[]);
366}
367
368/// Install project rules, optionally scoped to specific agents.
369/// If `agents` is empty, installs for all agents (legacy behavior).
370pub fn install_project_rules_for_agents(agents: &[&str]) {
371    if crate::core::config::Config::load().rules_scope_effective()
372        == crate::core::config::RulesScope::Global
373    {
374        return;
375    }
376
377    let cwd = std::env::current_dir().unwrap_or_default();
378
379    if !is_inside_git_repo(&cwd) {
380        eprintln!(
381            "  Skipping project files: not inside a git repository.\n  \
382             Run this command from your project root to create CLAUDE.md / AGENTS.md."
383        );
384        return;
385    }
386
387    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
388    if cwd == home {
389        eprintln!(
390            "  Skipping project files: current directory is your home folder.\n  \
391             Run this command from a project directory instead."
392        );
393        return;
394    }
395
396    let all = agents.is_empty();
397    let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
398
399    ensure_project_agents_integration(&cwd);
400
401    if wants("cursor") || wants("windsurf") {
402        let cursorrules = cwd.join(".cursorrules");
403        if !cursorrules.exists()
404            || !std::fs::read_to_string(&cursorrules)
405                .unwrap_or_default()
406                .contains("lean-ctx")
407        {
408            let content = CURSORRULES_TEMPLATE;
409            if cursorrules.exists() {
410                let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
411                if !existing.ends_with('\n') {
412                    existing.push('\n');
413                }
414                existing.push('\n');
415                existing.push_str(content);
416                write_file(&cursorrules, &existing);
417            } else {
418                write_file(&cursorrules, content);
419            }
420            if !mcp_server_quiet_mode() {
421                eprintln!("Created/updated .cursorrules in project root.");
422            }
423        }
424    }
425
426    if wants("claude") {
427        // GL #555: project rules files without `paths:` frontmatter load
428        // unconditionally every session and stacked on top of the global
429        // CLAUDE.md block (12k+ token memory footprints in the field). The
430        // AGENTS.md block + on-demand skill carry the same guidance, so the
431        // lean-ctx-owned copy is removed instead of refreshed.
432        let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
433        if let Ok(existing) = std::fs::read_to_string(&claude_rules_file) {
434            if existing.contains("<!-- lean-ctx-rules-")
435                && std::fs::remove_file(&claude_rules_file).is_ok()
436                && !mcp_server_quiet_mode()
437            {
438                eprintln!(
439                    "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
440                );
441            }
442        }
443
444        install_claude_project_hooks(&cwd);
445    }
446
447    if wants("kiro") {
448        let kiro_dir = cwd.join(".kiro");
449        if kiro_dir.exists() {
450            let steering_dir = kiro_dir.join("steering");
451            let steering_file = steering_dir.join("lean-ctx.md");
452            if !steering_file.exists()
453                || !std::fs::read_to_string(&steering_file)
454                    .unwrap_or_default()
455                    .contains("lean-ctx")
456            {
457                let _ = std::fs::create_dir_all(&steering_dir);
458                write_file(&steering_file, KIRO_STEERING_TEMPLATE);
459                if !mcp_server_quiet_mode() {
460                    eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
461                }
462            }
463        }
464    }
465}
466
467const PROJECT_LEAN_CTX_MD_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
468const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
469const PROJECT_AGENTS_MD: &str = "AGENTS.md";
470const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
471const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
472
473fn ensure_project_agents_integration(cwd: &std::path::Path) {
474    let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
475    let desired = format!(
476        "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
477        crate::rules_inject::rules_dedicated_markdown()
478    );
479
480    if !lean_ctx_md.exists() {
481        write_file(&lean_ctx_md, &desired);
482    } else if std::fs::read_to_string(&lean_ctx_md)
483        .unwrap_or_default()
484        .contains(PROJECT_LEAN_CTX_MD_MARKER)
485    {
486        let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
487        if !current.contains(crate::rules_inject::RULES_VERSION_STR) {
488            write_file(&lean_ctx_md, &desired);
489        }
490    }
491
492    // No `@` import: Claude Code expands `@file` references inline at session
493    // start, so pointing at LEAN-CTX.md re-loaded the full ruleset into every
494    // session on top of this block (GL #555). The block is self-contained;
495    // the full ruleset stays in LEAN-CTX.md for on-demand reading.
496    let block = format!(
497        "{AGENTS_BLOCK_START}\n\
498## lean-ctx\n\n\
499Prefer lean-ctx MCP tools over native equivalents for token savings:\n\
500`ctx_read` > Read/cat, `ctx_search` > Grep/rg, `ctx_shell` > bash, `ctx_tree` > ls/find.\n\
501Native Edit/Write/Glob stay as-is; use `ctx_edit` only when Edit needs an unavailable Read.\n\
502Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
503{AGENTS_BLOCK_END}\n"
504    );
505
506    let agents_md = cwd.join(PROJECT_AGENTS_MD);
507    if !agents_md.exists() {
508        let content = format!("# Agent Instructions\n\n{block}");
509        write_file(&agents_md, &content);
510        if !mcp_server_quiet_mode() {
511            eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
512        }
513        return;
514    }
515
516    let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
517
518    if existing.contains("CLI-first Token Optimization for Pi")
519        && !existing.contains(AGENTS_BLOCK_START)
520    {
521        let content = format!("# Agent Instructions\n\n{block}");
522        write_file(&agents_md, &content);
523        return;
524    }
525
526    if existing.contains(AGENTS_BLOCK_START) {
527        let updated = crate::marked_block::replace_marked_block(
528            &existing,
529            AGENTS_BLOCK_START,
530            AGENTS_BLOCK_END,
531            &block,
532        );
533        if updated != existing {
534            write_file(&agents_md, &updated);
535        }
536        return;
537    }
538
539    if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
540        return;
541    }
542
543    let mut out = existing;
544    if !out.ends_with('\n') {
545        out.push('\n');
546    }
547    out.push('\n');
548    out.push_str(&block);
549    write_file(&agents_md, &out);
550    if !mcp_server_quiet_mode() {
551        eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
552    }
553}
554
555/// Compact pointer only (#578): Cursor already auto-loads the canonical full
556/// ruleset from `~/.cursor/rules/lean-ctx.mdc`, so a project `.cursorrules`
557/// that repeats it bills the same guidance twice in every session.
558const CURSORRULES_TEMPLATE: &str = "\
559<!-- lean-ctx -->
560# lean-ctx
561
562Prefer lean-ctx MCP tools: ctx_read > Read/cat, ctx_search > Grep/rg, ctx_shell > bash, ctx_tree > ls/find.
563Edit/Write/Glob stay native; ctx_edit only when Edit needs an unavailable Read.
564Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) — do not duplicate here.
565<!-- /lean-ctx -->
566";
567
568pub const KIRO_STEERING_TEMPLATE: &str = "\
569---
570inclusion: always
571---
572
573# lean-ctx — Context Engineering Layer
574
575The workspace has the `lean-ctx` MCP server installed. You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.
576
577## Mandatory Tool Preferences
578
579| Use this | Instead of | Why |
580|----------|-----------|-----|
581| `mcp_lean_ctx_ctx_read` | `readFile`, `readCode` | Cached reads, 10 compression modes, re-reads cost ~13 tokens |
582| `mcp_lean_ctx_ctx_multi_read` | `readMultipleFiles` | Batch cached reads in one call |
583| `mcp_lean_ctx_ctx_shell` | `executeBash` | Pattern compression for git/npm/test output |
584| `mcp_lean_ctx_ctx_search` | `grepSearch` | Compact, .gitignore-aware results |
585| `mcp_lean_ctx_ctx_tree` | `listDirectory` | Compact directory maps with file counts |
586
587## When to use native Kiro tools instead
588
589- `fsWrite` / `fsAppend` — always use native (lean-ctx doesn't write files)
590- `strReplace` — always use native (precise string replacement)
591- `semanticRename` / `smartRelocate` — always use native (IDE integration)
592- `getDiagnostics` — always use native (language server diagnostics)
593- `deleteFile` — always use native
594
595## Session management
596
597- At the start of a long task, call `mcp_lean_ctx_ctx_preload` with a task description to warm the cache
598- Use `mcp_lean_ctx_ctx_compress` periodically in long conversations to checkpoint context
599- Use `mcp_lean_ctx_ctx_knowledge` to persist important discoveries across sessions
600
601## Rules
602
603- NEVER loop on edit failures — switch to `mcp_lean_ctx_ctx_edit` immediately
604- For large files, use `mcp_lean_ctx_ctx_read` with `mode: \"signatures\"` or `mode: \"map\"` first
605- For re-reading a file you already read, just call `mcp_lean_ctx_ctx_read` again (cache hit = ~13 tokens)
606- When running tests or build commands, use `mcp_lean_ctx_ctx_shell` for compressed output
607";
608
609pub fn install_agent_hook(agent: &str, global: bool) {
610    install_agent_hook_with_mode(agent, global, HookMode::Mcp);
611}
612
613pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
614    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
615    match agent {
616        "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
617        "cursor" => install_cursor_hook_with_mode(global, mode),
618        "gemini" => {
619            install_gemini_hook();
620            // Google is transitioning Gemini CLI → Antigravity CLI (`agy`), and
621            // `gemini` setup also configures the Antigravity CLI MCP target. The
622            // hooks must follow: `agy` reads hooks only from its plugin dir
623            // (`~/.gemini/config/plugins/lean-ctx`), never from the legacy
624            // `~/.gemini/settings.json`, so install the plugin too (#284).
625            install_antigravity_cli_hook();
626        }
627        "antigravity" => install_antigravity_hook(),
628        "antigravity-cli" => install_antigravity_cli_hook(),
629        "augment" => install_mcp_json_agent(
630            "Augment CLI",
631            "~/.augment/settings.json",
632            &crate::core::editor_registry::augment_cli_settings_path(&home),
633        ),
634        "codex" => install_codex_hook(),
635        "windsurf" => install_windsurf_rules(global),
636        "cline" | "roo" => install_cline_rules(global),
637        "copilot" | "vscode" => install_copilot_hook(global),
638        "pi" => install_pi_hook_with_mode(global, mode),
639        "qoder" => install_qoder_hook_with_mode(mode),
640        "qoderwork" => install_mcp_json_agent(
641            "QoderWork",
642            "~/.qoderwork/mcp.json",
643            &home.join(".qoderwork/mcp.json"),
644        ),
645        "qwen" => install_mcp_json_agent(
646            "Qwen Code",
647            "~/.qwen/settings.json",
648            &home.join(".qwen/settings.json"),
649        ),
650        "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
651        "amazonq" => install_mcp_json_agent(
652            "Amazon Q Developer",
653            "~/.aws/amazonq/default.json",
654            &home.join(".aws/amazonq/default.json"),
655        ),
656        "jetbrains" => install_jetbrains_hook(),
657        "kiro" => install_kiro_hook(),
658        "verdent" => install_mcp_json_agent(
659            "Verdent",
660            "~/.verdent/mcp.json",
661            &home.join(".verdent/mcp.json"),
662        ),
663        "opencode" => install_opencode_hook_with_mode(mode),
664        "amp" => install_amp_hook(),
665        "crush" => install_crush_hook_with_mode(mode),
666        "openclaw" => install_openclaw_hook(),
667        "hermes" => install_hermes_hook_with_mode(global, mode),
668        "zed" => {
669            let zed_path = crate::core::editor_registry::zed_settings_path(&home);
670            let binary = resolve_binary_path();
671            let entry = full_server_entry(&binary);
672            install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
673        }
674        "aider" => {
675            install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
676        }
677        "continue" => install_mcp_json_agent(
678            "Continue",
679            "~/.continue/mcp.json",
680            &home.join(".continue/mcp.json"),
681        ),
682        "neovim" => install_mcp_json_agent(
683            "Neovim (mcphub.nvim)",
684            "~/.config/mcphub/servers.json",
685            &home.join(".config/mcphub/servers.json"),
686        ),
687        "emacs" => install_mcp_json_agent(
688            "Emacs (mcp.el)",
689            "~/.emacs.d/mcp.json",
690            &home.join(".emacs.d/mcp.json"),
691        ),
692        "sublime" => install_mcp_json_agent(
693            "Sublime Text",
694            "~/.config/sublime-text/mcp.json",
695            &home.join(".config/sublime-text/mcp.json"),
696        ),
697        _ => {
698            eprintln!("Unknown agent: {agent}");
699            eprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
700            eprintln!("    claude, cline, codex, continue, copilot, crush, cursor, emacs, gemini,");
701            eprintln!("    hermes, jetbrains, kiro, neovim, openclaw, opencode, pi, qoder,");
702            eprintln!("    qoderwork, qwen, roo, sublime, trae, verdent, vscode, windsurf, zed");
703            std::process::exit(1);
704        }
705    }
706}
707
708pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
709    match agent {
710        "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
711        _ => {}
712    }
713}
714
715fn write_file(path: &std::path::Path, content: &str) {
716    // Skip identical rewrites: re-running setup/init must not churn mtimes or
717    // leave .bak files behind for content that did not change (GL #558).
718    if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
719        return;
720    }
721    if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
722        tracing::error!("Error writing {}: {e}", path.display());
723    }
724}
725
726fn is_inside_git_repo(path: &std::path::Path) -> bool {
727    let mut p = path;
728    loop {
729        if p.join(".git").exists() {
730            return true;
731        }
732        match p.parent() {
733            Some(parent) => p = parent,
734            None => return false,
735        }
736    }
737}
738
739#[cfg(unix)]
740fn make_executable(path: &PathBuf) {
741    use std::os::unix::fs::PermissionsExt;
742    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
743}
744
745#[cfg(not(unix))]
746fn make_executable(_path: &PathBuf) {}
747
748/// Env key/value pairs for the lean-ctx MCP server entry written into agent
749/// configs (Codex TOML + the JSON agents).
750///
751/// Always emits `LEAN_CTX_DATA_DIR`; adds `LEAN_CTX_PROJECT_ROOT` and
752/// `LEAN_CTX_EXTRA_ROOTS` when known (process env first, then config). Without
753/// these, a long-lived MCP server spawned by the agent loses the project /
754/// worktree scope captured at `init`, so an explicit path under a sibling
755/// worktree is wrongly rejected as a jail escape (#403). Single source of truth
756/// so every agent installer stays consistent.
757pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
758    let mut pairs = Vec::new();
759
760    let data_dir = crate::core::data_dir::lean_ctx_data_dir()
761        .map(|d| d.to_string_lossy().to_string())
762        .unwrap_or_default();
763    pairs.push(("LEAN_CTX_DATA_DIR".to_string(), data_dir));
764
765    let cfg = crate::core::config::Config::load();
766
767    let project_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
768        .ok()
769        .filter(|v| !v.trim().is_empty())
770        .or_else(|| cfg.project_root.clone().filter(|v| !v.trim().is_empty()));
771    if let Some(root) = project_root {
772        pairs.push(("LEAN_CTX_PROJECT_ROOT".to_string(), root));
773    }
774
775    // Env override is already a platform path-list; config is a Vec we join the
776    // same way `LEAN_CTX_EXTRA_ROOTS` is parsed (`std::env::split_paths`).
777    let extra_roots = std::env::var("LEAN_CTX_EXTRA_ROOTS")
778        .ok()
779        .filter(|v| !v.trim().is_empty())
780        .or_else(|| {
781            let roots: Vec<&str> = cfg
782                .extra_roots
783                .iter()
784                .map(String::as_str)
785                .filter(|s| !s.trim().is_empty())
786                .collect();
787            if roots.is_empty() {
788                return None;
789            }
790            std::env::join_paths(roots)
791                .ok()
792                .map(|s| s.to_string_lossy().to_string())
793        });
794    if let Some(extra) = extra_roots {
795        pairs.push(("LEAN_CTX_EXTRA_ROOTS".to_string(), extra));
796    }
797
798    pairs
799}
800
801/// The MCP server env block as a JSON object, for the JSON-config agents.
802pub(crate) fn mcp_server_env_json() -> serde_json::Value {
803    let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
804        .into_iter()
805        .map(|(k, v)| (k, serde_json::Value::String(v)))
806        .collect();
807    serde_json::Value::Object(map)
808}
809
810fn full_server_entry(binary: &str) -> serde_json::Value {
811    // No LEAN_CTX_FULL_TOOLS here: forcing the full toolset (69+ schemas,
812    // ~15k tokens of tool definitions resent every turn) made lean-ctx one of
813    // the biggest token consumers in users' sessions (GitHub #385). The server
814    // defaults to the core toolset + ctx_call/ctx_expand for on-demand access;
815    // power users opt in via `tool_profile = "power"` in config.toml.
816    serde_json::json!({
817        "command": binary,
818        "env": mcp_server_env_json()
819    })
820}
821
822pub(crate) fn install_mcp_json_agent(
823    name: &str,
824    display_path: &str,
825    config_path: &std::path::Path,
826) {
827    let binary = resolve_binary_path();
828    let entry = full_server_entry(&binary);
829    install_named_json_server(name, display_path, config_path, "mcpServers", entry);
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    #[test]
837    fn refresh_covers_every_hybrid_agent() {
838        // Every Hybrid agent must be in exactly one of the two sets, so a newly
839        // added agent can never silently skip the post-update hook refresh.
840        for agent in HYBRID_AGENTS {
841            let refreshed = REFRESHABLE_HOOK_AGENTS.contains(agent);
842            let exempt = REFRESH_EXEMPT_HYBRID_AGENTS.contains(agent);
843            assert!(
844                refreshed ^ exempt,
845                "hybrid agent `{agent}` must be either refreshed or explicitly exempt (exactly one)"
846            );
847        }
848    }
849
850    #[test]
851    fn refresh_sets_reference_only_hybrid_agents() {
852        for agent in REFRESHABLE_HOOK_AGENTS {
853            assert!(
854                HYBRID_AGENTS.contains(agent),
855                "refreshable agent `{agent}` is not a Hybrid agent"
856            );
857        }
858        for agent in REFRESH_EXEMPT_HYBRID_AGENTS {
859            assert!(
860                HYBRID_AGENTS.contains(agent),
861                "exempt agent `{agent}` is not a Hybrid agent (stale exemption?)"
862            );
863        }
864    }
865
866    #[test]
867    fn mcp_env_pairs_propagate_project_and_extra_roots_from_env() {
868        // #403: init must bake the captured project/worktree scope into the MCP
869        // server entry, otherwise the long-lived server rejects explicit paths
870        // under sibling worktrees as jail escapes.
871        let _iso = crate::core::data_dir::isolated_data_dir();
872        std::env::set_var("LEAN_CTX_PROJECT_ROOT", "/work/main");
873        std::env::set_var("LEAN_CTX_EXTRA_ROOTS", "/work/wt-a:/work/wt-b");
874
875        let pairs = mcp_server_env_pairs();
876        let get = |k: &str| pairs.iter().find(|(p, _)| p == k).map(|(_, v)| v.as_str());
877        assert!(
878            get("LEAN_CTX_DATA_DIR").is_some(),
879            "data dir always emitted"
880        );
881        assert_eq!(get("LEAN_CTX_PROJECT_ROOT"), Some("/work/main"));
882        assert_eq!(get("LEAN_CTX_EXTRA_ROOTS"), Some("/work/wt-a:/work/wt-b"));
883
884        // The JSON view mirrors the pairs for the JSON-config agents.
885        let json = mcp_server_env_json();
886        assert_eq!(json["LEAN_CTX_PROJECT_ROOT"].as_str(), Some("/work/main"));
887
888        std::env::remove_var("LEAN_CTX_PROJECT_ROOT");
889        std::env::remove_var("LEAN_CTX_EXTRA_ROOTS");
890    }
891
892    #[test]
893    fn mcp_env_pairs_omit_roots_when_unset() {
894        // No project context configured anywhere ⇒ only the data dir is emitted,
895        // so we never write empty/placeholder root keys into agent configs.
896        let _iso = crate::core::data_dir::isolated_data_dir();
897        std::env::remove_var("LEAN_CTX_PROJECT_ROOT");
898        std::env::remove_var("LEAN_CTX_EXTRA_ROOTS");
899
900        let pairs = mcp_server_env_pairs();
901        let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
902        assert!(keys.contains(&"LEAN_CTX_DATA_DIR"));
903        assert!(!keys.contains(&"LEAN_CTX_PROJECT_ROOT"));
904        assert!(!keys.contains(&"LEAN_CTX_EXTRA_ROOTS"));
905    }
906
907    #[test]
908    fn hooks_installed_for_is_false_without_artifacts() {
909        let tmp = unique_tmp_dir("leanctx_refresh_empty");
910        for agent in REFRESHABLE_HOOK_AGENTS {
911            // `codex` resolves its dir via the global CODEX_HOME-aware resolver
912            // (not the passed home), so it cannot be isolated to a temp dir here;
913            // its detection is exercised by the marker-content test instead.
914            if *agent == "codex" {
915                continue;
916            }
917            assert!(
918                !hooks_installed_for(agent, &tmp),
919                "`{agent}` should not be detected as installed in an empty home"
920            );
921        }
922        let _ = std::fs::remove_dir_all(&tmp);
923    }
924
925    #[test]
926    fn hooks_installed_for_detects_marker_content() {
927        let tmp = unique_tmp_dir("leanctx_refresh_marker");
928        let hooks = tmp.join(".codeium/windsurf/hooks.json");
929        std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
930
931        // A foreign hooks.json must not trigger a refresh.
932        std::fs::write(&hooks, "{\"hooks\":{}}").unwrap();
933        assert!(!hooks_installed_for("windsurf", &tmp));
934
935        // Once it mentions lean-ctx, it is ours and must be refreshed.
936        std::fs::write(&hooks, "{\"hooks\":{\"cmd\":\"lean-ctx hook rewrite\"}}").unwrap();
937        assert!(hooks_installed_for("windsurf", &tmp));
938
939        let _ = std::fs::remove_dir_all(&tmp);
940    }
941
942    fn unique_tmp_dir(prefix: &str) -> std::path::PathBuf {
943        let nanos = std::time::SystemTime::now()
944            .duration_since(std::time::UNIX_EPOCH)
945            .map_or(0, |d| d.as_nanos());
946        let dir = std::env::temp_dir().join(format!("{prefix}_{}_{nanos}", std::process::id()));
947        std::fs::create_dir_all(&dir).unwrap();
948        dir
949    }
950
951    #[test]
952    fn bash_path_unix_unchanged() {
953        assert_eq!(
954            to_bash_compatible_path("/usr/local/bin/lean-ctx"),
955            "/usr/local/bin/lean-ctx"
956        );
957    }
958
959    #[test]
960    fn bash_path_home_unchanged() {
961        assert_eq!(
962            to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
963            "/home/user/.cargo/bin/lean-ctx"
964        );
965    }
966
967    #[test]
968    fn bash_path_windows_drive_converted() {
969        assert_eq!(
970            to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
971            "/c/Users/Fraser/bin/lean-ctx.exe"
972        );
973    }
974
975    #[test]
976    fn bash_path_windows_lowercase_drive() {
977        assert_eq!(
978            to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
979            "/d/tools/lean-ctx.exe"
980        );
981    }
982
983    #[test]
984    fn bash_path_windows_forward_slashes() {
985        assert_eq!(
986            to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
987            "/c/Users/Fraser/bin/lean-ctx.exe"
988        );
989    }
990
991    #[test]
992    fn bash_path_bare_name_unchanged() {
993        assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
994    }
995
996    // MSYS2 drive mapping applies on Windows hosts only — on Linux/macOS
997    // /c/… is a literal directory and must pass through (GH #397).
998    #[cfg(windows)]
999    #[test]
1000    fn normalize_msys2_path() {
1001        assert_eq!(
1002            normalize_tool_path("/c/Users/game/Downloads/project"),
1003            "C:/Users/game/Downloads/project"
1004        );
1005        assert_eq!(
1006            normalize_tool_path("/d/Projects/app/src"),
1007            "D:/Projects/app/src"
1008        );
1009    }
1010
1011    #[cfg(not(windows))]
1012    #[test]
1013    fn normalize_msys2_path_untouched_on_unix() {
1014        assert_eq!(
1015            crate::core::pathutil::normalize_tool_path_lexical("/c/Users/game/Downloads/project"),
1016            "/c/Users/game/Downloads/project"
1017        );
1018    }
1019
1020    #[test]
1021    fn normalize_backslashes() {
1022        assert_eq!(
1023            normalize_tool_path("C:\\Users\\game\\project\\src"),
1024            "C:/Users/game/project/src"
1025        );
1026    }
1027
1028    #[test]
1029    fn normalize_mixed_separators() {
1030        assert_eq!(
1031            normalize_tool_path("C:\\Users/game\\project/src"),
1032            "C:/Users/game/project/src"
1033        );
1034    }
1035
1036    #[test]
1037    fn normalize_double_slashes() {
1038        assert_eq!(
1039            normalize_tool_path("/home/user//project///src"),
1040            "/home/user/project/src"
1041        );
1042    }
1043
1044    #[test]
1045    fn normalize_trailing_slash() {
1046        assert_eq!(
1047            normalize_tool_path("/home/user/project/"),
1048            "/home/user/project"
1049        );
1050    }
1051
1052    #[test]
1053    fn normalize_root_preserved() {
1054        assert_eq!(normalize_tool_path("/"), "/");
1055    }
1056
1057    #[test]
1058    fn normalize_windows_root_preserved() {
1059        assert_eq!(normalize_tool_path("C:/"), "C:/");
1060    }
1061
1062    #[test]
1063    fn normalize_unix_path_unchanged() {
1064        assert_eq!(
1065            normalize_tool_path("/home/user/project/src/main.rs"),
1066            "/home/user/project/src/main.rs"
1067        );
1068    }
1069
1070    #[test]
1071    fn normalize_relative_path_unchanged() {
1072        assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
1073    }
1074
1075    #[test]
1076    fn normalize_dot_unchanged() {
1077        assert_eq!(normalize_tool_path("."), ".");
1078    }
1079
1080    #[test]
1081    fn normalize_unc_path_preserved() {
1082        assert_eq!(
1083            normalize_tool_path("//server/share/file"),
1084            "//server/share/file"
1085        );
1086    }
1087
1088    #[test]
1089    fn cursor_hook_config_has_version_and_object_hooks() {
1090        let config = serde_json::json!({
1091            "version": 1,
1092            "hooks": {
1093                "preToolUse": [
1094                    {
1095                        "matcher": "terminal_command",
1096                        "command": "lean-ctx hook rewrite"
1097                    },
1098                    {
1099                        "matcher": "read_file|grep|search|list_files|list_directory",
1100                        "command": "lean-ctx hook redirect"
1101                    }
1102                ]
1103            }
1104        });
1105
1106        let json_str = serde_json::to_string_pretty(&config).unwrap();
1107        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1108
1109        assert_eq!(parsed["version"], 1);
1110        assert!(parsed["hooks"].is_object());
1111        assert!(parsed["hooks"]["preToolUse"].is_array());
1112        assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
1113        assert_eq!(
1114            parsed["hooks"]["preToolUse"][0]["matcher"],
1115            "terminal_command"
1116        );
1117    }
1118
1119    #[test]
1120    fn cursor_hook_detects_old_format_needs_migration() {
1121        let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
1122        let has_correct =
1123            old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
1124        assert!(
1125            !has_correct,
1126            "Old format should be detected as needing migration"
1127        );
1128    }
1129
1130    #[test]
1131    fn gemini_hook_config_has_type_command() {
1132        let binary = "lean-ctx";
1133        let rewrite_cmd = format!("{binary} hook rewrite");
1134        let redirect_cmd = format!("{binary} hook redirect");
1135
1136        let hook_config = serde_json::json!({
1137            "hooks": {
1138                "BeforeTool": [
1139                    {
1140                        "hooks": [{
1141                            "type": "command",
1142                            "command": rewrite_cmd
1143                        }]
1144                    },
1145                    {
1146                        "hooks": [{
1147                            "type": "command",
1148                            "command": redirect_cmd
1149                        }]
1150                    }
1151                ]
1152            }
1153        });
1154
1155        let parsed = hook_config;
1156        let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
1157        assert_eq!(before_tool.len(), 2);
1158
1159        let first_hook = &before_tool[0]["hooks"][0];
1160        assert_eq!(first_hook["type"], "command");
1161        assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
1162
1163        let second_hook = &before_tool[1]["hooks"][0];
1164        assert_eq!(second_hook["type"], "command");
1165        assert_eq!(second_hook["command"], "lean-ctx hook redirect");
1166    }
1167
1168    #[test]
1169    fn gemini_hook_old_format_detected() {
1170        let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
1171        let has_new = old_format.contains("hook rewrite")
1172            && old_format.contains("hook redirect")
1173            && old_format.contains("\"type\"");
1174        assert!(!has_new, "Missing 'type' field should trigger migration");
1175    }
1176
1177    #[test]
1178    fn rewrite_script_uses_registry_pattern() {
1179        let script = generate_rewrite_script("/usr/bin/lean-ctx");
1180        assert!(script.contains(r"git\ *"), "script missing git pattern");
1181        assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
1182        assert!(script.contains(r"npm\ *"), "script missing npm pattern");
1183        assert!(script.contains(r"rg\ *"), "script missing rg pattern");
1184        assert!(script.contains(r"ls\ *"), "script missing ls pattern");
1185        assert!(
1186            script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
1187            "script missing binary path"
1188        );
1189        assert!(
1190            script.contains("PowerShell|powershell"),
1191            "rewrite script must accept PowerShell tool names for Windows compatibility"
1192        );
1193    }
1194
1195    #[test]
1196    fn compact_rewrite_script_uses_registry_pattern() {
1197        let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
1198        assert!(script.contains(r"git\ *"), "compact script missing git");
1199        assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
1200        assert!(script.contains(r"rg\ *"), "compact script missing rg");
1201    }
1202
1203    #[test]
1204    fn rewrite_scripts_contain_all_registry_commands() {
1205        let script = generate_rewrite_script("lean-ctx");
1206        let compact = generate_compact_rewrite_script("lean-ctx");
1207        for entry in crate::rewrite_registry::REWRITE_COMMANDS {
1208            if matches!(entry.category, crate::rewrite_registry::Category::FileRead) {
1209                continue;
1210            }
1211            let pattern = if entry.command.contains('-') {
1212                format!("{}*", entry.command.replace('-', r"\-"))
1213            } else {
1214                format!(r"{}\ *", entry.command)
1215            };
1216            assert!(
1217                script.contains(&pattern),
1218                "rewrite_script missing '{}' (pattern: {})",
1219                entry.command,
1220                pattern
1221            );
1222            assert!(
1223                compact.contains(&pattern),
1224                "compact_rewrite_script missing '{}' (pattern: {})",
1225                entry.command,
1226                pattern
1227            );
1228        }
1229    }
1230
1231    #[test]
1232    fn codex_is_hybrid() {
1233        assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
1234    }
1235
1236    #[test]
1237    fn cursor_is_hybrid() {
1238        assert_eq!(recommend_hook_mode("cursor"), HookMode::Hybrid);
1239    }
1240
1241    #[test]
1242    fn gemini_is_hybrid() {
1243        assert_eq!(recommend_hook_mode("gemini"), HookMode::Hybrid);
1244    }
1245
1246    #[test]
1247    fn claude_is_hybrid() {
1248        assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
1249    }
1250
1251    #[test]
1252    fn unknown_agent_falls_back_to_mcp() {
1253        assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
1254    }
1255
1256    // Drive translation only applies on Windows hosts (GH #397).
1257    #[cfg(windows)]
1258    #[test]
1259    fn from_bash_to_native_converts_msys_drive() {
1260        assert_eq!(
1261            from_bash_to_native_path("/c/Users/ABC/lean-ctx"),
1262            "C:/Users/ABC/lean-ctx"
1263        );
1264        assert_eq!(
1265            from_bash_to_native_path("/d/Program Files/lean-ctx.exe"),
1266            "D:/Program Files/lean-ctx.exe"
1267        );
1268    }
1269
1270    #[test]
1271    fn from_bash_to_native_unix_path_unchanged() {
1272        assert_eq!(
1273            from_bash_to_native_path("/usr/local/bin/lean-ctx"),
1274            "/usr/local/bin/lean-ctx"
1275        );
1276    }
1277
1278    #[test]
1279    fn from_bash_to_native_bare_name() {
1280        assert_eq!(from_bash_to_native_path("lean-ctx"), "lean-ctx");
1281    }
1282
1283    #[test]
1284    fn windows_path_to_bash_form() {
1285        let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1286        let bash = to_bash_compatible_path(native);
1287        assert_eq!(bash, "/c/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1288    }
1289
1290    // The bash→native return leg only translates on Windows hosts (GH #397).
1291    #[cfg(windows)]
1292    #[test]
1293    fn roundtrip_windows_path() {
1294        let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1295        let bash = to_bash_compatible_path(native);
1296        let back = from_bash_to_native_path(&bash);
1297        assert_eq!(back, "C:/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1298    }
1299
1300    #[test]
1301    fn roundtrip_unix_path() {
1302        let native = "/usr/local/bin/lean-ctx";
1303        let bash = to_bash_compatible_path(native);
1304        assert_eq!(bash, native);
1305        let back = from_bash_to_native_path(&bash);
1306        assert_eq!(back, native);
1307    }
1308}