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/// * `CliRedirect` — CLI-first; agent has reliable shell access, so bash
10///   commands are rewritten to `lean-ctx -c "…"`.
11/// * `Hybrid` — MCP server + CLI redirect (agent has shell, both paths active).
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum HookMode {
15    #[default]
16    Mcp,
17    CliRedirect,
18    Hybrid,
19}
20
21impl std::fmt::Display for HookMode {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            Self::Mcp => write!(f, "MCP"),
25            Self::CliRedirect => write!(f, "CLI-redirect"),
26            Self::Hybrid => write!(f, "Hybrid"),
27        }
28    }
29}
30
31impl HookMode {
32    pub fn from_str_loose(s: &str) -> Option<Self> {
33        match s.to_lowercase().replace('-', "").as_str() {
34            "mcp" => Some(Self::Mcp),
35            "cliredirect" | "cli" => Some(Self::CliRedirect),
36            "hybrid" => Some(Self::Hybrid),
37            _ => None,
38        }
39    }
40
41    pub fn description(&self) -> &'static str {
42        match self {
43            Self::Mcp => "MCP server only (extension/plugin-based agents without reliable shell)",
44            Self::CliRedirect => {
45                "CLI-first (agent has shell access; commands rewritten to lean-ctx)"
46            }
47            Self::Hybrid => "MCP server + CLI redirect (agent has shell, both paths active)",
48        }
49    }
50}
51
52/// Auto-detect the best hook mode for a given agent key based on its shell capabilities.
53///
54/// Criteria (verified against provider docs May 2026):
55///   CliRedirect — agent has verified hooks for ALL tool types (bash + read + grep)
56///                 AND we can guarantee interception in every execution mode
57///   Hybrid      — MCP server (full Context OS) + CLI hooks where available
58///   Mcp         — agent has no reliable direct shell tool (e.g. IDE plugin only)
59///
60/// Hybrid is the safe default: it ensures graph, knowledge, sessions, and all
61/// background automations work (these require the MCP server). CLI-Redirect
62/// only for agents where hooks demonstrably intercept every tool call.
63pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
64    match agent_key {
65        // CLI-Redirect: hooks verified to intercept ALL tool types (bash + read + grep)
66        // in every execution mode the agent offers.
67        // Cursor: hooks.json with Shell + Read|Grep matchers.
68        // Gemini CLI: BeforeTool for shell + read_file + grep + list_dir.
69        "cursor" | "gemini" => HookMode::CliRedirect,
70
71        // Hybrid: MCP for Context OS features + hooks/rules for shell compression.
72        // Codex: CLI variant has Bash hooks, but Desktop/Cloud variants need MCP.
73        //   Shared config (~/.codex/config.toml) → Hybrid covers all three.
74        // Claude Code: PreToolUse hooks don't fire in -p mode; needs MCP.
75        // CRUSH/Hermes: no hooks at all, rules only → need MCP as reliable path.
76        // OpenCode/Qoder: Bash hook only, no Read/Grep interception → need MCP.
77        // Pi: external package routing, can't verify → need MCP.
78        "codex" | "claude" | "claude-code" | "crush" | "hermes" | "opencode" | "pi" | "qoder"
79        | "windsurf" | "amp" | "cline" | "roo" | "copilot" | "kiro" | "qwen" | "trae"
80        | "antigravity" | "amazonq" | "verdent" => HookMode::Hybrid,
81
82        // No reliable direct shell tool → MCP only
83        _ => HookMode::Mcp,
84    }
85}
86use agents::{
87    install_amp_hook, install_antigravity_hook, install_claude_hook_config,
88    install_claude_hook_scripts, install_claude_hook_with_mode, install_claude_project_hooks,
89    install_cline_rules, install_codex_hook, install_copilot_hook, install_crush_hook_with_mode,
90    install_cursor_hook_config, install_cursor_hook_scripts, install_cursor_hook_with_mode,
91    install_gemini_hook, install_gemini_hook_config, install_gemini_hook_scripts,
92    install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
93    install_opencode_hook_with_mode, install_pi_hook_with_mode, install_qoder_hook_with_mode,
94    install_windsurf_rules,
95};
96use support::{
97    ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
98    upsert_lean_ctx_codex_hook_entries,
99};
100
101fn mcp_server_quiet_mode() -> bool {
102    std::env::var_os("LEAN_CTX_MCP_SERVER").is_some()
103        || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(value) if value.trim() == "1")
104}
105
106/// Silently refresh all hook scripts for agents that are already configured.
107/// Called after updates and on MCP server start to ensure hooks match the current binary version.
108pub fn refresh_installed_hooks() {
109    let Some(home) = crate::core::home::resolve_home_dir() else {
110        return;
111    };
112
113    let claude_dir = crate::setup::claude_config_dir(&home);
114    let claude_hooks = claude_dir.join("hooks/lean-ctx-rewrite.sh").exists()
115        || claude_dir.join("settings.json").exists()
116            && std::fs::read_to_string(claude_dir.join("settings.json"))
117                .unwrap_or_default()
118                .contains("lean-ctx");
119
120    if claude_hooks {
121        install_claude_hook_scripts(&home);
122        install_claude_hook_config(&home);
123    }
124
125    let cursor_hooks = home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
126        || home.join(".cursor/hooks.json").exists()
127            && std::fs::read_to_string(home.join(".cursor/hooks.json"))
128                .unwrap_or_default()
129                .contains("lean-ctx");
130
131    if cursor_hooks {
132        install_cursor_hook_scripts(&home);
133        install_cursor_hook_config(&home);
134    }
135
136    let gemini_rewrite = home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh");
137    let gemini_legacy = home.join(".gemini/hooks/lean-ctx-hook-gemini.sh");
138    if gemini_rewrite.exists() || gemini_legacy.exists() {
139        install_gemini_hook_scripts(&home);
140        install_gemini_hook_config(&home);
141    }
142
143    let codex_hooks = home.join(".codex/hooks/lean-ctx-rewrite-codex.sh").exists()
144        || home.join(".codex/hooks.json").exists()
145            && std::fs::read_to_string(home.join(".codex/hooks.json"))
146                .unwrap_or_default()
147                .contains("lean-ctx");
148
149    if codex_hooks {
150        install_codex_hook();
151    }
152}
153
154fn resolve_binary_path() -> String {
155    if is_lean_ctx_in_path() {
156        return "lean-ctx".to_string();
157    }
158    crate::core::portable_binary::resolve_portable_binary()
159}
160
161fn is_lean_ctx_in_path() -> bool {
162    let which_cmd = if cfg!(windows) { "where" } else { "which" };
163    std::process::Command::new(which_cmd)
164        .arg("lean-ctx")
165        .stdout(std::process::Stdio::null())
166        .stderr(std::process::Stdio::null())
167        .status()
168        .is_ok_and(|s| s.success())
169}
170
171fn resolve_binary_path_for_bash() -> String {
172    let path = resolve_binary_path();
173    to_bash_compatible_path(&path)
174}
175
176pub fn to_bash_compatible_path(path: &str) -> String {
177    let path = match crate::core::pathutil::strip_verbatim_str(path) {
178        Some(stripped) => stripped,
179        None => path.replace('\\', "/"),
180    };
181    if path.len() >= 2 && path.as_bytes()[1] == b':' {
182        let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
183        format!("/{drive}{}", &path[2..])
184    } else {
185        path
186    }
187}
188
189/// Normalize paths from any client format to a consistent OS-native form.
190/// Delegates to `core::pathutil` so `core` crates do not depend on `hooks`.
191pub fn normalize_tool_path(path: &str) -> String {
192    crate::core::pathutil::normalize_tool_path(path)
193}
194
195pub fn generate_rewrite_script(binary: &str) -> String {
196    let case_pattern = crate::rewrite_registry::bash_case_pattern();
197    format!(
198        r#"#!/usr/bin/env bash
199# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
200set -euo pipefail
201
202LEAN_CTX_BIN="{binary}"
203
204INPUT=$(cat)
205TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
206
207case "$TOOL" in
208  Bash|bash|PowerShell|powershell) ;;
209  *) exit 0 ;;
210esac
211
212CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
213
214if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
215  exit 0
216fi
217
218case "$CMD" in
219  {case_pattern})
220    # Shell-escape then JSON-escape (two passes)
221    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
222    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
223    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
224    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
225    ;;
226  *) exit 0 ;;
227esac
228"#
229    )
230}
231
232pub fn generate_compact_rewrite_script(binary: &str) -> String {
233    let case_pattern = crate::rewrite_registry::bash_case_pattern();
234    format!(
235        r#"#!/usr/bin/env bash
236# lean-ctx hook — rewrites shell commands
237set -euo pipefail
238LEAN_CTX_BIN="{binary}"
239INPUT=$(cat)
240CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
241if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
242case "$CMD" in
243  {case_pattern})
244    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
245    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
246    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
247    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
248  *) exit 0 ;;
249esac
250"#
251    )
252}
253
254const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
255# lean-ctx PreToolUse hook — all native tools pass through
256# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
257# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
258exit 0
259";
260
261const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
262# lean-ctx hook — all native tools pass through
263exit 0
264";
265
266pub(crate) const CLI_REDIRECT_RULES: &str = "\
267# lean-ctx — CLI-Redirect Mode
268
269PREFER lean-ctx CLI commands over MCP tools for token savings (no MCP schema overhead):
270
271| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
272|---------------------|-------------------|-----|
273| `lean-ctx read <path>` | `ctx_read` | No MCP schema overhead, same caching |
274| `lean-ctx read <path> -m map` | `ctx_read(mode=\"map\")` | Compressed output via CLI |
275| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | Pattern compression via CLI |
276| `lean-ctx grep <pattern> [path]` | `ctx_search` | Compact results via CLI |
277| `lean-ctx ls [path]` | `ctx_tree` | Directory maps via CLI |
278
279## Usage via Shell
280
281Run lean-ctx commands through your Shell/Bash tool:
282```
283lean-ctx read src/main.rs
284lean-ctx read src/main.rs -m signatures
285lean-ctx -c \"cargo test\"
286lean-ctx grep \"fn main\" src/
287lean-ctx ls src/
288```
289
290## Read modes (same as MCP):
291auto | full | map | signatures | diff | aggressive | entropy | task | reference | lines:N-M
292
293## File editing:
294Use native Edit/StrReplace — lean-ctx only handles READ operations.
295Write, Delete, Glob → use normally.
296";
297
298pub(crate) const HYBRID_RULES: &str = "\
299# lean-ctx — Hybrid Mode (MCP reads + CLI commands)
300
301Use MCP tools for reads (cache benefit), CLI commands for everything else (no schema overhead):
302
303## MCP tools (keep using):
304| Tool | Why MCP |
305|------|---------|
306| `ctx_read(path, mode)` | In-process cache, re-reads ~13 tokens |
307
308## CLI commands (via Shell/Bash):
309| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
310|---------------------|-------------------|-----|
311| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | No MCP schema overhead |
312| `lean-ctx grep <pattern> [path]` | `ctx_search` | No MCP schema overhead |
313| `lean-ctx ls [path]` | `ctx_tree` | No MCP schema overhead |
314
315## File editing:
316Use native Edit/StrReplace — lean-ctx only handles READ operations.
317Write, Delete, Glob → use normally.
318";
319
320pub fn install_project_rules() {
321    install_project_rules_for_agents(&[]);
322}
323
324/// Install project rules, optionally scoped to specific agents.
325/// If `agents` is empty, installs for all agents (legacy behavior).
326pub fn install_project_rules_for_agents(agents: &[&str]) {
327    if crate::core::config::Config::load().rules_scope_effective()
328        == crate::core::config::RulesScope::Global
329    {
330        return;
331    }
332
333    let cwd = std::env::current_dir().unwrap_or_default();
334
335    if !is_inside_git_repo(&cwd) {
336        eprintln!(
337            "  Skipping project files: not inside a git repository.\n  \
338             Run this command from your project root to create CLAUDE.md / AGENTS.md."
339        );
340        return;
341    }
342
343    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
344    if cwd == home {
345        eprintln!(
346            "  Skipping project files: current directory is your home folder.\n  \
347             Run this command from a project directory instead."
348        );
349        return;
350    }
351
352    let all = agents.is_empty();
353    let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
354
355    ensure_project_agents_integration(&cwd);
356
357    if wants("cursor") || wants("windsurf") {
358        let cursorrules = cwd.join(".cursorrules");
359        if !cursorrules.exists()
360            || !std::fs::read_to_string(&cursorrules)
361                .unwrap_or_default()
362                .contains("lean-ctx")
363        {
364            let content = CURSORRULES_TEMPLATE;
365            if cursorrules.exists() {
366                let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
367                if !existing.ends_with('\n') {
368                    existing.push('\n');
369                }
370                existing.push('\n');
371                existing.push_str(content);
372                write_file(&cursorrules, &existing);
373            } else {
374                write_file(&cursorrules, content);
375            }
376            if !mcp_server_quiet_mode() {
377                eprintln!("Created/updated .cursorrules in project root.");
378            }
379        }
380    }
381
382    if wants("claude") {
383        let claude_rules_dir = cwd.join(".claude").join("rules");
384        let claude_rules_file = claude_rules_dir.join("lean-ctx.md");
385        if !claude_rules_file.exists()
386            || !std::fs::read_to_string(&claude_rules_file)
387                .unwrap_or_default()
388                .contains(crate::rules_inject::RULES_VERSION_STR)
389        {
390            let _ = std::fs::create_dir_all(&claude_rules_dir);
391            write_file(
392                &claude_rules_file,
393                crate::rules_inject::rules_dedicated_markdown(),
394            );
395            if !mcp_server_quiet_mode() {
396                eprintln!("Created .claude/rules/lean-ctx.md (Claude Code project rules).");
397            }
398        }
399
400        install_claude_project_hooks(&cwd);
401    }
402
403    if wants("kiro") {
404        let kiro_dir = cwd.join(".kiro");
405        if kiro_dir.exists() {
406            let steering_dir = kiro_dir.join("steering");
407            let steering_file = steering_dir.join("lean-ctx.md");
408            if !steering_file.exists()
409                || !std::fs::read_to_string(&steering_file)
410                    .unwrap_or_default()
411                    .contains("lean-ctx")
412            {
413                let _ = std::fs::create_dir_all(&steering_dir);
414                write_file(&steering_file, KIRO_STEERING_TEMPLATE);
415                if !mcp_server_quiet_mode() {
416                    eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
417                }
418            }
419        }
420    }
421}
422
423const PROJECT_LEAN_CTX_MD_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
424const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
425const PROJECT_AGENTS_MD: &str = "AGENTS.md";
426const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
427const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
428
429fn ensure_project_agents_integration(cwd: &std::path::Path) {
430    let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
431    let desired = format!(
432        "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
433        crate::rules_inject::rules_dedicated_markdown()
434    );
435
436    if !lean_ctx_md.exists() {
437        write_file(&lean_ctx_md, &desired);
438    } else if std::fs::read_to_string(&lean_ctx_md)
439        .unwrap_or_default()
440        .contains(PROJECT_LEAN_CTX_MD_MARKER)
441    {
442        let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
443        if !current.contains(crate::rules_inject::RULES_VERSION_STR) {
444            write_file(&lean_ctx_md, &desired);
445        }
446    }
447
448    let block = format!(
449        "{AGENTS_BLOCK_START}\n\
450## lean-ctx\n\n\
451Prefer lean-ctx MCP tools over native equivalents for token savings.\n\
452Full rules: @{PROJECT_LEAN_CTX_MD}\n\
453{AGENTS_BLOCK_END}\n"
454    );
455
456    let agents_md = cwd.join(PROJECT_AGENTS_MD);
457    if !agents_md.exists() {
458        let content = format!("# Agent Instructions\n\n{block}");
459        write_file(&agents_md, &content);
460        if !mcp_server_quiet_mode() {
461            eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
462        }
463        return;
464    }
465
466    let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
467
468    if existing.contains("CLI-first Token Optimization for Pi")
469        && !existing.contains(AGENTS_BLOCK_START)
470    {
471        let content = format!("# Agent Instructions\n\n{block}");
472        write_file(&agents_md, &content);
473        return;
474    }
475
476    if existing.contains(AGENTS_BLOCK_START) {
477        let updated = crate::marked_block::replace_marked_block(
478            &existing,
479            AGENTS_BLOCK_START,
480            AGENTS_BLOCK_END,
481            &block,
482        );
483        if updated != existing {
484            write_file(&agents_md, &updated);
485        }
486        return;
487    }
488
489    if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
490        return;
491    }
492
493    let mut out = existing;
494    if !out.ends_with('\n') {
495        out.push('\n');
496    }
497    out.push('\n');
498    out.push_str(&block);
499    write_file(&agents_md, &out);
500    if !mcp_server_quiet_mode() {
501        eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
502    }
503}
504
505const CURSORRULES_TEMPLATE: &str = "\
506# lean-ctx — Context Engineering Layer
507
508PREFER lean-ctx MCP tools over native equivalents for token savings:
509
510| PREFER | OVER | Why |
511|--------|------|-----|
512| `ctx_read(path)` | `Read` | Cached, 10 compression modes |
513| `ctx_shell(command)` | `Shell` | Pattern compression |
514| `ctx_search(pattern, path)` | `Grep` | Compact results |
515| `ctx_tree(path, depth)` | `ls` / `find` | Directory maps |
516| `ctx_edit(path, old_string, new_string)` | `Edit` (when Read unavailable) | Search-and-replace without native Read |
517
518Edit files: use native Edit/StrReplace if available. If Edit requires Read and Read is unavailable, use ctx_edit.
519Write, Delete, Glob — use normally. NEVER loop on Edit failures — switch to ctx_edit immediately.
520";
521
522pub const KIRO_STEERING_TEMPLATE: &str = "\
523---
524inclusion: always
525---
526
527# lean-ctx — Context Engineering Layer
528
529The workspace has the `lean-ctx` MCP server installed. You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.
530
531## Mandatory Tool Preferences
532
533| Use this | Instead of | Why |
534|----------|-----------|-----|
535| `mcp_lean_ctx_ctx_read` | `readFile`, `readCode` | Cached reads, 10 compression modes, re-reads cost ~13 tokens |
536| `mcp_lean_ctx_ctx_multi_read` | `readMultipleFiles` | Batch cached reads in one call |
537| `mcp_lean_ctx_ctx_shell` | `executeBash` | Pattern compression for git/npm/test output |
538| `mcp_lean_ctx_ctx_search` | `grepSearch` | Compact, .gitignore-aware results |
539| `mcp_lean_ctx_ctx_tree` | `listDirectory` | Compact directory maps with file counts |
540
541## When to use native Kiro tools instead
542
543- `fsWrite` / `fsAppend` — always use native (lean-ctx doesn't write files)
544- `strReplace` — always use native (precise string replacement)
545- `semanticRename` / `smartRelocate` — always use native (IDE integration)
546- `getDiagnostics` — always use native (language server diagnostics)
547- `deleteFile` — always use native
548
549## Session management
550
551- At the start of a long task, call `mcp_lean_ctx_ctx_preload` with a task description to warm the cache
552- Use `mcp_lean_ctx_ctx_compress` periodically in long conversations to checkpoint context
553- Use `mcp_lean_ctx_ctx_knowledge` to persist important discoveries across sessions
554
555## Rules
556
557- NEVER loop on edit failures — switch to `mcp_lean_ctx_ctx_edit` immediately
558- For large files, use `mcp_lean_ctx_ctx_read` with `mode: \"signatures\"` or `mode: \"map\"` first
559- For re-reading a file you already read, just call `mcp_lean_ctx_ctx_read` again (cache hit = ~13 tokens)
560- When running tests or build commands, use `mcp_lean_ctx_ctx_shell` for compressed output
561";
562
563pub fn install_agent_hook(agent: &str, global: bool) {
564    install_agent_hook_with_mode(agent, global, HookMode::Mcp);
565}
566
567pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
568    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
569    match agent {
570        "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
571        "cursor" => install_cursor_hook_with_mode(global, mode),
572        "gemini" => install_gemini_hook(),
573        "antigravity" => install_antigravity_hook(),
574        "codex" => install_codex_hook(),
575        "windsurf" => install_windsurf_rules(global),
576        "cline" | "roo" => install_cline_rules(global),
577        "copilot" | "vscode" => install_copilot_hook(global),
578        "pi" => install_pi_hook_with_mode(global, mode),
579        "qoder" => install_qoder_hook_with_mode(mode),
580        "qoderwork" => install_mcp_json_agent(
581            "QoderWork",
582            "~/.qoderwork/mcp.json",
583            &home.join(".qoderwork/mcp.json"),
584        ),
585        "qwen" => install_mcp_json_agent(
586            "Qwen Code",
587            "~/.qwen/settings.json",
588            &home.join(".qwen/settings.json"),
589        ),
590        "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
591        "amazonq" => install_mcp_json_agent(
592            "Amazon Q Developer",
593            "~/.aws/amazonq/default.json",
594            &home.join(".aws/amazonq/default.json"),
595        ),
596        "jetbrains" => install_jetbrains_hook(),
597        "kiro" => install_kiro_hook(),
598        "verdent" => install_mcp_json_agent(
599            "Verdent",
600            "~/.verdent/mcp.json",
601            &home.join(".verdent/mcp.json"),
602        ),
603        "opencode" => install_opencode_hook_with_mode(mode),
604        "amp" => install_amp_hook(),
605        "crush" => install_crush_hook_with_mode(mode),
606        "hermes" => install_hermes_hook_with_mode(global, mode),
607        "zed" => {
608            let zed_path = crate::core::editor_registry::zed_settings_path(&home);
609            let binary = resolve_binary_path();
610            let entry = full_server_entry(&binary);
611            install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
612        }
613        "aider" => {
614            install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
615        }
616        "continue" => install_mcp_json_agent(
617            "Continue",
618            "~/.continue/mcp.json",
619            &home.join(".continue/mcp.json"),
620        ),
621        "neovim" => install_mcp_json_agent(
622            "Neovim (mcphub.nvim)",
623            "~/.config/mcphub/servers.json",
624            &home.join(".config/mcphub/servers.json"),
625        ),
626        "emacs" => install_mcp_json_agent(
627            "Emacs (mcp.el)",
628            "~/.emacs.d/mcp.json",
629            &home.join(".emacs.d/mcp.json"),
630        ),
631        "sublime" => install_mcp_json_agent(
632            "Sublime Text",
633            "~/.config/sublime-text/mcp.json",
634            &home.join(".config/sublime-text/mcp.json"),
635        ),
636        _ => {
637            eprintln!("Unknown agent: {agent}");
638            eprintln!("  Supported: aider, amazonq, amp, antigravity, claude, cline, codex,");
639            eprintln!("    continue, copilot, crush, cursor, emacs, gemini, hermes, jetbrains,");
640            eprintln!("    kiro, neovim, opencode, pi, qoder, qoderwork, qwen, roo, sublime,");
641            eprintln!("    trae, verdent, vscode, windsurf, zed");
642            std::process::exit(1);
643        }
644    }
645}
646
647pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
648    match agent {
649        "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
650        _ => {}
651    }
652}
653
654fn write_file(path: &std::path::Path, content: &str) {
655    if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
656        tracing::error!("Error writing {}: {e}", path.display());
657    }
658}
659
660fn is_inside_git_repo(path: &std::path::Path) -> bool {
661    let mut p = path;
662    loop {
663        if p.join(".git").exists() {
664            return true;
665        }
666        match p.parent() {
667            Some(parent) => p = parent,
668            None => return false,
669        }
670    }
671}
672
673#[cfg(unix)]
674fn make_executable(path: &PathBuf) {
675    use std::os::unix::fs::PermissionsExt;
676    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
677}
678
679#[cfg(not(unix))]
680fn make_executable(_path: &PathBuf) {}
681
682fn full_server_entry(binary: &str) -> serde_json::Value {
683    let data_dir = crate::core::data_dir::lean_ctx_data_dir()
684        .map(|d| d.to_string_lossy().to_string())
685        .unwrap_or_default();
686    serde_json::json!({
687        "command": binary,
688        "env": {
689            "LEAN_CTX_DATA_DIR": data_dir,
690            "LEAN_CTX_FULL_TOOLS": "1"
691        }
692    })
693}
694
695pub(crate) fn install_mcp_json_agent(
696    name: &str,
697    display_path: &str,
698    config_path: &std::path::Path,
699) {
700    let binary = resolve_binary_path();
701    let entry = full_server_entry(&binary);
702    install_named_json_server(name, display_path, config_path, "mcpServers", entry);
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    #[test]
710    fn bash_path_unix_unchanged() {
711        assert_eq!(
712            to_bash_compatible_path("/usr/local/bin/lean-ctx"),
713            "/usr/local/bin/lean-ctx"
714        );
715    }
716
717    #[test]
718    fn bash_path_home_unchanged() {
719        assert_eq!(
720            to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
721            "/home/user/.cargo/bin/lean-ctx"
722        );
723    }
724
725    #[test]
726    fn bash_path_windows_drive_converted() {
727        assert_eq!(
728            to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
729            "/c/Users/Fraser/bin/lean-ctx.exe"
730        );
731    }
732
733    #[test]
734    fn bash_path_windows_lowercase_drive() {
735        assert_eq!(
736            to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
737            "/d/tools/lean-ctx.exe"
738        );
739    }
740
741    #[test]
742    fn bash_path_windows_forward_slashes() {
743        assert_eq!(
744            to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
745            "/c/Users/Fraser/bin/lean-ctx.exe"
746        );
747    }
748
749    #[test]
750    fn bash_path_bare_name_unchanged() {
751        assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
752    }
753
754    #[test]
755    fn normalize_msys2_path() {
756        assert_eq!(
757            normalize_tool_path("/c/Users/game/Downloads/project"),
758            "C:/Users/game/Downloads/project"
759        );
760    }
761
762    #[test]
763    fn normalize_msys2_drive_d() {
764        assert_eq!(
765            normalize_tool_path("/d/Projects/app/src"),
766            "D:/Projects/app/src"
767        );
768    }
769
770    #[test]
771    fn normalize_backslashes() {
772        assert_eq!(
773            normalize_tool_path("C:\\Users\\game\\project\\src"),
774            "C:/Users/game/project/src"
775        );
776    }
777
778    #[test]
779    fn normalize_mixed_separators() {
780        assert_eq!(
781            normalize_tool_path("C:\\Users/game\\project/src"),
782            "C:/Users/game/project/src"
783        );
784    }
785
786    #[test]
787    fn normalize_double_slashes() {
788        assert_eq!(
789            normalize_tool_path("/home/user//project///src"),
790            "/home/user/project/src"
791        );
792    }
793
794    #[test]
795    fn normalize_trailing_slash() {
796        assert_eq!(
797            normalize_tool_path("/home/user/project/"),
798            "/home/user/project"
799        );
800    }
801
802    #[test]
803    fn normalize_root_preserved() {
804        assert_eq!(normalize_tool_path("/"), "/");
805    }
806
807    #[test]
808    fn normalize_windows_root_preserved() {
809        assert_eq!(normalize_tool_path("C:/"), "C:/");
810    }
811
812    #[test]
813    fn normalize_unix_path_unchanged() {
814        assert_eq!(
815            normalize_tool_path("/home/user/project/src/main.rs"),
816            "/home/user/project/src/main.rs"
817        );
818    }
819
820    #[test]
821    fn normalize_relative_path_unchanged() {
822        assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
823    }
824
825    #[test]
826    fn normalize_dot_unchanged() {
827        assert_eq!(normalize_tool_path("."), ".");
828    }
829
830    #[test]
831    fn normalize_unc_path_preserved() {
832        assert_eq!(
833            normalize_tool_path("//server/share/file"),
834            "//server/share/file"
835        );
836    }
837
838    #[test]
839    fn cursor_hook_config_has_version_and_object_hooks() {
840        let config = serde_json::json!({
841            "version": 1,
842            "hooks": {
843                "preToolUse": [
844                    {
845                        "matcher": "terminal_command",
846                        "command": "lean-ctx hook rewrite"
847                    },
848                    {
849                        "matcher": "read_file|grep|search|list_files|list_directory",
850                        "command": "lean-ctx hook redirect"
851                    }
852                ]
853            }
854        });
855
856        let json_str = serde_json::to_string_pretty(&config).unwrap();
857        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
858
859        assert_eq!(parsed["version"], 1);
860        assert!(parsed["hooks"].is_object());
861        assert!(parsed["hooks"]["preToolUse"].is_array());
862        assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
863        assert_eq!(
864            parsed["hooks"]["preToolUse"][0]["matcher"],
865            "terminal_command"
866        );
867    }
868
869    #[test]
870    fn cursor_hook_detects_old_format_needs_migration() {
871        let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
872        let has_correct =
873            old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
874        assert!(
875            !has_correct,
876            "Old format should be detected as needing migration"
877        );
878    }
879
880    #[test]
881    fn gemini_hook_config_has_type_command() {
882        let binary = "lean-ctx";
883        let rewrite_cmd = format!("{binary} hook rewrite");
884        let redirect_cmd = format!("{binary} hook redirect");
885
886        let hook_config = serde_json::json!({
887            "hooks": {
888                "BeforeTool": [
889                    {
890                        "hooks": [{
891                            "type": "command",
892                            "command": rewrite_cmd
893                        }]
894                    },
895                    {
896                        "hooks": [{
897                            "type": "command",
898                            "command": redirect_cmd
899                        }]
900                    }
901                ]
902            }
903        });
904
905        let parsed = hook_config;
906        let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
907        assert_eq!(before_tool.len(), 2);
908
909        let first_hook = &before_tool[0]["hooks"][0];
910        assert_eq!(first_hook["type"], "command");
911        assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
912
913        let second_hook = &before_tool[1]["hooks"][0];
914        assert_eq!(second_hook["type"], "command");
915        assert_eq!(second_hook["command"], "lean-ctx hook redirect");
916    }
917
918    #[test]
919    fn gemini_hook_old_format_detected() {
920        let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
921        let has_new = old_format.contains("hook rewrite")
922            && old_format.contains("hook redirect")
923            && old_format.contains("\"type\"");
924        assert!(!has_new, "Missing 'type' field should trigger migration");
925    }
926
927    #[test]
928    fn rewrite_script_uses_registry_pattern() {
929        let script = generate_rewrite_script("/usr/bin/lean-ctx");
930        assert!(script.contains(r"git\ *"), "script missing git pattern");
931        assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
932        assert!(script.contains(r"npm\ *"), "script missing npm pattern");
933        assert!(
934            !script.contains(r"rg\ *"),
935            "script should not contain rg pattern"
936        );
937        assert!(
938            script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
939            "script missing binary path"
940        );
941        assert!(
942            script.contains("PowerShell|powershell"),
943            "rewrite script must accept PowerShell tool names for Windows compatibility"
944        );
945    }
946
947    #[test]
948    fn compact_rewrite_script_uses_registry_pattern() {
949        let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
950        assert!(script.contains(r"git\ *"), "compact script missing git");
951        assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
952        assert!(
953            !script.contains(r"rg\ *"),
954            "compact script should not contain rg"
955        );
956    }
957
958    #[test]
959    fn rewrite_scripts_contain_all_registry_commands() {
960        let script = generate_rewrite_script("lean-ctx");
961        let compact = generate_compact_rewrite_script("lean-ctx");
962        for entry in crate::rewrite_registry::REWRITE_COMMANDS {
963            if matches!(
964                entry.category,
965                crate::rewrite_registry::Category::Search
966                    | crate::rewrite_registry::Category::FileRead
967            ) {
968                continue;
969            }
970            let pattern = if entry.command.contains('-') {
971                format!("{}*", entry.command.replace('-', r"\-"))
972            } else {
973                format!(r"{}\ *", entry.command)
974            };
975            assert!(
976                script.contains(&pattern),
977                "rewrite_script missing '{}' (pattern: {})",
978                entry.command,
979                pattern
980            );
981            assert!(
982                compact.contains(&pattern),
983                "compact_rewrite_script missing '{}' (pattern: {})",
984                entry.command,
985                pattern
986            );
987        }
988    }
989
990    #[test]
991    fn codex_is_hybrid_not_cli_redirect() {
992        assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
993    }
994
995    #[test]
996    fn cursor_remains_cli_redirect() {
997        assert_eq!(recommend_hook_mode("cursor"), HookMode::CliRedirect);
998    }
999
1000    #[test]
1001    fn gemini_remains_cli_redirect() {
1002        assert_eq!(recommend_hook_mode("gemini"), HookMode::CliRedirect);
1003    }
1004
1005    #[test]
1006    fn claude_is_hybrid() {
1007        assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
1008    }
1009
1010    #[test]
1011    fn unknown_agent_falls_back_to_mcp() {
1012        assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
1013    }
1014}