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