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