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