Skip to main content

lean_ctx/hooks/
mod.rs

1use std::path::PathBuf;
2
3pub mod agents;
4pub(crate) mod project_pins;
5mod support;
6pub(crate) use project_pins::strip_project_scoped_env_toml;
7
8/// Controls how hooks instruct agents to access lean-ctx functionality.
9///
10/// * `Mcp` — MCP server only (extension/plugin-based agents without reliable shell).
11/// * `Hybrid` — MCP server + shell hooks for command compression (best of both).
12/// * `Replace` — Native Read/Grep/Glob/Shell are **denied**; lean-ctx MCP tools are
13///   the only path. Eliminates tool drift entirely — no agent compliance needed.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum HookMode {
17    #[default]
18    Mcp,
19    Hybrid,
20    Replace,
21}
22
23impl std::fmt::Display for HookMode {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        match self {
26            Self::Mcp => write!(f, "MCP"),
27            Self::Hybrid => write!(f, "Hybrid"),
28            Self::Replace => write!(f, "Replace"),
29        }
30    }
31}
32
33impl HookMode {
34    pub fn from_str_loose(s: &str) -> Option<Self> {
35        match s.to_lowercase().replace('-', "").as_str() {
36            "mcp" => Some(Self::Mcp),
37            "hybrid" => Some(Self::Hybrid),
38            "replace" => Some(Self::Replace),
39            _ => None,
40        }
41    }
42
43    /// Downgrade Replace → Hybrid; leave Hybrid/Mcp unchanged.
44    pub fn cap_at_hybrid(self) -> Self {
45        if matches!(self, Self::Replace) {
46            Self::Hybrid
47        } else {
48            self
49        }
50    }
51
52    pub fn description(&self) -> &'static str {
53        match self {
54            Self::Mcp => "MCP server only (extension/plugin-based agents without reliable shell)",
55            Self::Hybrid => "MCP server + shell hooks for command compression (best of both)",
56            Self::Replace => {
57                "Native tools denied — lean-ctx MCP is the only path (zero tool drift)"
58            }
59        }
60    }
61}
62
63/// Agents with reliable shell + hook infrastructure that *can* run Replace mode
64/// (native tools denied, lean-ctx MCP is the only path). These agents have
65/// either `permissions.deny` support or PreToolUse deny-hook capability.
66///
67/// Replace is opt-in (`hook_mode = "replace"`): denying native tools made
68/// agents fail and retry instead of working, so these agents default to Hybrid
69/// like every other hook-capable agent.
70pub const REPLACE_AGENTS: &[&str] = &[
71    "cursor",
72    "claude",
73    "claude-code",
74    "codebuddy",
75    "codex",
76    "windsurf",
77    "opencode",
78    "gemini",
79];
80
81/// Agents that get Hybrid mode (MCP + shell hooks) because they lack reliable
82/// deny infrastructure but do have shell hooks for command compression.
83pub const HYBRID_AGENTS: &[&str] = &[
84    "cursor",
85    "gemini",
86    "codex",
87    "claude",
88    "claude-code",
89    "crush",
90    "hermes",
91    "opencode",
92    "openclaw",
93    "pi",
94    "omp",
95    "qoder",
96    "qodercli",
97    "windsurf",
98    "amp",
99    "cline",
100    "roo",
101    "copilot",
102    "kiro",
103    "qwen",
104    "trae",
105    "antigravity",
106    "antigravity-cli",
107    "amazonq",
108    "verdent",
109];
110
111/// First-class agents that get MCP registration only — no shell hooks, because
112/// their hook surface does not (yet) carry lean-ctx's contract.
113///
114/// CodeWhale (#1402) is the first entry: its hooks are TUI-only and follow
115/// observer/steering semantics rather than the pre-tool rewrite/deny contract
116/// every `HYBRID_AGENTS` entry relies on, so installing lean-ctx's shell hooks
117/// there would ship a script whose behaviour we cannot honestly predict.
118/// Membership here does not enable any hook install — it only marks the agent
119/// as genuinely supported by `init --agent` / `setup` so `wrap` can say so.
120pub const MCP_ONLY_AGENTS: &[&str] = &["codewhale"];
121
122/// True when `agent` is integrated via `init --agent` / `setup` (hooks, rules,
123/// MCP registration). GH #1520: used by `wrap`'s error path to point users of
124/// a supported-but-not-proxy-wrappable agent (e.g. opencode) at the working
125/// command instead of a bare "unsupported agent".
126pub fn is_supported_agent(agent: &str) -> bool {
127    let key = agent.to_ascii_lowercase();
128    REPLACE_AGENTS.contains(&key.as_str())
129        || HYBRID_AGENTS.contains(&key.as_str())
130        || MCP_ONLY_AGENTS.contains(&key.as_str())
131}
132
133/// Auto-detect the best hook mode for a given agent key.
134///
135/// Priority: disabled/shadow_mode cap > config override > Hybrid > Mcp
136/// - Replace: native tools denied, MCP-only path — only when the user chose it
137///   (`hook_mode = "replace"`, `LEAN_CTX_HOOK_MODE=replace`, `harden --hard`)
138/// - Hybrid: MCP + shell hooks; native tools keep working, known commands
139///   are rewritten through lean-ctx (default for every hook-capable agent)
140/// - Mcp: MCP server only (no shell hooks available)
141///
142/// `LEAN_CTX_DISABLED=1` or `shadow_mode = false` cap the mode at Hybrid so
143/// the deny-list is never injected when the user opted out (#1037).
144pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
145    if let Some(override_mode) = crate::core::config::Config::load().hook_mode_override() {
146        return if is_deny_suppressed() {
147            override_mode.cap_at_hybrid()
148        } else {
149            override_mode
150        };
151    }
152    if REPLACE_AGENTS.contains(&agent_key) || HYBRID_AGENTS.contains(&agent_key) {
153        HookMode::Hybrid
154    } else {
155        HookMode::Mcp
156    }
157}
158
159/// True when native-tool denial is in effect: the user chose Replace and has
160/// not suppressed denials (#1037). Deny hooks consult this at call time, so a
161/// hook entry written while Replace was the default stops blocking the moment
162/// the binary updates — no settings rewrite has to happen first.
163#[must_use]
164pub fn replace_mode_chosen() -> bool {
165    crate::core::config::Config::load().hook_mode_override() == Some(HookMode::Replace)
166        && !is_deny_suppressed()
167}
168
169/// Whether Claude Code (and CodeBuddy, which shares its contract) keeps native
170/// Grep/Glob out of the model's tool list via `permissions.deny`.
171///
172/// Unlike a hook denial this costs no error and no retry: Claude Code drops a
173/// denied tool from the list, so the model never calls it. And it keeps
174/// searches on the compressed path — native Glob cannot be redirected (#1033).
175/// Measured 2026-10-13 over 30 days: 0 Grep/Glob calls and 0 denials in 380
176/// Claude sessions with the list, while native Glob returned ~12× the tokens
177/// of `ctx_glob` for the same patterns. So the default (auto) mode keeps it;
178/// an explicit `hook_mode = "hybrid"`/`"mcp"`, `shadow_mode = false` or
179/// `LEAN_CTX_DISABLED` give the tools back.
180#[must_use]
181pub fn claude_hides_native_search(mode: HookMode) -> bool {
182    match mode {
183        HookMode::Replace => true,
184        HookMode::Hybrid => {
185            crate::core::config::Config::load()
186                .hook_mode_override()
187                .is_none()
188                && !is_deny_suppressed()
189        }
190        HookMode::Mcp => false,
191    }
192}
193
194/// True when the user explicitly opted out of deny-list injection.
195fn is_deny_suppressed() -> bool {
196    if std::env::var("LEAN_CTX_DISABLED").is_ok() {
197        return true;
198    }
199    if matches!(std::env::var("LEAN_CTX_SHADOW_MODE"), Ok(v) if v.trim() == "false" || v.trim() == "0")
200    {
201        return true;
202    }
203    if matches!(std::env::var("LEAN_CTX_HEAL"), Ok(v) if v.trim().eq_ignore_ascii_case("off") || v.trim() == "0")
204    {
205        return true;
206    }
207    let cfg = crate::core::config::Config::load();
208    !cfg.shadow_mode
209}
210use agents::{
211    install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
212    install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
213    install_claude_permissions_allow_mcp, install_claude_permissions_deny_replace,
214    install_claude_project_hooks, install_claude_statusline, install_cline_rules,
215    install_codebuddy_hook_config, install_codebuddy_hook_scripts,
216    install_codebuddy_hook_with_mode, install_codebuddy_permissions_deny_replace,
217    install_codebuddy_project_hooks, install_codex_hook, install_codex_runtime_hook,
218    install_copilot_hook, install_copilot_runtime_hook, install_crush_hook_with_mode,
219    install_cursor_deny_hook, install_cursor_hook_config, install_cursor_hook_scripts,
220    install_cursor_hook_with_mode, install_gemini_deny_hook, install_gemini_hook,
221    install_gemini_hook_config, install_gemini_hook_scripts, install_grok_mcp,
222    install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
223    install_openclaw_hook, install_opencode_hook_with_mode, install_pi_hook_with_mode,
224    install_qoder_hook_with_mode, install_qoder_runtime_hook_with_mode, install_vibe_hook,
225    install_windsurf_hooks, install_windsurf_hooks_replace, install_windsurf_rules,
226};
227use support::{
228    ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
229    upsert_lean_ctx_codex_hook_entries,
230};
231
232fn mcp_server_quiet_mode() -> bool {
233    crate::core::runtime_flags::mcp_server_enabled() || crate::core::runtime_flags::quiet_enabled()
234}
235
236/// Agents whose global shell-hook artifacts embed the binary path / command
237/// and therefore must be re-rendered after an update or on MCP server start so
238/// they always point at the current binary. Each entry is gated on a detection
239/// marker (see `hooks_installed_for`) so we never install hooks for an agent
240/// the user never configured. The `refresh_covers_every_hybrid_agent` test
241/// proves this list plus `REFRESH_EXEMPT_HYBRID_AGENTS` accounts for every
242/// Hybrid agent, so a newly added agent can never silently regress.
243const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
244    "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder", "qodercli",
245];
246
247/// Hybrid agents intentionally NOT auto-refreshed, with the reason each is safe
248/// to skip. Refresh runs silently (including on every MCP server start), so it
249/// must never spawn subprocesses or write project/cwd-relative files. Used by
250/// the coverage test to prove every Hybrid agent has an explicit decision.
251#[cfg(test)]
252const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
253    // Alias of `claude` — same global files, already refreshed via "claude".
254    "claude-code",
255    // Installer shells out to `pi install` (subprocess) — unsafe on every start.
256    "pi",
257    // OMP uses native MCP/rules files; it has no binary-embedding shell hook.
258    "omp",
259    // Write project/cwd-relative rules (.clinerules, .kiro/steering) — a silent
260    // server-start refresh must not create files in the user's working dir.
261    "cline",
262    "roo",
263    "kiro",
264    // MCP-config / rules wiring only (no global binary-embedding shell-hook
265    // script to keep current); refreshed by `setup --fix`, not on start.
266    "antigravity",
267    "antigravity-cli",
268    "amp",
269    "crush",
270    "hermes",
271    "opencode",
272    "openclaw",
273    "qwen",
274    "trae",
275    "amazonq",
276    "verdent",
277];
278
279/// Silently refresh all hook scripts for agents that are already configured.
280/// Called after updates and on MCP server start to ensure hooks match the
281/// current binary version. Registry-driven: every Hybrid agent with a global
282/// shell hook is covered (the rest are explicitly exempted, enforced by test).
283///
284/// `[setup] manage_hooks = false` turns this into a no-op (#1879): users who
285/// hand-pick hook entries keep them, and only an explicit `setup`, `init` or
286/// `doctor --fix` writes agent hook config.
287pub fn refresh_installed_hooks() {
288    if !crate::core::config::Config::load().setup.manage_hooks {
289        tracing::debug!("hook refresh skipped: [setup] manage_hooks = false");
290        return;
291    }
292    let Some(home) = crate::core::home::resolve_home_dir() else {
293        return;
294    };
295    // OpenCode is refreshed by `setup`, not here — except its native-tool
296    // gates: "ask" refuses calls like a deny hook, and an update through a
297    // package manager never reaches setup.
298    agents::release_opencode_native_tool_gates(&home);
299    for agent in REFRESHABLE_HOOK_AGENTS {
300        if hooks_installed_for(agent, &home) {
301            refresh_agent_hooks(agent, &home);
302        }
303    }
304}
305
306/// The hook mode in effect for `agent`, or `None` when no lean-ctx hook
307/// artifacts are installed for it (global only). Used for coverage reporting.
308pub(crate) fn installed_hook_mode(agent: &str, home: &std::path::Path) -> Option<HookMode> {
309    hooks_installed_for(agent, home).then(|| recommend_hook_mode(agent))
310}
311
312/// True when `agent` already has lean-ctx hook artifacts on disk (global only).
313fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
314    match agent {
315        "claude" => {
316            let dir = crate::setup::claude_config_dir(home);
317            dir.join("hooks/lean-ctx-rewrite.sh").exists()
318                || file_contains_lean_ctx(&dir.join("settings.json"))
319        }
320        "codebuddy" => {
321            let dir = crate::core::editor_registry::codebuddy_state_dir(home);
322            dir.join("hooks/lean-ctx-rewrite.sh").exists()
323                || file_contains_lean_ctx(&dir.join("settings.json"))
324        }
325        "cursor" => {
326            home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
327                || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
328        }
329        "gemini" => {
330            home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
331                .exists()
332                || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
333        }
334        "codex" => {
335            let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
336            dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
337                || file_contains_lean_ctx(&dir.join("hooks.json"))
338        }
339        "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
340        "copilot" => {
341            // User-level Copilot hooks live under ~/.copilot/hooks (#381);
342            // ~/.github/hooks is the pre-#381 legacy location.
343            file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
344                || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
345        }
346        "qoder" | "qodercli" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
347        _ => false,
348    }
349}
350
351/// Re-render the hook artifacts for an already-configured agent. Only calls
352/// narrow, subprocess-free, global installers (never the full agent setup).
353/// Mode-aware: preserves Replace-mode deny artifacts (permissions.deny, deny
354/// hooks) so an MCP server restart never downgrades Replace → Hybrid.
355fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
356    let mode = recommend_hook_mode(agent);
357    match agent {
358        "claude" => {
359            install_claude_hook_scripts(home);
360            install_claude_hook_config(home);
361            // The value status line shipped in 3.10.3 but was only written by
362            // `init --agent claude`, so every existing install missed it.
363            install_claude_statusline(home);
364            if claude_hides_native_search(mode) {
365                install_claude_permissions_deny_replace(home);
366            }
367        }
368        "codebuddy" => {
369            install_codebuddy_hook_scripts(home);
370            install_codebuddy_hook_config(home);
371            if claude_hides_native_search(mode) {
372                install_codebuddy_permissions_deny_replace(home, mode);
373            }
374        }
375        "cursor" => {
376            install_cursor_hook_scripts(home);
377            install_cursor_hook_config(home);
378            if mode == HookMode::Replace {
379                install_cursor_deny_hook(true);
380            }
381        }
382        "gemini" => {
383            install_gemini_hook_scripts(home);
384            install_gemini_hook_config(home);
385            if mode == HookMode::Replace {
386                install_gemini_deny_hook(home);
387            }
388        }
389        "codex" => install_codex_runtime_hook(),
390        "windsurf" => {
391            if mode == HookMode::Replace {
392                install_windsurf_hooks_replace(home);
393            } else {
394                install_windsurf_hooks(home);
395            }
396        }
397        "copilot" => install_copilot_runtime_hook(true),
398        "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
399        _ => {}
400    }
401}
402
403fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
404    std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
405}
406
407/// Resolve the lean-ctx binary to an **absolute** path for generated hook
408/// commands and MCP server entries.
409///
410/// Agent hooks (Codex, Cursor, Claude, Gemini, Antigravity, …) are executed by
411/// the host under a plain non-login shell (`sh -c …`) whose `PATH` is not
412/// guaranteed to contain the install dir (e.g. `/usr/local/bin`). A bare
413/// `lean-ctx` therefore fails with exit code 127 (#367). Always emitting the
414/// resolved absolute path makes hook execution deterministic and matches what
415/// MCP setup (`setup/mcp.rs`) and `doctor` already do. Existing configs with a
416/// bare command are rewritten on the next `lean-ctx init` / `doctor` run.
417///
418/// Kept strictly absolute — also used for MCP server `command` fields, which
419/// hosts spawn **directly** (no shell), so `$HOME/...` forms would break
420/// there. Shell-executed hook commands go through
421/// [`resolve_hook_command_binary`], which honors the portable override (#708).
422fn resolve_binary_path() -> String {
423    crate::core::portable_binary::resolve_agent_binary()
424}
425
426/// Binary token for **shell-executed** hook commands (`<binary> hook rewrite`
427/// in Claude/Cursor/Gemini/… hook configs and generated `#!/bin/sh` scripts).
428///
429/// Portable override (#708): `LEAN_CTX_HOOK_BINARY` env, then config
430/// `hook_binary`, is emitted **verbatim** — for settings files synced across
431/// machines with different usernames (`$HOME/.local/bin/lean-ctx`). Hook
432/// hosts run these commands through a shell, so the variable expands at
433/// execution time; `doctor` accepts the override as current, so
434/// `init`/`--fix`/`update` stop rewriting synced files. MCP registrations
435/// and autostart units keep the absolute path (no shell there).
436fn resolve_hook_command_binary() -> String {
437    if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
438        return portable;
439    }
440    resolve_binary_path()
441}
442
443fn resolve_binary_path_for_bash() -> String {
444    if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
445        return portable;
446    }
447    to_bash_compatible_path(&resolve_binary_path())
448}
449
450/// Shell-quotes a binary token for generated `#!/bin/sh` wrappers and
451/// `LEAN_CTX_BIN=` assignments (#719). Double quotes keep `$HOME`-style
452/// portable overrides (#708) expanding at execution time while paths with
453/// spaces survive word splitting (npm installs under
454/// `C:\Users\First Last\AppData\…`). `"` and `` ` `` are escaped; `$` stays
455/// active on purpose — portable forms rely on it.
456pub(crate) fn shell_quoted_binary(binary: &str) -> String {
457    let escaped = binary.replace('"', "\\\"").replace('`', "\\`");
458    format!("\"{escaped}\"")
459}
460
461/// #719: true when an existing generated wrapper references a portable binary
462/// form (`$HOME/…`, `${HOME}/…`, `%USERPROFILE%\…`) that resolves to an
463/// existing binary on THIS machine. Such a wrapper is healthy and must not be
464/// re-stamped with a machine-absolute path: on multi-machine synced setups
465/// (Dropbox'd `~/.claude`, different usernames) a heal on the machine WITHOUT
466/// the portable override would otherwise bake its absolute path into the
467/// wrapper, and every new session on the peer machine dies mid tool call with
468/// no surfaced error.
469fn wrapper_is_portable_and_working(path: &std::path::Path, home: &std::path::Path) -> bool {
470    std::fs::read_to_string(path)
471        .is_ok_and(|content| wrapper_content_is_portable_and_working(&content, home))
472}
473
474pub(crate) fn wrapper_content_is_portable_and_working(
475    content: &str,
476    home: &std::path::Path,
477) -> bool {
478    let Some(token) = wrapper_binary_token(content) else {
479        return false;
480    };
481    if !(token.contains("$HOME") || token.contains("${HOME}") || token.contains("%USERPROFILE%")) {
482        return false;
483    }
484    let home_s = home.to_string_lossy();
485    let expanded = token
486        .replace("${HOME}", &home_s)
487        .replace("$HOME", &home_s)
488        .replace("%USERPROFILE%", &home_s);
489    std::path::Path::new(&from_bash_to_native_path(&expanded)).exists()
490}
491
492/// Extracts the binary token from a generated wrapper script: the
493/// `LEAN_CTX_BIN=` assignment (rewrite scripts) or the `exec <binary> hook …`
494/// line (native wrappers) — quoted or bare.
495pub(crate) fn wrapper_binary_token(content: &str) -> Option<String> {
496    for line in content.lines() {
497        let t = line.trim();
498        if let Some(rest) = t.strip_prefix("LEAN_CTX_BIN=") {
499            let rest = rest.trim();
500            let tok = rest
501                .strip_prefix('"')
502                .map_or(rest, |r| r.split('"').next().unwrap_or_default());
503            if !tok.is_empty() {
504                return Some(tok.to_string());
505            }
506        }
507        if let Some(rest) = t.strip_prefix("exec ") {
508            let rest = rest.trim();
509            let tok = match rest.strip_prefix('"') {
510                Some(r) => r.split('"').next().unwrap_or_default().to_string(),
511                None => rest
512                    .split_whitespace()
513                    .next()
514                    .unwrap_or_default()
515                    .to_string(),
516            };
517            if !tok.is_empty() {
518                return Some(tok);
519            }
520        }
521    }
522    None
523}
524
525/// Writes a generated hook wrapper unless the portable override is unset AND
526/// the existing file already carries a working portable reference (#719) —
527/// healing must never replace a synced portable wrapper with a
528/// machine-absolute path.
529fn write_wrapper_file(path: &std::path::Path, content: &str, home: &std::path::Path) {
530    if crate::core::portable_binary::hook_binary_override().is_none()
531        && wrapper_is_portable_and_working(path, home)
532    {
533        return;
534    }
535    write_file(path, content);
536}
537
538pub fn to_bash_compatible_path(path: &str) -> String {
539    let path = match crate::core::pathutil::strip_verbatim_str(path) {
540        Some(stripped) => stripped,
541        None => path.replace('\\', "/"),
542    };
543    if path.len() >= 2 && path.as_bytes()[1] == b':' {
544        let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
545        format!("/{drive}{}", &path[2..])
546    } else {
547        path
548    }
549}
550
551/// Convert a Unix/MSYS-style path (`/c/Users/...`) back to native Windows
552/// format (`C:/Users/...`). No-op for paths that don't match the pattern.
553pub fn from_bash_to_native_path(path: &str) -> String {
554    crate::core::pathutil::normalize_tool_path(path)
555}
556
557/// Normalize paths from any client format to a consistent OS-native form.
558/// Delegates to `core::pathutil` so `core` crates do not depend on `hooks`.
559pub fn normalize_tool_path(path: &str) -> String {
560    crate::core::pathutil::normalize_tool_path(path)
561}
562
563pub fn generate_rewrite_script(binary: &str) -> String {
564    let case_pattern = crate::rewrite_registry::bash_case_pattern();
565    // #719: assignment + rewritten command carry the binary quoted, so
566    // portable `$HOME/…` overrides expand at exec time and paths with spaces
567    // survive word splitting.
568    let quoted_binary = shell_quoted_binary(binary);
569    format!(
570        r#"#!/usr/bin/env bash
571# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
572set -euo pipefail
573
574LEAN_CTX_BIN={quoted_binary}
575
576INPUT=$(cat)
577TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
578
579case "$TOOL" in
580  Bash|bash|PowerShell|powershell) ;;
581  *) exit 0 ;;
582esac
583
584CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
585
586if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then
587  exit 0
588fi
589
590# Skip multi-line commands: the grep/sed extraction above does not decode
591# JSON \n into real newlines, so lean-ctx -c would receive fused lines (#787).
592if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
593
594case "$CMD" in
595  {case_pattern})
596    # Shell-escape then JSON-escape (two passes)
597    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
598    REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
599    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
600    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
601    ;;
602  *) exit 0 ;;
603esac
604"#
605    )
606}
607
608pub fn generate_compact_rewrite_script(binary: &str) -> String {
609    let case_pattern = crate::rewrite_registry::bash_case_pattern();
610    let quoted_binary = shell_quoted_binary(binary);
611    format!(
612        r#"#!/usr/bin/env bash
613# lean-ctx hook — rewrites shell commands
614set -euo pipefail
615LEAN_CTX_BIN={quoted_binary}
616INPUT=$(cat)
617CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
618if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then exit 0; fi
619if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
620case "$CMD" in
621  {case_pattern})
622    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
623    REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
624    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
625    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
626  *) exit 0 ;;
627esac
628"#
629    )
630}
631
632const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
633# lean-ctx PreToolUse hook — all native tools pass through
634# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
635# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
636exit 0
637";
638
639const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
640# lean-ctx hook — all native tools pass through
641exit 0
642";
643
644pub fn hybrid_rules_content() -> String {
645    use crate::core::rules_canonical;
646    format!(
647        "{start}\n<!-- version: {version} -->\n\n\
648# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
649{bullets}\n\n\
650{never}\n\n\
651{end}",
652        start = rules_canonical::START_MARK,
653        version = rules_canonical::RULES_VERSION,
654        bullets = rules_canonical::BULLETS,
655        never = rules_canonical::NEVER,
656        end = rules_canonical::END_MARK,
657    )
658}
659
660pub fn replace_rules_content() -> String {
661    use crate::core::rules_canonical;
662    format!(
663        "{start}\n<!-- version: {version} -->\n\n\
664# lean-ctx \u{2014} Replace Mode (native tools denied)\n\n\
665Native Read/Grep/Glob/Bash are denied by policy. Use ONLY ctx_* MCP tools:\n\
666- ctx_read for ALL file reads (cached, 10 modes, unchanged full/auto re-reads ~13 tokens)\n\
667- ctx_shell for ALL shell commands (95+ compression patterns)\n\
668- ctx_search instead of Grep/rg (compact results)\n\
669- ctx_tree instead of ls/find (compact directory maps)\n\
670- ctx_glob instead of Glob (file pattern matching)\n\n\
671Do NOT attempt native Read, Grep, Glob, or Bash \u{2014} they will be denied.\n\n\
672{end}",
673        start = rules_canonical::START_MARK,
674        version = rules_canonical::RULES_VERSION,
675        end = rules_canonical::END_MARK,
676    )
677}
678
679pub fn install_project_rules() {
680    install_project_rules_for_agents(&[]);
681}
682
683/// Install project rules, optionally scoped to specific agents.
684/// If `agents` is empty, installs for all agents (legacy behavior).
685pub fn install_project_rules_for_agents(agents: &[&str]) {
686    if crate::core::config::Config::load().rules_scope_effective()
687        == crate::core::config::RulesScope::Global
688    {
689        return;
690    }
691
692    let cwd = std::env::current_dir().unwrap_or_default();
693
694    if !is_inside_git_repo(&cwd) {
695        eprintln!(
696            "  Skipping project files: not inside a git repository.\n  \
697             Run this command from your project root to create CLAUDE.md / AGENTS.md."
698        );
699        return;
700    }
701
702    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
703    if cwd == home {
704        eprintln!(
705            "  Skipping project files: current directory is your home folder.\n  \
706             Run this command from a project directory instead."
707        );
708        return;
709    }
710
711    let all = agents.is_empty();
712    let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
713
714    ensure_project_agents_integration(&cwd);
715
716    if wants("cursor") || wants("windsurf") {
717        let cursorrules = cwd.join(".cursorrules");
718        if !cursorrules.exists()
719            || !std::fs::read_to_string(&cursorrules)
720                .unwrap_or_default()
721                .contains("lean-ctx")
722        {
723            let content = cursorrules_content();
724            if cursorrules.exists() {
725                let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
726                if !existing.ends_with('\n') {
727                    existing.push('\n');
728                }
729                existing.push('\n');
730                existing.push_str(&content);
731                write_file(&cursorrules, &existing);
732            } else {
733                write_file(&cursorrules, &content);
734            }
735            if !mcp_server_quiet_mode() {
736                eprintln!("Created/updated .cursorrules in project root.");
737            }
738        }
739    }
740
741    if wants("claude") {
742        // GL #555: project rules files without `paths:` frontmatter load
743        // unconditionally every session and stacked on top of the global
744        // CLAUDE.md block (12k+ token memory footprints in the field). The
745        // AGENTS.md block + on-demand skill carry the same guidance, so the
746        // lean-ctx-owned copy is removed instead of refreshed.
747        let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
748        if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
749            && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
750            && std::fs::remove_file(&claude_rules_file).is_ok()
751            && !mcp_server_quiet_mode()
752        {
753            eprintln!(
754                "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
755            );
756        }
757
758        install_claude_project_hooks(&cwd);
759    }
760
761    if wants("codebuddy") {
762        let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
763        if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
764            && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
765            && std::fs::remove_file(&codebuddy_rules_file).is_ok()
766            && !mcp_server_quiet_mode()
767        {
768            eprintln!(
769                "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
770            );
771        }
772
773        install_codebuddy_project_hooks(&cwd);
774    }
775
776    if wants("kiro") {
777        let kiro_dir = cwd.join(".kiro");
778        if kiro_dir.exists() {
779            let steering_dir = kiro_dir.join("steering");
780            let steering_file = steering_dir.join("lean-ctx.md");
781            if !steering_file.exists()
782                || !std::fs::read_to_string(&steering_file)
783                    .unwrap_or_default()
784                    .contains("lean-ctx")
785            {
786                let _ = std::fs::create_dir_all(&steering_dir);
787                write_file(&steering_file, &kiro_steering_content());
788                if !mcp_server_quiet_mode() {
789                    eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
790                }
791            }
792        }
793    }
794
795    if wants("copilot") || wants("vscode") {
796        ensure_copilot_instructions(&cwd);
797        ensure_vscode_instruction_files_setting(&cwd);
798    }
799}
800
801const PROJECT_LEAN_CTX_MD_MARKER: &str =
802    crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
803const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
804const PROJECT_AGENTS_MD: &str = "AGENTS.md";
805// The AGENTS.md pointer block keeps its own marker pair, independent of the
806// dedicated rules-file `START_MARK`: pointer-only files must not be counted as
807// duplicate lean-ctx sources (doctor overhead, #684).
808const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
809const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
810
811fn ensure_project_agents_integration(cwd: &std::path::Path) {
812    let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
813    // Longform (#578): LEAN-CTX.md is opened on demand via the AGENTS.md
814    // pointer, never auto-loaded, so it carries the verbose teaching profile.
815    let desired = format!(
816        "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
817        crate::rules_inject::rules_longform_markdown()
818    );
819
820    if !lean_ctx_md.exists() {
821        write_file(&lean_ctx_md, &desired);
822    } else if std::fs::read_to_string(&lean_ctx_md)
823        .unwrap_or_default()
824        .contains(PROJECT_LEAN_CTX_MD_MARKER)
825    {
826        let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
827        let version_str = format!(
828            "<!-- version: {} -->",
829            crate::core::rules_canonical::RULES_VERSION
830        );
831        if !current.contains(&version_str) {
832            write_file(&lean_ctx_md, &desired);
833        }
834    }
835
836    // No `@` import: Claude Code expands `@file` references inline at session
837    // start, so pointing at LEAN-CTX.md re-loaded the full ruleset into every
838    // session on top of this block (GL #555). The block is self-contained;
839    // the full ruleset stays in LEAN-CTX.md for on-demand reading.
840    let block = format!(
841        "{AGENTS_BLOCK_START}\n\
842## lean-ctx\n\n\
843lean-ctx is active — the MCP tools replace native equivalents.\n\
844Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
845{AGENTS_BLOCK_END}\n"
846    );
847
848    let agents_md = cwd.join(PROJECT_AGENTS_MD);
849    if !agents_md.exists() {
850        let content = format!("# Agent Instructions\n\n{block}");
851        write_file(&agents_md, &content);
852        if !mcp_server_quiet_mode() {
853            eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
854        }
855        return;
856    }
857
858    let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
859
860    // Marker checks are line-based (GL #1158): a prose mention of the marker
861    // (as this repo's own AGENTS.md carries) must not trigger block surgery.
862    let has_block = crate::marked_block::contains_marker_line(&existing, AGENTS_BLOCK_START);
863
864    if existing.contains("CLI-first Token Optimization for Pi") && !has_block {
865        let content = format!("# Agent Instructions\n\n{block}");
866        write_file(&agents_md, &content);
867        return;
868    }
869
870    if has_block {
871        let updated = crate::marked_block::replace_marked_block(
872            &existing,
873            AGENTS_BLOCK_START,
874            AGENTS_BLOCK_END,
875            &block,
876        );
877        if updated != existing {
878            write_file(&agents_md, &updated);
879        }
880        return;
881    }
882
883    if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
884        return;
885    }
886
887    let mut out = existing;
888    if !out.ends_with('\n') {
889        out.push('\n');
890    }
891    out.push('\n');
892    out.push_str(&block);
893    write_file(&agents_md, &out);
894    if !mcp_server_quiet_mode() {
895        eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
896    }
897}
898
899/// #555: VS Code Copilot Chat auto-applies `.github/copilot-instructions.md` to
900/// every request, but `init --agent copilot` previously wrote only a weak
901/// AGENTS.md pointer — Claude-family models then ignored the lean-ctx tool
902/// mapping while GPT-5.x mostly followed it. Write the strong dedicated ruleset
903/// into a `<!-- lean-ctx-rules -->` marked block so it merges idempotently and
904/// never clobbers the user's own instructions.
905fn ensure_copilot_instructions(cwd: &std::path::Path) {
906    let path = cwd.join(".github").join("copilot-instructions.md");
907    let block = crate::rules_inject::rules_dedicated_markdown();
908    let start = crate::core::rules_canonical::START_MARK;
909    let end = crate::core::rules_canonical::END_MARK;
910    let owned = format!("{}\n", block.trim_end());
911
912    let existing = std::fs::read_to_string(&path).unwrap_or_default();
913    let desired = if existing.trim().is_empty() {
914        owned
915    } else if existing.contains(start) {
916        // Refresh our block; keep any surrounding user-authored content.
917        let user = crate::marked_block::remove_content(&existing, start, end);
918        if user.trim().is_empty() {
919            owned
920        } else {
921            format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
922        }
923    } else {
924        // User-authored file with no lean-ctx block yet: append ours once.
925        format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
926    };
927
928    if desired == existing {
929        return;
930    }
931    if let Some(parent) = path.parent()
932        && std::fs::create_dir_all(parent).is_err()
933    {
934        return;
935    }
936    write_file(&path, &desired);
937    if !mcp_server_quiet_mode() {
938        eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
939    }
940}
941
942/// #555 safety net: VS Code applies instruction files when
943/// `github.copilot.chat.codeGeneration.useInstructionFiles` is on (the default).
944/// A user or org policy may have disabled it globally, so pin it on for this
945/// project. Set only when the key is absent — an explicit user value is honoured.
946fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
947    const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
948    let path = cwd.join(".vscode").join("settings.json");
949
950    let existing = std::fs::read_to_string(&path).unwrap_or_default();
951    let mut json = if existing.trim().is_empty() {
952        serde_json::json!({})
953    } else {
954        match crate::core::jsonc::parse_jsonc(&existing) {
955            Ok(v) if v.is_object() => v,
956            // Never clobber an unparseable or non-object settings file.
957            _ => return,
958        }
959    };
960    let Some(obj) = json.as_object_mut() else {
961        return;
962    };
963    if obj.contains_key(KEY) {
964        return;
965    }
966    obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
967
968    if let Some(parent) = path.parent()
969        && std::fs::create_dir_all(parent).is_err()
970    {
971        return;
972    }
973    let Ok(formatted) = serde_json::to_string_pretty(&json) else {
974        return;
975    };
976    if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
977        && !mcp_server_quiet_mode()
978    {
979        eprintln!("Set {KEY} in .vscode/settings.json.");
980    }
981}
982
983/// Compact pointer only (#578): Cursor already auto-loads the canonical full
984/// ruleset from `~/.cursor/rules/lean-ctx.mdc`, so a project `.cursorrules`
985/// that repeats it bills the same guidance twice in every session.
986pub fn cursorrules_content() -> String {
987    let start = crate::core::rules_canonical::START_MARK;
988    let end = crate::core::rules_canonical::END_MARK;
989    let version = crate::core::rules_canonical::RULES_VERSION;
990    format!(
991        "{start}\n<!-- version: {version} -->\n\n\
992# lean-ctx\n\n\
993{bullets}\n\n\
994{never}\n\
995Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
996{end}",
997        bullets = crate::core::rules_canonical::BULLETS,
998        never = crate::core::rules_canonical::NEVER,
999    )
1000}
1001
1002pub fn kiro_steering_content() -> String {
1003    use crate::core::rules_canonical;
1004    format!(
1005        "---\n\
1006inclusion: always\n\
1007---\n\n\
1008# LeanCTX — Context Gateway for AI Systems\n\n\
1009{start}\n\
1010<!-- version: {version} -->\n\n\
1011The workspace has the `lean-ctx` MCP server installed. \
1012You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
1013{bullets}\n\n\
1014{never}\n\n\
1015## When to use native Kiro tools instead\n\n\
1016- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
1017- `strReplace` \u{2014} always use native (precise string replacement)\n\
1018- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
1019- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
1020- `deleteFile` \u{2014} always use native\n\
1021- Glob \u{2014} always use native glob\n\n\
1022{end}",
1023        start = rules_canonical::START_MARK,
1024        version = rules_canonical::RULES_VERSION,
1025        bullets = rules_canonical::BULLETS,
1026        never = rules_canonical::NEVER,
1027        end = rules_canonical::END_MARK,
1028    )
1029}
1030/// #281: whether the hooks layer may register the lean-ctx MCP server in an
1031/// agent's config. Honors `[setup] auto_update_mcp`. Hooks, rules and skills
1032/// still install when this is `false` — only the MCP-server writes are gated, so
1033/// MCP-disabled environments stay free of MCP entries. Centralised here so every
1034/// per-agent writer shares one source of truth (the shared JSON writer in
1035/// `support.rs` enforces the same gate for `mcpServers`-style agents).
1036pub(crate) fn should_register_mcp() -> bool {
1037    crate::core::config::Config::load()
1038        .setup
1039        .should_update_mcp()
1040}
1041
1042pub fn install_agent_hook(agent: &str, global: bool) {
1043    install_agent_hook_with_mode(agent, global, HookMode::Mcp);
1044}
1045
1046pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1047    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1048    match agent {
1049        "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
1050        "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
1051        "cursor" => install_cursor_hook_with_mode(global, mode),
1052        "gemini" => {
1053            install_gemini_hook();
1054            if mode == HookMode::Replace {
1055                install_gemini_deny_hook(&home);
1056            }
1057            // Google is transitioning Gemini CLI → Antigravity CLI (`agy`), and
1058            // `gemini` setup also configures the Antigravity CLI MCP target. The
1059            // hooks must follow: `agy` reads hooks only from its plugin dir
1060            // (`~/.gemini/config/plugins/lean-ctx`), never from the legacy
1061            // `~/.gemini/settings.json`, so install the plugin too (#284).
1062            install_antigravity_cli_hook();
1063        }
1064        "grok" | "grok-build" => install_grok_mcp(),
1065        "antigravity" => install_antigravity_hook(),
1066        "antigravity-cli" => install_antigravity_cli_hook(),
1067        "augment" => install_mcp_json_agent(
1068            "Augment CLI",
1069            "~/.augment/settings.json",
1070            &crate::core::editor_registry::augment_cli_settings_path(&home),
1071        ),
1072        "codex" => {
1073            install_codex_hook();
1074        }
1075        "windsurf" => {
1076            install_windsurf_rules(global);
1077            if mode == HookMode::Replace {
1078                install_windsurf_hooks_replace(&home);
1079            }
1080        }
1081        "cline" | "roo" => install_cline_rules(global),
1082        "copilot" | "vscode" => install_copilot_hook(global),
1083        // VS Code Insiders needs no hook install of its own: the MCP entry in
1084        // its separate `Code - Insiders/User/mcp.json` is written by the
1085        // editor-registry writer (GH #694), and the Copilot hook layer is
1086        // user-global (`~/.copilot`), already covered by copilot/vscode.
1087        // Command Code has no hook surface either; shadow mode rides on the
1088        // MCP entry's `instructions` field written by the same writer.
1089        // CodeWhale (#1402) has no hook surface lean-ctx can honestly drive:
1090        // its hooks are TUI-only and use observer/steering semantics, not the
1091        // pre-tool rewrite/deny contract our scripts assume. MCP registration
1092        // is handled by the editor-registry writer via `configure_agent_mcp`,
1093        // which honours the `servers` / `mcpServers` root the user already has
1094        // — `install_mcp_json_agent` would hardcode `mcpServers` and could add
1095        // a competing second root.
1096        "vscode-insiders" | "commandcode" | "codewhale" | "omp" => {}
1097        "pi" => install_pi_hook_with_mode(global, mode),
1098        "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
1099        "qoderwork" => install_mcp_json_agent(
1100            "QoderWork",
1101            "~/.qoderwork/mcp.json",
1102            &home.join(".qoderwork/mcp.json"),
1103        ),
1104        "qwen" => install_mcp_json_agent(
1105            "Qwen Code",
1106            "~/.qwen/settings.json",
1107            &home.join(".qwen/settings.json"),
1108        ),
1109        "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
1110        "amazonq" => install_mcp_json_agent(
1111            "Amazon Q Developer",
1112            "~/.aws/amazonq/default.json",
1113            &home.join(".aws/amazonq/default.json"),
1114        ),
1115        "jetbrains" => install_jetbrains_hook(),
1116        "kiro" => install_kiro_hook(),
1117        "verdent" => install_mcp_json_agent(
1118            "Verdent",
1119            "~/.verdent/mcp.json",
1120            &home.join(".verdent/mcp.json"),
1121        ),
1122        "opencode" => install_opencode_hook_with_mode(mode),
1123        "amp" => install_amp_hook(),
1124        "crush" => install_crush_hook_with_mode(mode),
1125        "openclaw" => install_openclaw_hook(),
1126        "hermes" => install_hermes_hook_with_mode(global, mode),
1127        "vibe" => install_vibe_hook(),
1128        "zed" => {
1129            let zed_path = crate::core::editor_registry::zed_settings_path(&home);
1130            let binary = resolve_binary_path();
1131            let entry = full_server_entry(&binary);
1132            install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
1133        }
1134        "aider" => {
1135            install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
1136        }
1137        "continue" => install_mcp_json_agent(
1138            "Continue",
1139            "~/.continue/mcp.json",
1140            &home.join(".continue/mcp.json"),
1141        ),
1142        "neovim" => install_mcp_json_agent(
1143            "Neovim (mcphub.nvim)",
1144            "~/.config/mcphub/servers.json",
1145            &home.join(".config/mcphub/servers.json"),
1146        ),
1147        "emacs" => install_mcp_json_agent(
1148            "Emacs (mcp.el)",
1149            "~/.emacs.d/mcp.json",
1150            &home.join(".emacs.d/mcp.json"),
1151        ),
1152        "sublime" => install_mcp_json_agent(
1153            "Sublime Text",
1154            "~/.config/sublime-text/mcp.json",
1155            &home.join(".config/sublime-text/mcp.json"),
1156        ),
1157        _ => {
1158            eprintln!("Unknown agent: {agent}");
1159            eprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
1160            eprintln!(
1161                "    claude, cline, codebuddy, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, grok,"
1162            );
1163            eprintln!(
1164                "    grok-build, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi, qoder,"
1165            );
1166            eprintln!(
1167                "    qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vibe, vscode, windsurf, zed"
1168            );
1169            std::process::exit(1);
1170        }
1171    }
1172}
1173
1174/// Install an agent integration for an explicit setup/repair action.
1175///
1176/// `setup.auto_inject_rules=false` only disables automatic steering and may be
1177/// overridden by an explicit action. `rules_injection=off` is the stronger
1178/// policy boundary: even explicit setup/repair must retain only the functional
1179/// runtime integration and must not recreate steering artifacts.
1180pub(crate) fn install_agent_hook_respecting_rules_off(agent: &str, global: bool, mode: HookMode) {
1181    if crate::core::config::Config::load().rules_injection_effective()
1182        == crate::core::config::RulesInjection::Off
1183    {
1184        install_agent_runtime_hook_with_mode(agent, global, mode);
1185    } else {
1186        install_agent_hook_with_mode(agent, global, mode);
1187    }
1188}
1189
1190/// Install only the functional runtime integration for an agent.
1191///
1192/// Unlike `install_agent_hook_with_mode`, this path must not create or
1193/// register lean-ctx-authored rule/instruction files. Automatic `setup` uses
1194/// it whenever steering is declined; explicit setup/repair reaches it through
1195/// `install_agent_hook_respecting_rules_off` only for the stronger
1196/// `rules_injection=off` policy.
1197pub(crate) fn install_agent_runtime_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1198    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1199
1200    match agent {
1201        "claude" | "claude-code" => {
1202            install_claude_hook_scripts(&home);
1203            install_claude_hook_config(&home);
1204            install_claude_statusline(&home);
1205
1206            if claude_hides_native_search(mode) {
1207                install_claude_permissions_deny_replace(&home);
1208            }
1209
1210            install_claude_permissions_allow_mcp(&home);
1211        }
1212        "codebuddy" => {
1213            install_codebuddy_hook_scripts(&home);
1214            install_codebuddy_hook_config(&home);
1215
1216            if claude_hides_native_search(mode) {
1217                install_codebuddy_permissions_deny_replace(&home, mode);
1218            }
1219        }
1220        "cursor" => {
1221            install_cursor_hook_scripts(&home);
1222            install_cursor_hook_config(&home);
1223
1224            if mode == HookMode::Replace {
1225                install_cursor_deny_hook(global);
1226            }
1227        }
1228        "gemini" => {
1229            install_gemini_hook_scripts(&home);
1230            install_gemini_hook_config(&home);
1231
1232            if mode == HookMode::Replace {
1233                install_gemini_deny_hook(&home);
1234            }
1235
1236            // Gemini setup also maintains the Antigravity CLI runtime plugin.
1237            // Its SessionStart observe channel is independently governed by
1238            // declines_rule_steering().
1239            install_antigravity_cli_hook();
1240        }
1241        "codex" => install_codex_runtime_hook(),
1242        "windsurf" => {
1243            if mode == HookMode::Replace {
1244                install_windsurf_hooks_replace(&home);
1245            } else {
1246                install_windsurf_hooks(&home);
1247            }
1248        }
1249        "copilot" | "vscode" => install_copilot_runtime_hook(global),
1250        "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
1251
1252        // Pi's global setup installs the runtime package/config but deliberately
1253        // skips its project-local AGENTS.md when global=true.
1254        "pi" => install_pi_hook_with_mode(global, mode),
1255
1256        // These integrations are functional MCP/plugin installers and do not
1257        // create lean-ctx rule files themselves.
1258        "antigravity" => install_antigravity_hook(),
1259        "antigravity-cli" => install_antigravity_cli_hook(),
1260        "amp" => install_amp_hook(),
1261        "jetbrains" => install_jetbrains_hook(),
1262        "openclaw" => install_openclaw_hook(),
1263        "vibe" => install_vibe_hook(),
1264        // No independent runtime hook exists for the remaining integrations.
1265        // Their MCP registration is handled separately by setup's editor/MCP
1266        // writers. Do not call their full installers here because some also
1267        // create rule/steering files. Unknown agents are likewise a safe no-op.
1268        _ => {}
1269    }
1270}
1271
1272pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
1273    match agent {
1274        "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
1275        "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
1276        _ => {}
1277    }
1278}
1279
1280fn write_file(path: &std::path::Path, content: &str) {
1281    // Skip identical rewrites: re-running setup/init must not churn mtimes or
1282    // leave .bak files behind for content that did not change (GL #558).
1283    if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1284        return;
1285    }
1286    if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
1287        tracing::error!("Error writing {}: {e}", path.display());
1288    }
1289}
1290
1291/// Create a setup directory, surfacing a clear error instead of silently
1292/// swallowing it (#596).
1293///
1294/// A user may symlink `~/.claude` / `~/.codex` (or a child) into a dotfiles
1295/// repo; [`crate::config_io::ensure_dir`] follows such a symlink to its real
1296/// in-`$HOME` target and tolerates a dangling one. Returns `false` (after
1297/// printing the reason) when the directory cannot be prepared, so the caller can
1298/// skip the now-impossible writes rather than failing confusingly downstream.
1299fn ensure_state_dir(dir: &std::path::Path) -> bool {
1300    match crate::config_io::ensure_dir(dir) {
1301        Ok(()) => true,
1302        Err(e) => {
1303            // Always surface — a swallowed dir failure was the #596 footgun.
1304            eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
1305            false
1306        }
1307    }
1308}
1309
1310fn is_inside_git_repo(path: &std::path::Path) -> bool {
1311    let mut p = path;
1312    loop {
1313        if p.join(".git").exists() {
1314            return true;
1315        }
1316        match p.parent() {
1317            Some(parent) => p = parent,
1318            None => return false,
1319        }
1320    }
1321}
1322
1323#[cfg(unix)]
1324fn make_executable(path: &PathBuf) {
1325    use std::os::unix::fs::PermissionsExt;
1326    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1327}
1328
1329#[cfg(not(unix))]
1330fn make_executable(_path: &PathBuf) {}
1331
1332/// Env key/value pairs for the lean-ctx MCP server entry written into agent
1333/// configs (Codex TOML + the JSON agents).
1334///
1335/// Deliberately does NOT pin `LEAN_CTX_DATA_DIR`: lean-ctx auto-detects its
1336/// per-category dirs (config/data/state/cache) at runtime, and pinning the data
1337/// dir would set that var in the server's environment, forcing single-dir mode
1338/// and collapsing config/state/cache onto the data dir — defeating the XDG split
1339/// (GH #408).
1340///
1341/// Deliberately does NOT pin a project either. Agent configs are user-global:
1342/// one `~/.codex/config.toml` serves every Codex session on the machine. The
1343/// #403 build copied the *installing* process's `LEAN_CTX_PROJECT_ROOT` /
1344/// `LEAN_CTX_EXTRA_ROOTS` in here, so whichever project last ran `setup`,
1345/// `doctor --fix` or an MCP-start hook refresh became the project of every
1346/// later session — and each switch needed a config edit plus an MCP restart.
1347/// The server derives its project per session instead (host roots, host env,
1348/// working directory) and reads `extra_roots` from config.toml itself; stale
1349/// pins are removed by [`project_pins`].
1350///
1351/// Single source of truth so every agent installer stays consistent; it is
1352/// currently empty on purpose.
1353pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
1354    Vec::new()
1355}
1356
1357/// The MCP server env block as a JSON object, for the JSON-config agents.
1358pub(crate) fn mcp_server_env_json() -> serde_json::Value {
1359    let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
1360        .into_iter()
1361        .map(|(k, v)| (k, serde_json::Value::String(v)))
1362        .collect();
1363    serde_json::Value::Object(map)
1364}
1365
1366fn full_server_entry(binary: &str) -> serde_json::Value {
1367    // No LEAN_CTX_FULL_TOOLS here: forcing the full toolset (69+ schemas,
1368    // ~15k tokens of tool definitions resent every turn) made lean-ctx one of
1369    // the biggest token consumers in users' sessions (GitHub #385). The server
1370    // defaults to the core toolset + ctx_call/ctx_expand for on-demand access;
1371    // power users opt in via `tool_profile = "power"` in config.toml.
1372    serde_json::json!({
1373        "command": binary,
1374        "env": mcp_server_env_json()
1375    })
1376}
1377
1378pub(crate) fn install_mcp_json_agent(
1379    name: &str,
1380    display_path: &str,
1381    config_path: &std::path::Path,
1382) {
1383    let binary = resolve_binary_path();
1384    let entry = full_server_entry(&binary);
1385    install_named_json_server(name, display_path, config_path, "mcpServers", entry);
1386}
1387
1388#[cfg(test)]
1389mod tests;