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