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/// Handles MSYS2/Git Bash (`/c/Users/...` -> `C:/Users/...`), mixed separators,
191/// double slashes, and trailing slashes. Always uses forward slashes for consistency.
192pub fn normalize_tool_path(path: &str) -> String {
193    let mut p = match crate::core::pathutil::strip_verbatim_str(path) {
194        Some(stripped) => stripped,
195        None => path.to_string(),
196    };
197
198    // MSYS2/Git Bash: /c/Users/... -> C:/Users/...
199    if p.len() >= 3
200        && p.starts_with('/')
201        && p.as_bytes()[1].is_ascii_alphabetic()
202        && p.as_bytes()[2] == b'/'
203    {
204        let drive = p.as_bytes()[1].to_ascii_uppercase() as char;
205        p = format!("{drive}:{}", &p[2..]);
206    }
207
208    p = p.replace('\\', "/");
209
210    // Collapse double slashes (preserve UNC paths starting with //)
211    while p.contains("//") && !p.starts_with("//") {
212        p = p.replace("//", "/");
213    }
214
215    // Remove trailing slash (unless root like "/" or "C:/")
216    if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
217        p.pop();
218    }
219
220    p
221}
222
223pub fn generate_rewrite_script(binary: &str) -> String {
224    let case_pattern = crate::rewrite_registry::bash_case_pattern();
225    format!(
226        r#"#!/usr/bin/env bash
227# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
228set -euo pipefail
229
230LEAN_CTX_BIN="{binary}"
231
232INPUT=$(cat)
233TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
234
235if [ "$TOOL" != "Bash" ] && [ "$TOOL" != "bash" ]; then
236  exit 0
237fi
238
239CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
240
241if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
242  exit 0
243fi
244
245case "$CMD" in
246  {case_pattern})
247    # Shell-escape then JSON-escape (two passes)
248    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
249    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
250    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
251    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
252    ;;
253  *) exit 0 ;;
254esac
255"#
256    )
257}
258
259pub fn generate_compact_rewrite_script(binary: &str) -> String {
260    let case_pattern = crate::rewrite_registry::bash_case_pattern();
261    format!(
262        r#"#!/usr/bin/env bash
263# lean-ctx hook — rewrites shell commands
264set -euo pipefail
265LEAN_CTX_BIN="{binary}"
266INPUT=$(cat)
267CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
268if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
269case "$CMD" in
270  {case_pattern})
271    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
272    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
273    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
274    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
275  *) exit 0 ;;
276esac
277"#
278    )
279}
280
281const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
282# lean-ctx PreToolUse hook — all native tools pass through
283# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
284# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
285exit 0
286";
287
288const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
289# lean-ctx hook — all native tools pass through
290exit 0
291";
292
293pub(crate) const CLI_REDIRECT_RULES: &str = "\
294# lean-ctx — CLI-Redirect Mode
295
296PREFER lean-ctx CLI commands over MCP tools for token savings (no MCP schema overhead):
297
298| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
299|---------------------|-------------------|-----|
300| `lean-ctx read <path>` | `ctx_read` | No MCP schema overhead, same caching |
301| `lean-ctx read <path> -m map` | `ctx_read(mode=\"map\")` | Compressed output via CLI |
302| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | Pattern compression via CLI |
303| `lean-ctx grep <pattern> [path]` | `ctx_search` | Compact results via CLI |
304| `lean-ctx ls [path]` | `ctx_tree` | Directory maps via CLI |
305
306## Usage via Shell
307
308Run lean-ctx commands through your Shell/Bash tool:
309```
310lean-ctx read src/main.rs
311lean-ctx read src/main.rs -m signatures
312lean-ctx -c \"cargo test\"
313lean-ctx grep \"fn main\" src/
314lean-ctx ls src/
315```
316
317## Read modes (same as MCP):
318auto | full | map | signatures | diff | aggressive | entropy | task | reference | lines:N-M
319
320## File editing:
321Use native Edit/StrReplace — lean-ctx only handles READ operations.
322Write, Delete, Glob → use normally.
323";
324
325pub(crate) const HYBRID_RULES: &str = "\
326# lean-ctx — Hybrid Mode (MCP reads + CLI commands)
327
328Use MCP tools for reads (cache benefit), CLI commands for everything else (no schema overhead):
329
330## MCP tools (keep using):
331| Tool | Why MCP |
332|------|---------|
333| `ctx_read(path, mode)` | In-process cache, re-reads ~13 tokens |
334
335## CLI commands (via Shell/Bash):
336| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
337|---------------------|-------------------|-----|
338| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | No MCP schema overhead |
339| `lean-ctx grep <pattern> [path]` | `ctx_search` | No MCP schema overhead |
340| `lean-ctx ls [path]` | `ctx_tree` | No MCP schema overhead |
341
342## File editing:
343Use native Edit/StrReplace — lean-ctx only handles READ operations.
344Write, Delete, Glob → use normally.
345";
346
347pub fn install_project_rules() {
348    install_project_rules_for_agents(&[]);
349}
350
351/// Install project rules, optionally scoped to specific agents.
352/// If `agents` is empty, installs for all agents (legacy behavior).
353pub fn install_project_rules_for_agents(agents: &[&str]) {
354    if crate::core::config::Config::load().rules_scope_effective()
355        == crate::core::config::RulesScope::Global
356    {
357        return;
358    }
359
360    let cwd = std::env::current_dir().unwrap_or_default();
361
362    if !is_inside_git_repo(&cwd) {
363        eprintln!(
364            "  Skipping project files: not inside a git repository.\n  \
365             Run this command from your project root to create CLAUDE.md / AGENTS.md."
366        );
367        return;
368    }
369
370    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
371    if cwd == home {
372        eprintln!(
373            "  Skipping project files: current directory is your home folder.\n  \
374             Run this command from a project directory instead."
375        );
376        return;
377    }
378
379    let all = agents.is_empty();
380    let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
381
382    ensure_project_agents_integration(&cwd);
383
384    if wants("cursor") || wants("windsurf") {
385        let cursorrules = cwd.join(".cursorrules");
386        if !cursorrules.exists()
387            || !std::fs::read_to_string(&cursorrules)
388                .unwrap_or_default()
389                .contains("lean-ctx")
390        {
391            let content = CURSORRULES_TEMPLATE;
392            if cursorrules.exists() {
393                let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
394                if !existing.ends_with('\n') {
395                    existing.push('\n');
396                }
397                existing.push('\n');
398                existing.push_str(content);
399                write_file(&cursorrules, &existing);
400            } else {
401                write_file(&cursorrules, content);
402            }
403            if !mcp_server_quiet_mode() {
404                eprintln!("Created/updated .cursorrules in project root.");
405            }
406        }
407    }
408
409    if wants("claude") {
410        let claude_rules_dir = cwd.join(".claude").join("rules");
411        let claude_rules_file = claude_rules_dir.join("lean-ctx.md");
412        if !claude_rules_file.exists()
413            || !std::fs::read_to_string(&claude_rules_file)
414                .unwrap_or_default()
415                .contains(crate::rules_inject::RULES_VERSION_STR)
416        {
417            let _ = std::fs::create_dir_all(&claude_rules_dir);
418            write_file(
419                &claude_rules_file,
420                crate::rules_inject::rules_dedicated_markdown(),
421            );
422            if !mcp_server_quiet_mode() {
423                eprintln!("Created .claude/rules/lean-ctx.md (Claude Code project rules).");
424            }
425        }
426
427        install_claude_project_hooks(&cwd);
428    }
429
430    if wants("kiro") {
431        let kiro_dir = cwd.join(".kiro");
432        if kiro_dir.exists() {
433            let steering_dir = kiro_dir.join("steering");
434            let steering_file = steering_dir.join("lean-ctx.md");
435            if !steering_file.exists()
436                || !std::fs::read_to_string(&steering_file)
437                    .unwrap_or_default()
438                    .contains("lean-ctx")
439            {
440                let _ = std::fs::create_dir_all(&steering_dir);
441                write_file(&steering_file, KIRO_STEERING_TEMPLATE);
442                if !mcp_server_quiet_mode() {
443                    eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
444                }
445            }
446        }
447    }
448}
449
450const PROJECT_LEAN_CTX_MD_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
451const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
452const PROJECT_AGENTS_MD: &str = "AGENTS.md";
453const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
454const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
455
456fn ensure_project_agents_integration(cwd: &std::path::Path) {
457    let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
458    let desired = format!(
459        "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
460        crate::rules_inject::rules_dedicated_markdown()
461    );
462
463    if !lean_ctx_md.exists() {
464        write_file(&lean_ctx_md, &desired);
465    } else if std::fs::read_to_string(&lean_ctx_md)
466        .unwrap_or_default()
467        .contains(PROJECT_LEAN_CTX_MD_MARKER)
468    {
469        let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
470        if !current.contains(crate::rules_inject::RULES_VERSION_STR) {
471            write_file(&lean_ctx_md, &desired);
472        }
473    }
474
475    let block = format!(
476        "{AGENTS_BLOCK_START}\n\
477## lean-ctx\n\n\
478Prefer lean-ctx MCP tools over native equivalents for token savings.\n\
479Full rules: @{PROJECT_LEAN_CTX_MD}\n\
480{AGENTS_BLOCK_END}\n"
481    );
482
483    let agents_md = cwd.join(PROJECT_AGENTS_MD);
484    if !agents_md.exists() {
485        let content = format!("# Agent Instructions\n\n{block}");
486        write_file(&agents_md, &content);
487        if !mcp_server_quiet_mode() {
488            eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
489        }
490        return;
491    }
492
493    let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
494    if existing.contains(AGENTS_BLOCK_START) {
495        let updated = replace_marked_block(&existing, AGENTS_BLOCK_START, AGENTS_BLOCK_END, &block);
496        if updated != existing {
497            write_file(&agents_md, &updated);
498        }
499        return;
500    }
501
502    if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
503        return;
504    }
505
506    let mut out = existing;
507    if !out.ends_with('\n') {
508        out.push('\n');
509    }
510    out.push('\n');
511    out.push_str(&block);
512    write_file(&agents_md, &out);
513    if !mcp_server_quiet_mode() {
514        eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
515    }
516}
517
518pub(crate) fn replace_marked_block(
519    content: &str,
520    start: &str,
521    end: &str,
522    replacement: &str,
523) -> String {
524    let s = content.find(start);
525    let e = content.find(end);
526    match (s, e) {
527        (Some(si), Some(ei)) if ei >= si => {
528            let after_end = ei + end.len();
529            let before = &content[..si];
530            let after = &content[after_end..];
531            let mut out = String::new();
532            out.push_str(before.trim_end_matches('\n'));
533            out.push('\n');
534            out.push('\n');
535            out.push_str(replacement.trim_end_matches('\n'));
536            out.push('\n');
537            out.push_str(after.trim_start_matches('\n'));
538            out
539        }
540        _ => content.to_string(),
541    }
542}
543
544const CURSORRULES_TEMPLATE: &str = "\
545# lean-ctx — Context Engineering Layer
546
547PREFER lean-ctx MCP tools over native equivalents for token savings:
548
549| PREFER | OVER | Why |
550|--------|------|-----|
551| `ctx_read(path)` | `Read` | Cached, 10 compression modes |
552| `ctx_shell(command)` | `Shell` | Pattern compression |
553| `ctx_search(pattern, path)` | `Grep` | Compact results |
554| `ctx_tree(path, depth)` | `ls` / `find` | Directory maps |
555| `ctx_edit(path, old_string, new_string)` | `Edit` (when Read unavailable) | Search-and-replace without native Read |
556
557Edit files: use native Edit/StrReplace if available. If Edit requires Read and Read is unavailable, use ctx_edit.
558Write, Delete, Glob — use normally. NEVER loop on Edit failures — switch to ctx_edit immediately.
559";
560
561pub const KIRO_STEERING_TEMPLATE: &str = "\
562---
563inclusion: always
564---
565
566# lean-ctx — Context Engineering Layer
567
568The workspace has the `lean-ctx` MCP server installed. You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.
569
570## Mandatory Tool Preferences
571
572| Use this | Instead of | Why |
573|----------|-----------|-----|
574| `mcp_lean_ctx_ctx_read` | `readFile`, `readCode` | Cached reads, 10 compression modes, re-reads cost ~13 tokens |
575| `mcp_lean_ctx_ctx_multi_read` | `readMultipleFiles` | Batch cached reads in one call |
576| `mcp_lean_ctx_ctx_shell` | `executeBash` | Pattern compression for git/npm/test output |
577| `mcp_lean_ctx_ctx_search` | `grepSearch` | Compact, .gitignore-aware results |
578| `mcp_lean_ctx_ctx_tree` | `listDirectory` | Compact directory maps with file counts |
579
580## When to use native Kiro tools instead
581
582- `fsWrite` / `fsAppend` — always use native (lean-ctx doesn't write files)
583- `strReplace` — always use native (precise string replacement)
584- `semanticRename` / `smartRelocate` — always use native (IDE integration)
585- `getDiagnostics` — always use native (language server diagnostics)
586- `deleteFile` — always use native
587
588## Session management
589
590- At the start of a long task, call `mcp_lean_ctx_ctx_preload` with a task description to warm the cache
591- Use `mcp_lean_ctx_ctx_compress` periodically in long conversations to checkpoint context
592- Use `mcp_lean_ctx_ctx_knowledge` to persist important discoveries across sessions
593
594## Rules
595
596- NEVER loop on edit failures — switch to `mcp_lean_ctx_ctx_edit` immediately
597- For large files, use `mcp_lean_ctx_ctx_read` with `mode: \"signatures\"` or `mode: \"map\"` first
598- For re-reading a file you already read, just call `mcp_lean_ctx_ctx_read` again (cache hit = ~13 tokens)
599- When running tests or build commands, use `mcp_lean_ctx_ctx_shell` for compressed output
600";
601
602pub fn install_agent_hook(agent: &str, global: bool) {
603    install_agent_hook_with_mode(agent, global, HookMode::Mcp);
604}
605
606pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
607    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
608    match agent {
609        "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
610        "cursor" => install_cursor_hook_with_mode(global, mode),
611        "gemini" => install_gemini_hook(),
612        "antigravity" => install_antigravity_hook(),
613        "codex" => install_codex_hook(),
614        "windsurf" => install_windsurf_rules(global),
615        "cline" | "roo" => install_cline_rules(global),
616        "copilot" | "vscode" => install_copilot_hook(global),
617        "pi" => install_pi_hook_with_mode(global, mode),
618        "qoder" => install_qoder_hook_with_mode(mode),
619        "qoderwork" => install_mcp_json_agent(
620            "QoderWork",
621            "~/.qoderwork/mcp.json",
622            &home.join(".qoderwork/mcp.json"),
623        ),
624        "qwen" => install_mcp_json_agent(
625            "Qwen Code",
626            "~/.qwen/settings.json",
627            &home.join(".qwen/settings.json"),
628        ),
629        "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
630        "amazonq" => install_mcp_json_agent(
631            "Amazon Q Developer",
632            "~/.aws/amazonq/default.json",
633            &home.join(".aws/amazonq/default.json"),
634        ),
635        "jetbrains" => install_jetbrains_hook(),
636        "kiro" => install_kiro_hook(),
637        "verdent" => install_mcp_json_agent(
638            "Verdent",
639            "~/.verdent/mcp.json",
640            &home.join(".verdent/mcp.json"),
641        ),
642        "opencode" => install_opencode_hook_with_mode(mode),
643        "amp" => install_amp_hook(),
644        "crush" => install_crush_hook_with_mode(mode),
645        "hermes" => install_hermes_hook_with_mode(global, mode),
646        "zed" => {
647            let zed_path = crate::core::editor_registry::zed_settings_path(&home);
648            let binary = resolve_binary_path();
649            let entry = full_server_entry(&binary);
650            install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
651        }
652        "aider" => {
653            install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
654        }
655        "continue" => install_mcp_json_agent(
656            "Continue",
657            "~/.continue/mcp.json",
658            &home.join(".continue/mcp.json"),
659        ),
660        "neovim" => install_mcp_json_agent(
661            "Neovim (mcphub.nvim)",
662            "~/.config/mcphub/servers.json",
663            &home.join(".config/mcphub/servers.json"),
664        ),
665        "emacs" => install_mcp_json_agent(
666            "Emacs (mcp.el)",
667            "~/.emacs.d/mcp.json",
668            &home.join(".emacs.d/mcp.json"),
669        ),
670        "sublime" => install_mcp_json_agent(
671            "Sublime Text",
672            "~/.config/sublime-text/mcp.json",
673            &home.join(".config/sublime-text/mcp.json"),
674        ),
675        _ => {
676            eprintln!("Unknown agent: {agent}");
677            eprintln!("  Supported: aider, amazonq, amp, antigravity, claude, cline, codex,");
678            eprintln!("    continue, copilot, crush, cursor, emacs, gemini, hermes, jetbrains,");
679            eprintln!("    kiro, neovim, opencode, pi, qoder, qoderwork, qwen, roo, sublime,");
680            eprintln!("    trae, verdent, vscode, windsurf, zed");
681            std::process::exit(1);
682        }
683    }
684}
685
686pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
687    match agent {
688        "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
689        _ => {}
690    }
691}
692
693fn write_file(path: &std::path::Path, content: &str) {
694    if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
695        tracing::error!("Error writing {}: {e}", path.display());
696    }
697}
698
699fn is_inside_git_repo(path: &std::path::Path) -> bool {
700    let mut p = path;
701    loop {
702        if p.join(".git").exists() {
703            return true;
704        }
705        match p.parent() {
706            Some(parent) => p = parent,
707            None => return false,
708        }
709    }
710}
711
712#[cfg(unix)]
713fn make_executable(path: &PathBuf) {
714    use std::os::unix::fs::PermissionsExt;
715    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
716}
717
718#[cfg(not(unix))]
719fn make_executable(_path: &PathBuf) {}
720
721fn full_server_entry(binary: &str) -> serde_json::Value {
722    let data_dir = crate::core::data_dir::lean_ctx_data_dir()
723        .map(|d| d.to_string_lossy().to_string())
724        .unwrap_or_default();
725    serde_json::json!({
726        "command": binary,
727        "env": {
728            "LEAN_CTX_DATA_DIR": data_dir,
729            "LEAN_CTX_FULL_TOOLS": "1"
730        }
731    })
732}
733
734pub(crate) fn install_mcp_json_agent(
735    name: &str,
736    display_path: &str,
737    config_path: &std::path::Path,
738) {
739    let binary = resolve_binary_path();
740    let entry = full_server_entry(&binary);
741    install_named_json_server(name, display_path, config_path, "mcpServers", entry);
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747
748    #[test]
749    fn bash_path_unix_unchanged() {
750        assert_eq!(
751            to_bash_compatible_path("/usr/local/bin/lean-ctx"),
752            "/usr/local/bin/lean-ctx"
753        );
754    }
755
756    #[test]
757    fn bash_path_home_unchanged() {
758        assert_eq!(
759            to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
760            "/home/user/.cargo/bin/lean-ctx"
761        );
762    }
763
764    #[test]
765    fn bash_path_windows_drive_converted() {
766        assert_eq!(
767            to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
768            "/c/Users/Fraser/bin/lean-ctx.exe"
769        );
770    }
771
772    #[test]
773    fn bash_path_windows_lowercase_drive() {
774        assert_eq!(
775            to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
776            "/d/tools/lean-ctx.exe"
777        );
778    }
779
780    #[test]
781    fn bash_path_windows_forward_slashes() {
782        assert_eq!(
783            to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
784            "/c/Users/Fraser/bin/lean-ctx.exe"
785        );
786    }
787
788    #[test]
789    fn bash_path_bare_name_unchanged() {
790        assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
791    }
792
793    #[test]
794    fn normalize_msys2_path() {
795        assert_eq!(
796            normalize_tool_path("/c/Users/game/Downloads/project"),
797            "C:/Users/game/Downloads/project"
798        );
799    }
800
801    #[test]
802    fn normalize_msys2_drive_d() {
803        assert_eq!(
804            normalize_tool_path("/d/Projects/app/src"),
805            "D:/Projects/app/src"
806        );
807    }
808
809    #[test]
810    fn normalize_backslashes() {
811        assert_eq!(
812            normalize_tool_path("C:\\Users\\game\\project\\src"),
813            "C:/Users/game/project/src"
814        );
815    }
816
817    #[test]
818    fn normalize_mixed_separators() {
819        assert_eq!(
820            normalize_tool_path("C:\\Users/game\\project/src"),
821            "C:/Users/game/project/src"
822        );
823    }
824
825    #[test]
826    fn normalize_double_slashes() {
827        assert_eq!(
828            normalize_tool_path("/home/user//project///src"),
829            "/home/user/project/src"
830        );
831    }
832
833    #[test]
834    fn normalize_trailing_slash() {
835        assert_eq!(
836            normalize_tool_path("/home/user/project/"),
837            "/home/user/project"
838        );
839    }
840
841    #[test]
842    fn normalize_root_preserved() {
843        assert_eq!(normalize_tool_path("/"), "/");
844    }
845
846    #[test]
847    fn normalize_windows_root_preserved() {
848        assert_eq!(normalize_tool_path("C:/"), "C:/");
849    }
850
851    #[test]
852    fn normalize_unix_path_unchanged() {
853        assert_eq!(
854            normalize_tool_path("/home/user/project/src/main.rs"),
855            "/home/user/project/src/main.rs"
856        );
857    }
858
859    #[test]
860    fn normalize_relative_path_unchanged() {
861        assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
862    }
863
864    #[test]
865    fn normalize_dot_unchanged() {
866        assert_eq!(normalize_tool_path("."), ".");
867    }
868
869    #[test]
870    fn normalize_unc_path_preserved() {
871        assert_eq!(
872            normalize_tool_path("//server/share/file"),
873            "//server/share/file"
874        );
875    }
876
877    #[test]
878    fn cursor_hook_config_has_version_and_object_hooks() {
879        let config = serde_json::json!({
880            "version": 1,
881            "hooks": {
882                "preToolUse": [
883                    {
884                        "matcher": "terminal_command",
885                        "command": "lean-ctx hook rewrite"
886                    },
887                    {
888                        "matcher": "read_file|grep|search|list_files|list_directory",
889                        "command": "lean-ctx hook redirect"
890                    }
891                ]
892            }
893        });
894
895        let json_str = serde_json::to_string_pretty(&config).unwrap();
896        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
897
898        assert_eq!(parsed["version"], 1);
899        assert!(parsed["hooks"].is_object());
900        assert!(parsed["hooks"]["preToolUse"].is_array());
901        assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
902        assert_eq!(
903            parsed["hooks"]["preToolUse"][0]["matcher"],
904            "terminal_command"
905        );
906    }
907
908    #[test]
909    fn cursor_hook_detects_old_format_needs_migration() {
910        let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
911        let has_correct =
912            old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
913        assert!(
914            !has_correct,
915            "Old format should be detected as needing migration"
916        );
917    }
918
919    #[test]
920    fn gemini_hook_config_has_type_command() {
921        let binary = "lean-ctx";
922        let rewrite_cmd = format!("{binary} hook rewrite");
923        let redirect_cmd = format!("{binary} hook redirect");
924
925        let hook_config = serde_json::json!({
926            "hooks": {
927                "BeforeTool": [
928                    {
929                        "hooks": [{
930                            "type": "command",
931                            "command": rewrite_cmd
932                        }]
933                    },
934                    {
935                        "hooks": [{
936                            "type": "command",
937                            "command": redirect_cmd
938                        }]
939                    }
940                ]
941            }
942        });
943
944        let parsed = hook_config;
945        let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
946        assert_eq!(before_tool.len(), 2);
947
948        let first_hook = &before_tool[0]["hooks"][0];
949        assert_eq!(first_hook["type"], "command");
950        assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
951
952        let second_hook = &before_tool[1]["hooks"][0];
953        assert_eq!(second_hook["type"], "command");
954        assert_eq!(second_hook["command"], "lean-ctx hook redirect");
955    }
956
957    #[test]
958    fn gemini_hook_old_format_detected() {
959        let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
960        let has_new = old_format.contains("hook rewrite")
961            && old_format.contains("hook redirect")
962            && old_format.contains("\"type\"");
963        assert!(!has_new, "Missing 'type' field should trigger migration");
964    }
965
966    #[test]
967    fn rewrite_script_uses_registry_pattern() {
968        let script = generate_rewrite_script("/usr/bin/lean-ctx");
969        assert!(script.contains(r"git\ *"), "script missing git pattern");
970        assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
971        assert!(script.contains(r"npm\ *"), "script missing npm pattern");
972        assert!(
973            !script.contains(r"rg\ *"),
974            "script should not contain rg pattern"
975        );
976        assert!(
977            script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
978            "script missing binary path"
979        );
980    }
981
982    #[test]
983    fn compact_rewrite_script_uses_registry_pattern() {
984        let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
985        assert!(script.contains(r"git\ *"), "compact script missing git");
986        assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
987        assert!(
988            !script.contains(r"rg\ *"),
989            "compact script should not contain rg"
990        );
991    }
992
993    #[test]
994    fn rewrite_scripts_contain_all_registry_commands() {
995        let script = generate_rewrite_script("lean-ctx");
996        let compact = generate_compact_rewrite_script("lean-ctx");
997        for entry in crate::rewrite_registry::REWRITE_COMMANDS {
998            if matches!(
999                entry.category,
1000                crate::rewrite_registry::Category::Search
1001                    | crate::rewrite_registry::Category::FileRead
1002            ) {
1003                continue;
1004            }
1005            let pattern = if entry.command.contains('-') {
1006                format!("{}*", entry.command.replace('-', r"\-"))
1007            } else {
1008                format!(r"{}\ *", entry.command)
1009            };
1010            assert!(
1011                script.contains(&pattern),
1012                "rewrite_script missing '{}' (pattern: {})",
1013                entry.command,
1014                pattern
1015            );
1016            assert!(
1017                compact.contains(&pattern),
1018                "compact_rewrite_script missing '{}' (pattern: {})",
1019                entry.command,
1020                pattern
1021            );
1022        }
1023    }
1024
1025    #[test]
1026    fn codex_is_hybrid_not_cli_redirect() {
1027        assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
1028    }
1029
1030    #[test]
1031    fn cursor_remains_cli_redirect() {
1032        assert_eq!(recommend_hook_mode("cursor"), HookMode::CliRedirect);
1033    }
1034
1035    #[test]
1036    fn gemini_remains_cli_redirect() {
1037        assert_eq!(recommend_hook_mode("gemini"), HookMode::CliRedirect);
1038    }
1039
1040    #[test]
1041    fn claude_is_hybrid() {
1042        assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
1043    }
1044
1045    #[test]
1046    fn unknown_agent_falls_back_to_mcp() {
1047        assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
1048    }
1049}