Skip to main content

lean_ctx/hooks/
mod.rs

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