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