Skip to main content

lean_ctx/
hooks.rs

1use std::path::PathBuf;
2
3fn mcp_server_quiet_mode() -> bool {
4    std::env::var_os("LEAN_CTX_MCP_SERVER").is_some()
5}
6
7/// Silently refresh all hook scripts for agents that are already configured.
8/// Called after updates and on MCP server start to ensure hooks match the current binary version.
9pub fn refresh_installed_hooks() {
10    let home = match dirs::home_dir() {
11        Some(h) => h,
12        None => return,
13    };
14
15    let claude_hooks = home.join(".claude/hooks/lean-ctx-rewrite.sh").exists()
16        || home.join(".claude/settings.json").exists()
17            && std::fs::read_to_string(home.join(".claude/settings.json"))
18                .unwrap_or_default()
19                .contains("lean-ctx");
20
21    if claude_hooks {
22        install_claude_hook_scripts(&home);
23        install_claude_hook_config(&home);
24    }
25
26    let cursor_hooks = home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
27        || home.join(".cursor/hooks.json").exists()
28            && std::fs::read_to_string(home.join(".cursor/hooks.json"))
29                .unwrap_or_default()
30                .contains("lean-ctx");
31
32    if cursor_hooks {
33        install_cursor_hook_scripts(&home);
34        install_cursor_hook_config(&home);
35    }
36
37    let gemini_rewrite = home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh");
38    let gemini_legacy = home.join(".gemini/hooks/lean-ctx-hook-gemini.sh");
39    if gemini_rewrite.exists() || gemini_legacy.exists() {
40        install_gemini_hook_scripts(&home);
41        install_gemini_hook_config(&home);
42    }
43
44    if home.join(".codex/hooks/lean-ctx-rewrite-codex.sh").exists() {
45        install_codex_hook_scripts(&home);
46    }
47}
48
49fn resolve_binary_path() -> String {
50    if is_lean_ctx_in_path() {
51        return "lean-ctx".to_string();
52    }
53    std::env::current_exe()
54        .map(|p| p.to_string_lossy().to_string())
55        .unwrap_or_else(|_| "lean-ctx".to_string())
56}
57
58fn is_lean_ctx_in_path() -> bool {
59    let which_cmd = if cfg!(windows) { "where" } else { "which" };
60    std::process::Command::new(which_cmd)
61        .arg("lean-ctx")
62        .stdout(std::process::Stdio::null())
63        .stderr(std::process::Stdio::null())
64        .status()
65        .map(|s| s.success())
66        .unwrap_or(false)
67}
68
69fn resolve_binary_path_for_bash() -> String {
70    let path = resolve_binary_path();
71    to_bash_compatible_path(&path)
72}
73
74pub fn to_bash_compatible_path(path: &str) -> String {
75    let path = path.replace('\\', "/");
76    if path.len() >= 2 && path.as_bytes()[1] == b':' {
77        let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
78        format!("/{drive}{}", &path[2..])
79    } else {
80        path
81    }
82}
83
84/// Normalize paths from any client format to a consistent OS-native form.
85/// Handles MSYS2/Git Bash (`/c/Users/...` -> `C:/Users/...`), mixed separators,
86/// double slashes, and trailing slashes. Always uses forward slashes for consistency.
87pub fn normalize_tool_path(path: &str) -> String {
88    let mut p = path.to_string();
89
90    // MSYS2/Git Bash: /c/Users/... -> C:/Users/...
91    if p.len() >= 3
92        && p.starts_with('/')
93        && p.as_bytes()[1].is_ascii_alphabetic()
94        && p.as_bytes()[2] == b'/'
95    {
96        let drive = p.as_bytes()[1].to_ascii_uppercase() as char;
97        p = format!("{drive}:{}", &p[2..]);
98    }
99
100    p = p.replace('\\', "/");
101
102    // Collapse double slashes (preserve UNC paths starting with //)
103    while p.contains("//") && !p.starts_with("//") {
104        p = p.replace("//", "/");
105    }
106
107    // Remove trailing slash (unless root like "/" or "C:/")
108    if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
109        p.pop();
110    }
111
112    p
113}
114
115fn generate_rewrite_script(binary: &str) -> String {
116    format!(
117        r#"#!/usr/bin/env bash
118# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
119set -euo pipefail
120
121LEAN_CTX_BIN="{binary}"
122
123INPUT=$(cat)
124TOOL=$(echo "$INPUT" | grep -o '"tool_name":"[^"]*"' | head -1 | cut -d'"' -f4)
125
126if [ "$TOOL" != "Bash" ] && [ "$TOOL" != "bash" ]; then
127  exit 0
128fi
129
130CMD=$(echo "$INPUT" | grep -o '"command":"[^"]*"' | head -1 | cut -d'"' -f4)
131
132if echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
133  exit 0
134fi
135
136REWRITE=""
137case "$CMD" in
138  git\ *)       REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
139  gh\ *)        REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
140  cargo\ *)     REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
141  npm\ *)       REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
142  pnpm\ *)      REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
143  yarn\ *)      REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
144  docker\ *)    REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
145  kubectl\ *)   REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
146  pip\ *|pip3\ *)  REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
147  ruff\ *)      REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
148  go\ *)        REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
149  curl\ *)      REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
150  grep\ *|rg\ *)  REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
151  find\ *)      REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
152  cat\ *|head\ *|tail\ *)  REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
153  ls\ *|ls)     REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
154  eslint*|prettier*|tsc*)  REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
155  pytest*|ruff\ *|mypy*)   REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
156  aws\ *)       REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
157  helm\ *)      REWRITE="$LEAN_CTX_BIN -c $CMD" ;;
158  *)            exit 0 ;;
159esac
160
161if [ -n "$REWRITE" ]; then
162  echo "{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{{\"command\":\"$REWRITE\"}}}}}}"
163fi
164"#
165    )
166}
167
168fn generate_compact_rewrite_script(binary: &str) -> String {
169    format!(
170        r#"#!/usr/bin/env bash
171# lean-ctx hook — rewrites shell commands
172set -euo pipefail
173LEAN_CTX_BIN="{binary}"
174INPUT=$(cat)
175CMD=$(echo "$INPUT" | grep -o '"command":"[^"]*"' | head -1 | cut -d'"' -f4 2>/dev/null || echo "")
176if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
177case "$CMD" in
178  git\ *|gh\ *|cargo\ *|npm\ *|pnpm\ *|docker\ *|kubectl\ *|pip\ *|ruff\ *|go\ *|curl\ *|grep\ *|rg\ *|find\ *|ls\ *|ls|cat\ *|aws\ *|helm\ *)
179    echo "{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{{\"command\":\"$LEAN_CTX_BIN -c $CMD\"}}}}}}" ;;
180  *) exit 0 ;;
181esac
182"#
183    )
184}
185
186const REDIRECT_SCRIPT_CLAUDE: &str = r#"#!/usr/bin/env bash
187# lean-ctx PreToolUse hook — redirects Read/Grep/List to MCP equivalents
188set -euo pipefail
189
190INPUT=$(cat)
191TOOL=$(echo "$INPUT" | grep -o '"tool_name":"[^"]*"' | head -1 | cut -d'"' -f4 2>/dev/null || echo "")
192
193case "$TOOL" in
194  Read|read|ReadFile|read_file|View|view)
195    if pgrep -f "lean-ctx" >/dev/null 2>&1; then
196      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"STOP. Use ctx_read(path) from the lean-ctx MCP server instead. It saves 60-80% input tokens via caching and compression. Available modes: full, map, signatures, diff, lines:N-M. Never use native Read — always use ctx_read."}}'
197    fi
198    ;;
199  Grep|grep|Search|search|RipGrep|ripgrep)
200    if pgrep -f "lean-ctx" >/dev/null 2>&1; then
201      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"STOP. Use ctx_search(pattern, path) from the lean-ctx MCP server instead. It provides compact, token-efficient results with .gitignore awareness. Never use native Grep — always use ctx_search."}}'
202    fi
203    ;;
204  ListFiles|list_files|ListDirectory|list_directory)
205    if pgrep -f "lean-ctx" >/dev/null 2>&1; then
206      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"STOP. Use ctx_tree(path, depth) from the lean-ctx MCP server instead. It provides compact directory maps with file counts. Never use native ListFiles — always use ctx_tree."}}'
207    fi
208    ;;
209esac
210"#;
211
212const REDIRECT_SCRIPT_GENERIC: &str = r#"#!/usr/bin/env bash
213# lean-ctx hook — redirects Read/Grep to MCP equivalents
214set -euo pipefail
215
216INPUT=$(cat)
217TOOL=$(echo "$INPUT" | grep -o '"tool_name":"[^"]*"' | head -1 | cut -d'"' -f4 2>/dev/null || echo "")
218
219case "$TOOL" in
220  Read|read|ReadFile|read_file)
221    if pgrep -f "lean-ctx" >/dev/null 2>&1; then
222      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"STOP. Use ctx_read(path) from lean-ctx MCP instead. Saves 60-80% tokens."}}'
223    fi
224    ;;
225  Grep|grep|Search|search)
226    if pgrep -f "lean-ctx" >/dev/null 2>&1; then
227      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"STOP. Use ctx_search(pattern, path) from lean-ctx MCP instead."}}'
228    fi
229    ;;
230  ListFiles|list_files|ListDirectory|list_directory)
231    if pgrep -f "lean-ctx" >/dev/null 2>&1; then
232      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"STOP. Use ctx_tree(path, depth) from lean-ctx MCP instead."}}'
233    fi
234    ;;
235esac
236"#;
237
238pub fn install_project_rules() {
239    let cwd = std::env::current_dir().unwrap_or_default();
240
241    let agents_md = cwd.join("AGENTS.md");
242    if !agents_md.exists()
243        || !std::fs::read_to_string(&agents_md)
244            .unwrap_or_default()
245            .contains("lean-ctx")
246    {
247        let content = AGENTS_MD_TEMPLATE;
248        write_file(&agents_md, content);
249        println!("Created AGENTS.md in project root.");
250    }
251
252    let cursorrules = cwd.join(".cursorrules");
253    if !cursorrules.exists()
254        || !std::fs::read_to_string(&cursorrules)
255            .unwrap_or_default()
256            .contains("lean-ctx")
257    {
258        let content = CURSORRULES_TEMPLATE;
259        if cursorrules.exists() {
260            let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
261            if !existing.ends_with('\n') {
262                existing.push('\n');
263            }
264            existing.push('\n');
265            existing.push_str(content);
266            write_file(&cursorrules, &existing);
267        } else {
268            write_file(&cursorrules, content);
269        }
270        println!("Created/updated .cursorrules in project root.");
271    }
272}
273
274const AGENTS_MD_TEMPLATE: &str = "\
275# lean-ctx — Context Engineering Layer
276
277PREFER lean-ctx MCP tools over native equivalents for token savings:
278
279| PREFER | OVER | Why |
280|--------|------|-----|
281| `ctx_read(path)` | Read / cat / head / tail | Cached, 8 compression modes, re-reads ~13 tokens |
282| `ctx_shell(command)` | Shell / bash / terminal | Pattern compression for git/npm/cargo output |
283| `ctx_search(pattern, path)` | Grep / rg / search | Compact, token-efficient results |
284| `ctx_tree(path, depth)` | ls / find / tree | Compact directory maps |
285| `ctx_edit(path, old_string, new_string)` | Edit (when Read unavailable) | Search-and-replace without native Read |
286
287Edit files: use native Edit/StrReplace if available. If Edit requires Read and Read is unavailable, use ctx_edit.
288Write, Delete, Glob — use normally. NEVER loop on Edit failures — switch to ctx_edit immediately.
289";
290
291const CURSORRULES_TEMPLATE: &str = "\
292# lean-ctx — Context Engineering Layer
293
294PREFER lean-ctx MCP tools over native equivalents for token savings:
295
296| PREFER | OVER | Why |
297|--------|------|-----|
298| `ctx_read(path)` | `Read` | Cached, 8 compression modes |
299| `ctx_shell(command)` | `Shell` | Pattern compression |
300| `ctx_search(pattern, path)` | `Grep` | Compact results |
301| `ctx_tree(path, depth)` | `ls` / `find` | Directory maps |
302| `ctx_edit(path, old_string, new_string)` | `Edit` (when Read unavailable) | Search-and-replace without native Read |
303
304Edit files: use native Edit/StrReplace if available. If Edit requires Read and Read is unavailable, use ctx_edit.
305Write, Delete, Glob — use normally. NEVER loop on Edit failures — switch to ctx_edit immediately.
306";
307
308pub fn install_agent_hook(agent: &str, global: bool) {
309    match agent {
310        "claude" | "claude-code" => install_claude_hook(global),
311        "cursor" => install_cursor_hook(global),
312        "gemini" => install_gemini_hook(),
313        "codex" => install_codex_hook(),
314        "windsurf" => install_windsurf_rules(global),
315        "cline" | "roo" => install_cline_rules(global),
316        "copilot" => install_copilot_hook(global),
317        "pi" => install_pi_hook(global),
318        "qwen" => install_mcp_json_agent(
319            "Qwen Code",
320            "~/.qwen/mcp.json",
321            &dirs::home_dir().unwrap_or_default().join(".qwen/mcp.json"),
322        ),
323        "trae" => install_mcp_json_agent(
324            "Trae",
325            "~/.trae/mcp.json",
326            &dirs::home_dir().unwrap_or_default().join(".trae/mcp.json"),
327        ),
328        "amazonq" => install_mcp_json_agent(
329            "Amazon Q Developer",
330            "~/.aws/amazonq/mcp.json",
331            &dirs::home_dir()
332                .unwrap_or_default()
333                .join(".aws/amazonq/mcp.json"),
334        ),
335        "jetbrains" => install_mcp_json_agent(
336            "JetBrains IDEs",
337            "~/.jb-mcp.json",
338            &dirs::home_dir().unwrap_or_default().join(".jb-mcp.json"),
339        ),
340        "kiro" => install_mcp_json_agent(
341            "AWS Kiro",
342            "~/.kiro/settings/mcp.json",
343            &dirs::home_dir()
344                .unwrap_or_default()
345                .join(".kiro/settings/mcp.json"),
346        ),
347        "verdent" => install_mcp_json_agent(
348            "Verdent",
349            "~/.verdent/mcp.json",
350            &dirs::home_dir()
351                .unwrap_or_default()
352                .join(".verdent/mcp.json"),
353        ),
354        "opencode" => install_mcp_json_agent(
355            "OpenCode",
356            "~/.opencode/mcp.json",
357            &dirs::home_dir()
358                .unwrap_or_default()
359                .join(".opencode/mcp.json"),
360        ),
361        "aider" => install_mcp_json_agent(
362            "Aider",
363            "~/.aider/mcp.json",
364            &dirs::home_dir().unwrap_or_default().join(".aider/mcp.json"),
365        ),
366        "amp" => install_mcp_json_agent(
367            "Amp",
368            "~/.amp/mcp.json",
369            &dirs::home_dir().unwrap_or_default().join(".amp/mcp.json"),
370        ),
371        _ => {
372            eprintln!("Unknown agent: {agent}");
373            eprintln!("  Supported: claude, cursor, gemini, codex, windsurf, cline, roo, copilot, pi, qwen, trae, amazonq, jetbrains, kiro, verdent, opencode, aider, amp");
374            std::process::exit(1);
375        }
376    }
377}
378
379fn install_claude_hook(global: bool) {
380    let home = match dirs::home_dir() {
381        Some(h) => h,
382        None => {
383            eprintln!("Cannot resolve home directory");
384            return;
385        }
386    };
387
388    install_claude_hook_scripts(&home);
389    install_claude_hook_config(&home);
390
391    install_claude_global_md(&home);
392
393    if !global {
394        let claude_md = PathBuf::from("CLAUDE.md");
395        if !claude_md.exists()
396            || !std::fs::read_to_string(&claude_md)
397                .unwrap_or_default()
398                .contains("lean-ctx")
399        {
400            let content = include_str!("templates/CLAUDE.md");
401            write_file(&claude_md, content);
402            println!("Created CLAUDE.md in current project directory.");
403        } else {
404            println!("CLAUDE.md already configured.");
405        }
406    }
407}
408
409fn install_claude_global_md(home: &std::path::Path) {
410    let claude_dir = home.join(".claude");
411    let _ = std::fs::create_dir_all(&claude_dir);
412    let global_md = claude_dir.join("CLAUDE.md");
413
414    let existing = std::fs::read_to_string(&global_md).unwrap_or_default();
415    if existing.contains("lean-ctx") {
416        println!("  \x1b[32m✓\x1b[0m ~/.claude/CLAUDE.md already configured");
417        return;
418    }
419
420    let content = include_str!("templates/CLAUDE_GLOBAL.md");
421
422    if existing.is_empty() {
423        write_file(&global_md, content);
424    } else {
425        let mut merged = existing;
426        if !merged.ends_with('\n') {
427            merged.push('\n');
428        }
429        merged.push('\n');
430        merged.push_str(content);
431        write_file(&global_md, &merged);
432    }
433    println!("  \x1b[32m✓\x1b[0m Installed global ~/.claude/CLAUDE.md");
434}
435
436fn install_claude_hook_scripts(home: &std::path::Path) {
437    let hooks_dir = home.join(".claude").join("hooks");
438    let _ = std::fs::create_dir_all(&hooks_dir);
439
440    let binary = resolve_binary_path();
441
442    let rewrite_path = hooks_dir.join("lean-ctx-rewrite.sh");
443    let rewrite_script = generate_rewrite_script(&resolve_binary_path_for_bash());
444    write_file(&rewrite_path, &rewrite_script);
445    make_executable(&rewrite_path);
446
447    let redirect_path = hooks_dir.join("lean-ctx-redirect.sh");
448    write_file(&redirect_path, REDIRECT_SCRIPT_CLAUDE);
449    make_executable(&redirect_path);
450
451    let wrapper = |subcommand: &str| -> String {
452        if cfg!(windows) {
453            format!("{binary} hook {subcommand}")
454        } else {
455            format!("{} hook {subcommand}", resolve_binary_path_for_bash())
456        }
457    };
458
459    let rewrite_native = hooks_dir.join("lean-ctx-rewrite-native");
460    write_file(
461        &rewrite_native,
462        &format!(
463            "#!/bin/sh\nexec {} hook rewrite\n",
464            resolve_binary_path_for_bash()
465        ),
466    );
467    make_executable(&rewrite_native);
468
469    let redirect_native = hooks_dir.join("lean-ctx-redirect-native");
470    write_file(
471        &redirect_native,
472        &format!(
473            "#!/bin/sh\nexec {} hook redirect\n",
474            resolve_binary_path_for_bash()
475        ),
476    );
477    make_executable(&redirect_native);
478
479    let _ = wrapper; // suppress unused warning on unix
480}
481
482fn install_claude_hook_config(home: &std::path::Path) {
483    let hooks_dir = home.join(".claude").join("hooks");
484    let binary = resolve_binary_path();
485
486    let rewrite_cmd = format!("{binary} hook rewrite");
487    let redirect_cmd = format!("{binary} hook redirect");
488
489    let settings_path = home.join(".claude").join("settings.json");
490    let settings_content = if settings_path.exists() {
491        std::fs::read_to_string(&settings_path).unwrap_or_default()
492    } else {
493        String::new()
494    };
495
496    let needs_update =
497        !settings_content.contains("hook rewrite") || !settings_content.contains("hook redirect");
498    let has_old_hooks = settings_content.contains("lean-ctx-rewrite.sh")
499        || settings_content.contains("lean-ctx-redirect.sh");
500
501    if !needs_update && !has_old_hooks {
502        return;
503    }
504
505    let hook_entry = serde_json::json!({
506        "hooks": {
507            "PreToolUse": [
508                {
509                    "matcher": "Bash|bash",
510                    "hooks": [{
511                        "type": "command",
512                        "command": rewrite_cmd
513                    }]
514                },
515                {
516                    "matcher": "Read|read|ReadFile|read_file|View|view|Grep|grep|Search|search|ListFiles|list_files|ListDirectory|list_directory",
517                    "hooks": [{
518                        "type": "command",
519                        "command": redirect_cmd
520                    }]
521                }
522            ]
523        }
524    });
525
526    if settings_content.is_empty() {
527        write_file(
528            &settings_path,
529            &serde_json::to_string_pretty(&hook_entry).unwrap(),
530        );
531    } else if let Ok(mut existing) = serde_json::from_str::<serde_json::Value>(&settings_content) {
532        if let Some(obj) = existing.as_object_mut() {
533            obj.insert("hooks".to_string(), hook_entry["hooks"].clone());
534            write_file(
535                &settings_path,
536                &serde_json::to_string_pretty(&existing).unwrap(),
537            );
538        }
539    }
540    if !mcp_server_quiet_mode() {
541        println!("Installed Claude Code hooks at {}", hooks_dir.display());
542    }
543}
544
545fn install_cursor_hook(global: bool) {
546    let home = match dirs::home_dir() {
547        Some(h) => h,
548        None => {
549            eprintln!("Cannot resolve home directory");
550            return;
551        }
552    };
553
554    install_cursor_hook_scripts(&home);
555    install_cursor_hook_config(&home);
556
557    if !global {
558        let rules_dir = PathBuf::from(".cursor").join("rules");
559        let _ = std::fs::create_dir_all(&rules_dir);
560        let rule_path = rules_dir.join("lean-ctx.mdc");
561        if !rule_path.exists() {
562            let rule_content = include_str!("templates/lean-ctx.mdc");
563            write_file(&rule_path, rule_content);
564            println!("Created .cursor/rules/lean-ctx.mdc in current project.");
565        } else {
566            println!("Cursor rule already exists.");
567        }
568    } else {
569        println!("Global mode: skipping project-local .cursor/rules/ (use without --global in a project).");
570    }
571
572    println!("Restart Cursor to activate.");
573}
574
575fn install_cursor_hook_scripts(home: &std::path::Path) {
576    let hooks_dir = home.join(".cursor").join("hooks");
577    let _ = std::fs::create_dir_all(&hooks_dir);
578
579    let binary = resolve_binary_path_for_bash();
580
581    let rewrite_path = hooks_dir.join("lean-ctx-rewrite.sh");
582    let rewrite_script = generate_compact_rewrite_script(&binary);
583    write_file(&rewrite_path, &rewrite_script);
584    make_executable(&rewrite_path);
585
586    let redirect_path = hooks_dir.join("lean-ctx-redirect.sh");
587    write_file(&redirect_path, REDIRECT_SCRIPT_GENERIC);
588    make_executable(&redirect_path);
589
590    let native_binary = resolve_binary_path();
591    let rewrite_native = hooks_dir.join("lean-ctx-rewrite-native");
592    write_file(
593        &rewrite_native,
594        &format!("#!/bin/sh\nexec {} hook rewrite\n", native_binary),
595    );
596    make_executable(&rewrite_native);
597
598    let redirect_native = hooks_dir.join("lean-ctx-redirect-native");
599    write_file(
600        &redirect_native,
601        &format!("#!/bin/sh\nexec {} hook redirect\n", native_binary),
602    );
603    make_executable(&redirect_native);
604}
605
606fn install_cursor_hook_config(home: &std::path::Path) {
607    let binary = resolve_binary_path();
608    let rewrite_cmd = format!("{binary} hook rewrite");
609    let redirect_cmd = format!("{binary} hook redirect");
610
611    let hooks_json = home.join(".cursor").join("hooks.json");
612    let hook_config = serde_json::json!({
613        "hooks": [
614            {
615                "event": "preToolUse",
616                "matcher": {
617                    "tool": "terminal_command"
618                },
619                "command": rewrite_cmd
620            },
621            {
622                "event": "preToolUse",
623                "matcher": {
624                    "tool": "read_file|grep|search|list_files|list_directory"
625                },
626                "command": redirect_cmd
627            }
628        ]
629    });
630
631    let content = if hooks_json.exists() {
632        std::fs::read_to_string(&hooks_json).unwrap_or_default()
633    } else {
634        String::new()
635    };
636
637    if content.contains("lean-ctx-rewrite") && content.contains("lean-ctx-redirect") {
638        return;
639    }
640
641    write_file(
642        &hooks_json,
643        &serde_json::to_string_pretty(&hook_config).unwrap(),
644    );
645    if !mcp_server_quiet_mode() {
646        println!("Installed Cursor hooks at {}", hooks_json.display());
647    }
648}
649
650fn install_gemini_hook() {
651    let home = match dirs::home_dir() {
652        Some(h) => h,
653        None => {
654            eprintln!("Cannot resolve home directory");
655            return;
656        }
657    };
658
659    install_gemini_hook_scripts(&home);
660    install_gemini_hook_config(&home);
661}
662
663fn install_gemini_hook_scripts(home: &std::path::Path) {
664    let hooks_dir = home.join(".gemini").join("hooks");
665    let _ = std::fs::create_dir_all(&hooks_dir);
666
667    let binary = resolve_binary_path_for_bash();
668
669    let rewrite_path = hooks_dir.join("lean-ctx-rewrite-gemini.sh");
670    let rewrite_script = generate_compact_rewrite_script(&binary);
671    write_file(&rewrite_path, &rewrite_script);
672    make_executable(&rewrite_path);
673
674    let redirect_path = hooks_dir.join("lean-ctx-redirect-gemini.sh");
675    write_file(&redirect_path, REDIRECT_SCRIPT_GENERIC);
676    make_executable(&redirect_path);
677}
678
679fn install_gemini_hook_config(home: &std::path::Path) {
680    let binary = resolve_binary_path();
681    let rewrite_cmd = format!("{binary} hook rewrite");
682    let redirect_cmd = format!("{binary} hook redirect");
683
684    let settings_path = home.join(".gemini").join("settings.json");
685    let settings_content = if settings_path.exists() {
686        std::fs::read_to_string(&settings_path).unwrap_or_default()
687    } else {
688        String::new()
689    };
690
691    let needs_update =
692        !settings_content.contains("hook rewrite") || !settings_content.contains("hook redirect");
693    let has_old_hooks = settings_content.contains("lean-ctx-rewrite")
694        || settings_content.contains("lean-ctx-redirect");
695
696    if !needs_update && !has_old_hooks {
697        return;
698    }
699
700    let hook_config = serde_json::json!({
701        "hooks": {
702            "BeforeTool": [
703                {
704                    "command": rewrite_cmd
705                },
706                {
707                    "command": redirect_cmd
708                }
709            ]
710        }
711    });
712
713    if settings_content.is_empty() {
714        write_file(
715            &settings_path,
716            &serde_json::to_string_pretty(&hook_config).unwrap(),
717        );
718    } else if let Ok(mut existing) = serde_json::from_str::<serde_json::Value>(&settings_content) {
719        if let Some(obj) = existing.as_object_mut() {
720            obj.insert("hooks".to_string(), hook_config["hooks"].clone());
721            write_file(
722                &settings_path,
723                &serde_json::to_string_pretty(&existing).unwrap(),
724            );
725        }
726    }
727    if !mcp_server_quiet_mode() {
728        println!(
729            "Installed Gemini CLI hooks at {}",
730            settings_path.parent().unwrap_or(&settings_path).display()
731        );
732    }
733}
734
735fn install_codex_hook() {
736    let home = match dirs::home_dir() {
737        Some(h) => h,
738        None => {
739            eprintln!("Cannot resolve home directory");
740            return;
741        }
742    };
743
744    let codex_dir = home.join(".codex");
745    let _ = std::fs::create_dir_all(&codex_dir);
746
747    install_codex_hook_scripts(&home);
748
749    let agents_path = codex_dir.join("AGENTS.md");
750    let agents_content = "# Global Agent Instructions\n\n@LEAN-CTX.md\n";
751
752    let lean_ctx_md = codex_dir.join("LEAN-CTX.md");
753    let binary = resolve_binary_path();
754    let lean_ctx_content = format!(
755        r#"# lean-ctx — Token Optimization
756
757Prefix all shell commands with `{binary} -c` for compressed output:
758
759```bash
760{binary} -c git status    # instead of: git status
761{binary} -c cargo test    # instead of: cargo test
762{binary} -c ls src/       # instead of: ls src/
763```
764
765This saves 60-90% tokens per command. Works with: git, cargo, npm, pnpm, docker, kubectl, pip, ruff, go, curl, grep, find, ls, aws, helm, and 90+ more commands.
766Use `{binary} -c --raw <cmd>` to skip compression and get full output.
767"#
768    );
769
770    if agents_path.exists() {
771        let content = std::fs::read_to_string(&agents_path).unwrap_or_default();
772        if content.contains("lean-ctx") || content.contains("LEAN-CTX") {
773            println!("Codex AGENTS.md already configured.");
774            return;
775        }
776    }
777
778    write_file(&agents_path, agents_content);
779    write_file(&lean_ctx_md, &lean_ctx_content);
780    println!("Installed Codex instructions at {}", codex_dir.display());
781}
782
783fn install_codex_hook_scripts(home: &std::path::Path) {
784    let hooks_dir = home.join(".codex").join("hooks");
785    let _ = std::fs::create_dir_all(&hooks_dir);
786
787    let binary = resolve_binary_path_for_bash();
788    let rewrite_path = hooks_dir.join("lean-ctx-rewrite-codex.sh");
789    let rewrite_script = generate_compact_rewrite_script(&binary);
790    write_file(&rewrite_path, &rewrite_script);
791    make_executable(&rewrite_path);
792    if !mcp_server_quiet_mode() {
793        println!(
794            "  \x1b[32m✓\x1b[0m Installed Codex hook scripts at {}",
795            hooks_dir.display()
796        );
797    }
798}
799
800fn install_windsurf_rules(global: bool) {
801    if global {
802        println!("Global mode: skipping project-local .windsurfrules (use without --global in a project).");
803        return;
804    }
805
806    let rules_path = PathBuf::from(".windsurfrules");
807    if rules_path.exists() {
808        let content = std::fs::read_to_string(&rules_path).unwrap_or_default();
809        if content.contains("lean-ctx") {
810            println!(".windsurfrules already configured.");
811            return;
812        }
813    }
814
815    let rules = include_str!("templates/windsurfrules.txt");
816    write_file(&rules_path, rules);
817    println!("Installed .windsurfrules in current project.");
818}
819
820fn install_cline_rules(global: bool) {
821    if global {
822        println!(
823            "Global mode: skipping project-local .clinerules (use without --global in a project)."
824        );
825        return;
826    }
827
828    let rules_path = PathBuf::from(".clinerules");
829    if rules_path.exists() {
830        let content = std::fs::read_to_string(&rules_path).unwrap_or_default();
831        if content.contains("lean-ctx") {
832            println!(".clinerules already configured.");
833            return;
834        }
835    }
836
837    let binary = resolve_binary_path();
838    let rules = format!(
839        r#"# lean-ctx Shell Optimization
840# Prefix all shell commands with `{binary} -c` for 60-90% token savings.
841
842When running shell commands, always prefix them with `{binary} -c` to compress output. For example:
843- `{binary} -c git status` instead of `git status`
844- `{binary} -c cargo test` instead of `cargo test`
845- `{binary} -c ls src/` instead of `ls src/`
846
847Supported commands: git, cargo, npm, pnpm, docker, kubectl, pip, ruff, go, curl, grep, find, ls, aws, helm, and 90+ more.
848"#
849    );
850
851    write_file(&rules_path, &rules);
852    println!("Installed .clinerules in current project.");
853}
854
855fn install_pi_hook(global: bool) {
856    let has_pi = std::process::Command::new("pi")
857        .arg("--version")
858        .output()
859        .is_ok();
860
861    if !has_pi {
862        println!("Pi Coding Agent not found in PATH.");
863        println!("Install Pi first: npm install -g @mariozechner/pi-coding-agent");
864        println!();
865    }
866
867    println!("Installing pi-lean-ctx Pi Package...");
868    println!();
869
870    let install_result = std::process::Command::new("pi")
871        .args(["install", "npm:pi-lean-ctx"])
872        .status();
873
874    match install_result {
875        Ok(status) if status.success() => {
876            println!("Installed pi-lean-ctx Pi Package.");
877        }
878        _ => {
879            println!("Could not auto-install pi-lean-ctx. Install manually:");
880            println!("  pi install npm:pi-lean-ctx");
881            println!();
882        }
883    }
884
885    if !global {
886        let agents_md = PathBuf::from("AGENTS.md");
887        if !agents_md.exists()
888            || !std::fs::read_to_string(&agents_md)
889                .unwrap_or_default()
890                .contains("lean-ctx")
891        {
892            let content = include_str!("templates/PI_AGENTS.md");
893            write_file(&agents_md, content);
894            println!("Created AGENTS.md in current project directory.");
895        } else {
896            println!("AGENTS.md already contains lean-ctx configuration.");
897        }
898    } else {
899        println!(
900            "Global mode: skipping project-local AGENTS.md (use without --global in a project)."
901        );
902    }
903
904    println!();
905    println!(
906        "Setup complete. All Pi tools (bash, read, grep, find, ls) now route through lean-ctx."
907    );
908    println!("Use /lean-ctx in Pi to verify the binary path.");
909}
910
911fn install_copilot_hook(global: bool) {
912    let binary = resolve_binary_path();
913
914    if global {
915        let mcp_path = copilot_global_mcp_path();
916        if mcp_path.as_os_str() == "/nonexistent" {
917            println!("  \x1b[2mVS Code not found — skipping global Copilot config\x1b[0m");
918            return;
919        }
920        write_vscode_mcp_file(&mcp_path, &binary, "global VS Code User MCP");
921    } else {
922        let vscode_dir = PathBuf::from(".vscode");
923        let _ = std::fs::create_dir_all(&vscode_dir);
924        let mcp_path = vscode_dir.join("mcp.json");
925        write_vscode_mcp_file(&mcp_path, &binary, ".vscode/mcp.json");
926    }
927}
928
929fn copilot_global_mcp_path() -> PathBuf {
930    if let Some(home) = dirs::home_dir() {
931        #[cfg(target_os = "macos")]
932        {
933            return home.join("Library/Application Support/Code/User/mcp.json");
934        }
935        #[cfg(target_os = "linux")]
936        {
937            return home.join(".config/Code/User/mcp.json");
938        }
939        #[cfg(target_os = "windows")]
940        {
941            if let Ok(appdata) = std::env::var("APPDATA") {
942                return PathBuf::from(appdata).join("Code/User/mcp.json");
943            }
944        }
945        #[allow(unreachable_code)]
946        home.join(".config/Code/User/mcp.json")
947    } else {
948        PathBuf::from("/nonexistent")
949    }
950}
951
952fn write_vscode_mcp_file(mcp_path: &PathBuf, binary: &str, label: &str) {
953    if mcp_path.exists() {
954        let content = std::fs::read_to_string(mcp_path).unwrap_or_default();
955        if content.contains("lean-ctx") {
956            println!("  \x1b[32m✓\x1b[0m Copilot already configured in {label}");
957            return;
958        }
959
960        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
961            if let Some(obj) = json.as_object_mut() {
962                let servers = obj
963                    .entry("servers")
964                    .or_insert_with(|| serde_json::json!({}));
965                if let Some(servers_obj) = servers.as_object_mut() {
966                    servers_obj.insert(
967                        "lean-ctx".to_string(),
968                        serde_json::json!({ "command": binary, "args": [] }),
969                    );
970                }
971                write_file(
972                    mcp_path,
973                    &serde_json::to_string_pretty(&json).unwrap_or_default(),
974                );
975                println!("  \x1b[32m✓\x1b[0m Added lean-ctx to {label}");
976                return;
977            }
978        }
979    }
980
981    if let Some(parent) = mcp_path.parent() {
982        let _ = std::fs::create_dir_all(parent);
983    }
984
985    let config = serde_json::json!({
986        "servers": {
987            "lean-ctx": {
988                "command": binary,
989                "args": []
990            }
991        }
992    });
993
994    write_file(
995        mcp_path,
996        &serde_json::to_string_pretty(&config).unwrap_or_default(),
997    );
998    println!("  \x1b[32m✓\x1b[0m Created {label} with lean-ctx MCP server");
999}
1000
1001fn write_file(path: &PathBuf, content: &str) {
1002    if let Err(e) = std::fs::write(path, content) {
1003        eprintln!("Error writing {}: {e}", path.display());
1004    }
1005}
1006
1007#[cfg(unix)]
1008fn make_executable(path: &PathBuf) {
1009    use std::os::unix::fs::PermissionsExt;
1010    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1011}
1012
1013#[cfg(not(unix))]
1014fn make_executable(_path: &PathBuf) {}
1015
1016fn install_mcp_json_agent(name: &str, display_path: &str, config_path: &std::path::Path) {
1017    let binary = resolve_binary_path();
1018
1019    if let Some(parent) = config_path.parent() {
1020        let _ = std::fs::create_dir_all(parent);
1021    }
1022
1023    if config_path.exists() {
1024        let content = std::fs::read_to_string(config_path).unwrap_or_default();
1025        if content.contains("lean-ctx") {
1026            println!("{name} MCP already configured at {display_path}");
1027            return;
1028        }
1029
1030        if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&content) {
1031            if let Some(obj) = json.as_object_mut() {
1032                let servers = obj
1033                    .entry("mcpServers")
1034                    .or_insert_with(|| serde_json::json!({}));
1035                if let Some(servers_obj) = servers.as_object_mut() {
1036                    servers_obj.insert(
1037                        "lean-ctx".to_string(),
1038                        serde_json::json!({ "command": binary }),
1039                    );
1040                }
1041                if let Ok(formatted) = serde_json::to_string_pretty(&json) {
1042                    let _ = std::fs::write(config_path, formatted);
1043                    println!("  \x1b[32m✓\x1b[0m {name} MCP configured at {display_path}");
1044                    return;
1045                }
1046            }
1047        }
1048    }
1049
1050    let content = serde_json::to_string_pretty(&serde_json::json!({
1051        "mcpServers": {
1052            "lean-ctx": {
1053                "command": binary
1054            }
1055        }
1056    }));
1057
1058    if let Ok(json_str) = content {
1059        let _ = std::fs::write(config_path, json_str);
1060        println!("  \x1b[32m✓\x1b[0m {name} MCP configured at {display_path}");
1061    } else {
1062        eprintln!("  \x1b[31m✗\x1b[0m Failed to configure {name}");
1063    }
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::*;
1069
1070    #[test]
1071    fn bash_path_unix_unchanged() {
1072        assert_eq!(
1073            to_bash_compatible_path("/usr/local/bin/lean-ctx"),
1074            "/usr/local/bin/lean-ctx"
1075        );
1076    }
1077
1078    #[test]
1079    fn bash_path_home_unchanged() {
1080        assert_eq!(
1081            to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
1082            "/home/user/.cargo/bin/lean-ctx"
1083        );
1084    }
1085
1086    #[test]
1087    fn bash_path_windows_drive_converted() {
1088        assert_eq!(
1089            to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
1090            "/c/Users/Fraser/bin/lean-ctx.exe"
1091        );
1092    }
1093
1094    #[test]
1095    fn bash_path_windows_lowercase_drive() {
1096        assert_eq!(
1097            to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
1098            "/d/tools/lean-ctx.exe"
1099        );
1100    }
1101
1102    #[test]
1103    fn bash_path_windows_forward_slashes() {
1104        assert_eq!(
1105            to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
1106            "/c/Users/Fraser/bin/lean-ctx.exe"
1107        );
1108    }
1109
1110    #[test]
1111    fn bash_path_bare_name_unchanged() {
1112        assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
1113    }
1114
1115    #[test]
1116    fn normalize_msys2_path() {
1117        assert_eq!(
1118            normalize_tool_path("/c/Users/game/Downloads/project"),
1119            "C:/Users/game/Downloads/project"
1120        );
1121    }
1122
1123    #[test]
1124    fn normalize_msys2_drive_d() {
1125        assert_eq!(
1126            normalize_tool_path("/d/Projects/app/src"),
1127            "D:/Projects/app/src"
1128        );
1129    }
1130
1131    #[test]
1132    fn normalize_backslashes() {
1133        assert_eq!(
1134            normalize_tool_path("C:\\Users\\game\\project\\src"),
1135            "C:/Users/game/project/src"
1136        );
1137    }
1138
1139    #[test]
1140    fn normalize_mixed_separators() {
1141        assert_eq!(
1142            normalize_tool_path("C:\\Users/game\\project/src"),
1143            "C:/Users/game/project/src"
1144        );
1145    }
1146
1147    #[test]
1148    fn normalize_double_slashes() {
1149        assert_eq!(
1150            normalize_tool_path("/home/user//project///src"),
1151            "/home/user/project/src"
1152        );
1153    }
1154
1155    #[test]
1156    fn normalize_trailing_slash() {
1157        assert_eq!(
1158            normalize_tool_path("/home/user/project/"),
1159            "/home/user/project"
1160        );
1161    }
1162
1163    #[test]
1164    fn normalize_root_preserved() {
1165        assert_eq!(normalize_tool_path("/"), "/");
1166    }
1167
1168    #[test]
1169    fn normalize_windows_root_preserved() {
1170        assert_eq!(normalize_tool_path("C:/"), "C:/");
1171    }
1172
1173    #[test]
1174    fn normalize_unix_path_unchanged() {
1175        assert_eq!(
1176            normalize_tool_path("/home/user/project/src/main.rs"),
1177            "/home/user/project/src/main.rs"
1178        );
1179    }
1180
1181    #[test]
1182    fn normalize_relative_path_unchanged() {
1183        assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
1184    }
1185
1186    #[test]
1187    fn normalize_dot_unchanged() {
1188        assert_eq!(normalize_tool_path("."), ".");
1189    }
1190
1191    #[test]
1192    fn normalize_unc_path_preserved() {
1193        assert_eq!(
1194            normalize_tool_path("//server/share/file"),
1195            "//server/share/file"
1196        );
1197    }
1198}