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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum HookMode {
13    #[default]
14    Mcp,
15    Hybrid,
16}
17
18impl std::fmt::Display for HookMode {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            Self::Mcp => write!(f, "MCP"),
22            Self::Hybrid => write!(f, "Hybrid"),
23        }
24    }
25}
26
27impl HookMode {
28    pub fn from_str_loose(s: &str) -> Option<Self> {
29        match s.to_lowercase().replace('-', "").as_str() {
30            "mcp" => Some(Self::Mcp),
31            "hybrid" => Some(Self::Hybrid),
32            _ => None,
33        }
34    }
35
36    pub fn description(&self) -> &'static str {
37        match self {
38            Self::Mcp => "MCP server only (extension/plugin-based agents without reliable shell)",
39            Self::Hybrid => "MCP server + shell hooks for command compression (best of both)",
40        }
41    }
42}
43
44/// Auto-detect the best hook mode for a given agent key based on its shell capabilities.
45///
46/// Criteria (verified against provider docs May 2026):
47///   Hybrid — MCP server (full Context OS) + shell hooks where available.
48///            Read/Search via MCP (reliable, cached). Shell via hooks (zero overhead).
49///   Mcp    — agent has no reliable direct shell tool (e.g. IDE plugin only)
50/// Agents that get the Hybrid integration (MCP for reads/search + shell hooks
51/// or rules for command compression). Kept as a single data list so it is
52/// testable and so `refresh_installed_hooks` can prove it covers every one of
53/// them (see `refresh_covers_every_hybrid_agent`).
54pub const HYBRID_AGENTS: &[&str] = &[
55    "cursor",
56    "gemini",
57    "codex",
58    "claude",
59    "claude-code",
60    "crush",
61    "hermes",
62    "opencode",
63    "openclaw",
64    "pi",
65    "qoder",
66    "windsurf",
67    "amp",
68    "cline",
69    "roo",
70    "copilot",
71    "kiro",
72    "qwen",
73    "trae",
74    "antigravity",
75    "antigravity-cli",
76    "amazonq",
77    "verdent",
78];
79
80pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
81    if HYBRID_AGENTS.contains(&agent_key) {
82        HookMode::Hybrid
83    } else {
84        // No reliable direct shell tool → MCP only.
85        HookMode::Mcp
86    }
87}
88use agents::{
89    install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
90    install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
91    install_claude_project_hooks, install_cline_rules, install_codebuddy_hook_config,
92    install_codebuddy_hook_scripts, install_codebuddy_hook_with_mode,
93    install_codebuddy_project_hooks, install_codex_hook, install_copilot_hook,
94    install_crush_hook_with_mode, install_cursor_hook_config, install_cursor_hook_scripts,
95    install_cursor_hook_with_mode, install_gemini_hook, install_gemini_hook_config,
96    install_gemini_hook_scripts, install_hermes_hook_with_mode, install_jetbrains_hook,
97    install_kiro_hook, install_openclaw_hook, install_opencode_hook_with_mode,
98    install_pi_hook_with_mode, install_qoder_hook, install_qoder_hook_with_mode,
99    install_windsurf_hooks, install_windsurf_rules,
100};
101use support::{
102    ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
103    upsert_lean_ctx_codex_hook_entries,
104};
105
106fn mcp_server_quiet_mode() -> bool {
107    std::env::var_os("LEAN_CTX_MCP_SERVER").is_some()
108        || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(value) if value.trim() == "1")
109}
110
111/// Agents whose global shell-hook artifacts embed the binary path / command
112/// and therefore must be re-rendered after an update or on MCP server start so
113/// they always point at the current binary. Each entry is gated on a detection
114/// marker (see `hooks_installed_for`) so we never install hooks for an agent
115/// the user never configured. The `refresh_covers_every_hybrid_agent` test
116/// proves this list plus `REFRESH_EXEMPT_HYBRID_AGENTS` accounts for every
117/// Hybrid agent, so a newly added agent can never silently regress.
118const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
119    "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder",
120];
121
122/// Hybrid agents intentionally NOT auto-refreshed, with the reason each is safe
123/// to skip. Refresh runs silently (including on every MCP server start), so it
124/// must never spawn subprocesses or write project/cwd-relative files. Used by
125/// the coverage test to prove every Hybrid agent has an explicit decision.
126#[cfg(test)]
127const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
128    // Alias of `claude` — same global files, already refreshed via "claude".
129    "claude-code",
130    // Installer shells out to `pi install` (subprocess) — unsafe on every start.
131    "pi",
132    // Write project/cwd-relative rules (.clinerules, .kiro/steering) — a silent
133    // server-start refresh must not create files in the user's working dir.
134    "cline",
135    "roo",
136    "kiro",
137    // MCP-config / rules wiring only (no global binary-embedding shell-hook
138    // script to keep current); refreshed by `setup --fix`, not on start.
139    "antigravity",
140    "antigravity-cli",
141    "amp",
142    "crush",
143    "hermes",
144    "opencode",
145    "openclaw",
146    "qwen",
147    "trae",
148    "amazonq",
149    "verdent",
150];
151
152/// Silently refresh all hook scripts for agents that are already configured.
153/// Called after updates and on MCP server start to ensure hooks match the
154/// current binary version. Registry-driven: every Hybrid agent with a global
155/// shell hook is covered (the rest are explicitly exempted, enforced by test).
156pub fn refresh_installed_hooks() {
157    let Some(home) = crate::core::home::resolve_home_dir() else {
158        return;
159    };
160    for agent in REFRESHABLE_HOOK_AGENTS {
161        if hooks_installed_for(agent, &home) {
162            refresh_agent_hooks(agent, &home);
163        }
164    }
165}
166
167/// True when `agent` already has lean-ctx hook artifacts on disk (global only).
168fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
169    match agent {
170        "claude" => {
171            let dir = crate::setup::claude_config_dir(home);
172            dir.join("hooks/lean-ctx-rewrite.sh").exists()
173                || file_contains_lean_ctx(&dir.join("settings.json"))
174        }
175        "codebuddy" => {
176            let dir = crate::core::editor_registry::codebuddy_state_dir(home);
177            dir.join("hooks/lean-ctx-rewrite.sh").exists()
178                || file_contains_lean_ctx(&dir.join("settings.json"))
179        }
180        "cursor" => {
181            home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
182                || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
183        }
184        "gemini" => {
185            home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
186                .exists()
187                || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
188        }
189        "codex" => {
190            let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
191            dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
192                || file_contains_lean_ctx(&dir.join("hooks.json"))
193        }
194        "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
195        "copilot" => {
196            // User-level Copilot hooks live under ~/.copilot/hooks (#381);
197            // ~/.github/hooks is the pre-#381 legacy location.
198            file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
199                || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
200        }
201        "qoder" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
202        _ => false,
203    }
204}
205
206/// Re-render the hook artifacts for an already-configured agent. Only calls
207/// narrow, subprocess-free, global installers (never the full agent setup).
208fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
209    match agent {
210        "claude" => {
211            install_claude_hook_scripts(home);
212            install_claude_hook_config(home);
213        }
214        "codebuddy" => {
215            install_codebuddy_hook_scripts(home);
216            install_codebuddy_hook_config(home);
217        }
218        "cursor" => {
219            install_cursor_hook_scripts(home);
220            install_cursor_hook_config(home);
221        }
222        "gemini" => {
223            install_gemini_hook_scripts(home);
224            install_gemini_hook_config(home);
225        }
226        "codex" => install_codex_hook(),
227        "windsurf" => install_windsurf_hooks(home),
228        "copilot" => install_copilot_hook(true),
229        "qoder" => install_qoder_hook(),
230        _ => {}
231    }
232}
233
234fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
235    std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
236}
237
238/// Resolve the lean-ctx binary to an **absolute** path for generated hook
239/// commands and MCP server entries.
240///
241/// Agent hooks (Codex, Cursor, Claude, Gemini, Antigravity, …) are executed by
242/// the host under a plain non-login shell (`sh -c …`) whose `PATH` is not
243/// guaranteed to contain the install dir (e.g. `/usr/local/bin`). A bare
244/// `lean-ctx` therefore fails with exit code 127 (#367). Always emitting the
245/// resolved absolute path makes hook execution deterministic and matches what
246/// MCP setup (`setup/mcp.rs`) and `doctor` already do. Existing configs with a
247/// bare command are rewritten on the next `lean-ctx init` / `doctor` run.
248fn resolve_binary_path() -> String {
249    crate::core::portable_binary::resolve_portable_binary()
250}
251
252fn resolve_binary_path_for_bash() -> String {
253    let path = resolve_binary_path();
254    to_bash_compatible_path(&path)
255}
256
257pub fn to_bash_compatible_path(path: &str) -> String {
258    let path = match crate::core::pathutil::strip_verbatim_str(path) {
259        Some(stripped) => stripped,
260        None => path.replace('\\', "/"),
261    };
262    if path.len() >= 2 && path.as_bytes()[1] == b':' {
263        let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
264        format!("/{drive}{}", &path[2..])
265    } else {
266        path
267    }
268}
269
270/// Convert a Unix/MSYS-style path (`/c/Users/...`) back to native Windows
271/// format (`C:/Users/...`). No-op for paths that don't match the pattern.
272pub fn from_bash_to_native_path(path: &str) -> String {
273    crate::core::pathutil::normalize_tool_path(path)
274}
275
276/// Normalize paths from any client format to a consistent OS-native form.
277/// Delegates to `core::pathutil` so `core` crates do not depend on `hooks`.
278pub fn normalize_tool_path(path: &str) -> String {
279    crate::core::pathutil::normalize_tool_path(path)
280}
281
282pub fn generate_rewrite_script(binary: &str) -> String {
283    let case_pattern = crate::rewrite_registry::bash_case_pattern();
284    format!(
285        r#"#!/usr/bin/env bash
286# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
287set -euo pipefail
288
289LEAN_CTX_BIN="{binary}"
290
291INPUT=$(cat)
292TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
293
294case "$TOOL" in
295  Bash|bash|PowerShell|powershell) ;;
296  *) exit 0 ;;
297esac
298
299CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
300
301if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
302  exit 0
303fi
304
305case "$CMD" in
306  {case_pattern})
307    # Shell-escape then JSON-escape (two passes)
308    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
309    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
310    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
311    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
312    ;;
313  *) exit 0 ;;
314esac
315"#
316    )
317}
318
319pub fn generate_compact_rewrite_script(binary: &str) -> String {
320    let case_pattern = crate::rewrite_registry::bash_case_pattern();
321    format!(
322        r#"#!/usr/bin/env bash
323# lean-ctx hook — rewrites shell commands
324set -euo pipefail
325LEAN_CTX_BIN="{binary}"
326INPUT=$(cat)
327CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
328if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
329case "$CMD" in
330  {case_pattern})
331    SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
332    REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
333    JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
334    printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
335  *) exit 0 ;;
336esac
337"#
338    )
339}
340
341const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
342# lean-ctx PreToolUse hook — all native tools pass through
343# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
344# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
345exit 0
346";
347
348const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
349# lean-ctx hook — all native tools pass through
350exit 0
351";
352
353pub fn hybrid_rules_content() -> String {
354    use crate::core::rules_canonical;
355    format!(
356        "{start}\n<!-- version: {version} -->\n\n\
357# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
358{bullets}\n\n\
359{never}\n\n\
360{end}",
361        start = rules_canonical::START_MARK,
362        version = rules_canonical::RULES_VERSION,
363        bullets = rules_canonical::BULLETS,
364        never = rules_canonical::NEVER,
365        end = rules_canonical::END_MARK,
366    )
367}
368
369pub fn install_project_rules() {
370    install_project_rules_for_agents(&[]);
371}
372
373/// Install project rules, optionally scoped to specific agents.
374/// If `agents` is empty, installs for all agents (legacy behavior).
375pub fn install_project_rules_for_agents(agents: &[&str]) {
376    if crate::core::config::Config::load().rules_scope_effective()
377        == crate::core::config::RulesScope::Global
378    {
379        return;
380    }
381
382    let cwd = std::env::current_dir().unwrap_or_default();
383
384    if !is_inside_git_repo(&cwd) {
385        eprintln!(
386            "  Skipping project files: not inside a git repository.\n  \
387             Run this command from your project root to create CLAUDE.md / AGENTS.md."
388        );
389        return;
390    }
391
392    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
393    if cwd == home {
394        eprintln!(
395            "  Skipping project files: current directory is your home folder.\n  \
396             Run this command from a project directory instead."
397        );
398        return;
399    }
400
401    let all = agents.is_empty();
402    let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
403
404    ensure_project_agents_integration(&cwd);
405
406    if wants("cursor") || wants("windsurf") {
407        let cursorrules = cwd.join(".cursorrules");
408        if !cursorrules.exists()
409            || !std::fs::read_to_string(&cursorrules)
410                .unwrap_or_default()
411                .contains("lean-ctx")
412        {
413            let content = cursorrules_content();
414            if cursorrules.exists() {
415                let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
416                if !existing.ends_with('\n') {
417                    existing.push('\n');
418                }
419                existing.push('\n');
420                existing.push_str(&content);
421                write_file(&cursorrules, &existing);
422            } else {
423                write_file(&cursorrules, &content);
424            }
425            if !mcp_server_quiet_mode() {
426                eprintln!("Created/updated .cursorrules in project root.");
427            }
428        }
429    }
430
431    if wants("claude") {
432        // GL #555: project rules files without `paths:` frontmatter load
433        // unconditionally every session and stacked on top of the global
434        // CLAUDE.md block (12k+ token memory footprints in the field). The
435        // AGENTS.md block + on-demand skill carry the same guidance, so the
436        // lean-ctx-owned copy is removed instead of refreshed.
437        let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
438        if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
439            && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
440            && std::fs::remove_file(&claude_rules_file).is_ok()
441            && !mcp_server_quiet_mode()
442        {
443            eprintln!(
444                "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
445            );
446        }
447
448        install_claude_project_hooks(&cwd);
449    }
450
451    if wants("codebuddy") {
452        let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
453        if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
454            && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
455            && std::fs::remove_file(&codebuddy_rules_file).is_ok()
456            && !mcp_server_quiet_mode()
457        {
458            eprintln!(
459                "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
460            );
461        }
462
463        install_codebuddy_project_hooks(&cwd);
464    }
465
466    if wants("kiro") {
467        let kiro_dir = cwd.join(".kiro");
468        if kiro_dir.exists() {
469            let steering_dir = kiro_dir.join("steering");
470            let steering_file = steering_dir.join("lean-ctx.md");
471            if !steering_file.exists()
472                || !std::fs::read_to_string(&steering_file)
473                    .unwrap_or_default()
474                    .contains("lean-ctx")
475            {
476                let _ = std::fs::create_dir_all(&steering_dir);
477                write_file(&steering_file, &kiro_steering_content());
478                if !mcp_server_quiet_mode() {
479                    eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
480                }
481            }
482        }
483    }
484
485    if wants("copilot") || wants("vscode") {
486        ensure_copilot_instructions(&cwd);
487        ensure_vscode_instruction_files_setting(&cwd);
488    }
489}
490
491const PROJECT_LEAN_CTX_MD_MARKER: &str =
492    crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
493const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
494const PROJECT_AGENTS_MD: &str = "AGENTS.md";
495// The AGENTS.md pointer block keeps its own marker pair, independent of the
496// dedicated rules-file `START_MARK`: pointer-only files must not be counted as
497// duplicate lean-ctx sources (doctor overhead, #684).
498const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
499const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
500
501fn ensure_project_agents_integration(cwd: &std::path::Path) {
502    let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
503    let desired = format!(
504        "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
505        crate::rules_inject::rules_dedicated_markdown()
506    );
507
508    if !lean_ctx_md.exists() {
509        write_file(&lean_ctx_md, &desired);
510    } else if std::fs::read_to_string(&lean_ctx_md)
511        .unwrap_or_default()
512        .contains(PROJECT_LEAN_CTX_MD_MARKER)
513    {
514        let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
515        let version_str = format!(
516            "<!-- version: {} -->",
517            crate::core::rules_canonical::RULES_VERSION
518        );
519        if !current.contains(&version_str) {
520            write_file(&lean_ctx_md, &desired);
521        }
522    }
523
524    // No `@` import: Claude Code expands `@file` references inline at session
525    // start, so pointing at LEAN-CTX.md re-loaded the full ruleset into every
526    // session on top of this block (GL #555). The block is self-contained;
527    // the full ruleset stays in LEAN-CTX.md for on-demand reading.
528    let block = format!(
529        "{AGENTS_BLOCK_START}\n\
530## lean-ctx\n\n\
531lean-ctx is active — the MCP tools replace native equivalents.\n\
532Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
533{AGENTS_BLOCK_END}\n"
534    );
535
536    let agents_md = cwd.join(PROJECT_AGENTS_MD);
537    if !agents_md.exists() {
538        let content = format!("# Agent Instructions\n\n{block}");
539        write_file(&agents_md, &content);
540        if !mcp_server_quiet_mode() {
541            eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
542        }
543        return;
544    }
545
546    let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
547
548    if existing.contains("CLI-first Token Optimization for Pi")
549        && !existing.contains(AGENTS_BLOCK_START)
550    {
551        let content = format!("# Agent Instructions\n\n{block}");
552        write_file(&agents_md, &content);
553        return;
554    }
555
556    if existing.contains(AGENTS_BLOCK_START) {
557        let updated = crate::marked_block::replace_marked_block(
558            &existing,
559            AGENTS_BLOCK_START,
560            AGENTS_BLOCK_END,
561            &block,
562        );
563        if updated != existing {
564            write_file(&agents_md, &updated);
565        }
566        return;
567    }
568
569    if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
570        return;
571    }
572
573    let mut out = existing;
574    if !out.ends_with('\n') {
575        out.push('\n');
576    }
577    out.push('\n');
578    out.push_str(&block);
579    write_file(&agents_md, &out);
580    if !mcp_server_quiet_mode() {
581        eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
582    }
583}
584
585/// #555: VS Code Copilot Chat auto-applies `.github/copilot-instructions.md` to
586/// every request, but `init --agent copilot` previously wrote only a weak
587/// AGENTS.md pointer — Claude-family models then ignored the lean-ctx tool
588/// mapping while GPT-5.x mostly followed it. Write the strong dedicated ruleset
589/// into a `<!-- lean-ctx-rules -->` marked block so it merges idempotently and
590/// never clobbers the user's own instructions.
591fn ensure_copilot_instructions(cwd: &std::path::Path) {
592    let path = cwd.join(".github").join("copilot-instructions.md");
593    let block = crate::rules_inject::rules_dedicated_markdown();
594    let start = crate::core::rules_canonical::START_MARK;
595    let end = crate::core::rules_canonical::END_MARK;
596    let owned = format!("{}\n", block.trim_end());
597
598    let existing = std::fs::read_to_string(&path).unwrap_or_default();
599    let desired = if existing.trim().is_empty() {
600        owned
601    } else if existing.contains(start) {
602        // Refresh our block; keep any surrounding user-authored content.
603        let user = crate::marked_block::remove_content(&existing, start, end);
604        if user.trim().is_empty() {
605            owned
606        } else {
607            format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
608        }
609    } else {
610        // User-authored file with no lean-ctx block yet: append ours once.
611        format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
612    };
613
614    if desired == existing {
615        return;
616    }
617    if let Some(parent) = path.parent()
618        && std::fs::create_dir_all(parent).is_err()
619    {
620        return;
621    }
622    write_file(&path, &desired);
623    if !mcp_server_quiet_mode() {
624        eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
625    }
626}
627
628/// #555 safety net: VS Code applies instruction files when
629/// `github.copilot.chat.codeGeneration.useInstructionFiles` is on (the default).
630/// A user or org policy may have disabled it globally, so pin it on for this
631/// project. Set only when the key is absent — an explicit user value is honoured.
632fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
633    const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
634    let path = cwd.join(".vscode").join("settings.json");
635
636    let existing = std::fs::read_to_string(&path).unwrap_or_default();
637    let mut json = if existing.trim().is_empty() {
638        serde_json::json!({})
639    } else {
640        match crate::core::jsonc::parse_jsonc(&existing) {
641            Ok(v) if v.is_object() => v,
642            // Never clobber an unparseable or non-object settings file.
643            _ => return,
644        }
645    };
646    let Some(obj) = json.as_object_mut() else {
647        return;
648    };
649    if obj.contains_key(KEY) {
650        return;
651    }
652    obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
653
654    if let Some(parent) = path.parent()
655        && std::fs::create_dir_all(parent).is_err()
656    {
657        return;
658    }
659    let Ok(formatted) = serde_json::to_string_pretty(&json) else {
660        return;
661    };
662    if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
663        && !mcp_server_quiet_mode()
664    {
665        eprintln!("Set {KEY} in .vscode/settings.json.");
666    }
667}
668
669/// Compact pointer only (#578): Cursor already auto-loads the canonical full
670/// ruleset from `~/.cursor/rules/lean-ctx.mdc`, so a project `.cursorrules`
671/// that repeats it bills the same guidance twice in every session.
672pub fn cursorrules_content() -> String {
673    let start = crate::core::rules_canonical::START_MARK;
674    let end = crate::core::rules_canonical::END_MARK;
675    let version = crate::core::rules_canonical::RULES_VERSION;
676    format!(
677        "{start}\n<!-- version: {version} -->\n\n\
678# lean-ctx\n\n\
679{bullets}\n\n\
680{never}\n\
681Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
682{end}",
683        bullets = crate::core::rules_canonical::BULLETS,
684        never = crate::core::rules_canonical::NEVER,
685    )
686}
687
688pub fn kiro_steering_content() -> String {
689    use crate::core::rules_canonical;
690    format!(
691        "---\n\
692inclusion: always\n\
693---\n\n\
694# Context Engineering Layer\n\n\
695{start}\n\
696<!-- version: {version} -->\n\n\
697The workspace has the `lean-ctx` MCP server installed. \
698You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
699{bullets}\n\n\
700{never}\n\n\
701## When to use native Kiro tools instead\n\n\
702- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
703- `strReplace` \u{2014} always use native (precise string replacement)\n\
704- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
705- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
706- `deleteFile` \u{2014} always use native\n\
707- Glob \u{2014} always use native glob\n\n\
708{end}",
709        start = rules_canonical::START_MARK,
710        version = rules_canonical::RULES_VERSION,
711        bullets = rules_canonical::BULLETS,
712        never = rules_canonical::NEVER,
713        end = rules_canonical::END_MARK,
714    )
715}
716/// #281: whether the hooks layer may register the lean-ctx MCP server in an
717/// agent's config. Honors `[setup] auto_update_mcp`. Hooks, rules and skills
718/// still install when this is `false` — only the MCP-server writes are gated, so
719/// MCP-disabled environments stay free of MCP entries. Centralised here so every
720/// per-agent writer shares one source of truth (the shared JSON writer in
721/// `support.rs` enforces the same gate for `mcpServers`-style agents).
722pub(crate) fn should_register_mcp() -> bool {
723    crate::core::config::Config::load()
724        .setup
725        .should_update_mcp()
726}
727
728pub fn install_agent_hook(agent: &str, global: bool) {
729    install_agent_hook_with_mode(agent, global, HookMode::Mcp);
730}
731
732pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
733    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
734    match agent {
735        "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
736        "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
737        "cursor" => install_cursor_hook_with_mode(global, mode),
738        "gemini" => {
739            install_gemini_hook();
740            // Google is transitioning Gemini CLI → Antigravity CLI (`agy`), and
741            // `gemini` setup also configures the Antigravity CLI MCP target. The
742            // hooks must follow: `agy` reads hooks only from its plugin dir
743            // (`~/.gemini/config/plugins/lean-ctx`), never from the legacy
744            // `~/.gemini/settings.json`, so install the plugin too (#284).
745            install_antigravity_cli_hook();
746        }
747        "antigravity" => install_antigravity_hook(),
748        "antigravity-cli" => install_antigravity_cli_hook(),
749        "augment" => install_mcp_json_agent(
750            "Augment CLI",
751            "~/.augment/settings.json",
752            &crate::core::editor_registry::augment_cli_settings_path(&home),
753        ),
754        "codex" => install_codex_hook(),
755        "windsurf" => install_windsurf_rules(global),
756        "cline" | "roo" => install_cline_rules(global),
757        "copilot" | "vscode" => install_copilot_hook(global),
758        "pi" => install_pi_hook_with_mode(global, mode),
759        "qoder" => install_qoder_hook_with_mode(mode),
760        "qoderwork" => install_mcp_json_agent(
761            "QoderWork",
762            "~/.qoderwork/mcp.json",
763            &home.join(".qoderwork/mcp.json"),
764        ),
765        "qwen" => install_mcp_json_agent(
766            "Qwen Code",
767            "~/.qwen/settings.json",
768            &home.join(".qwen/settings.json"),
769        ),
770        "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
771        "amazonq" => install_mcp_json_agent(
772            "Amazon Q Developer",
773            "~/.aws/amazonq/default.json",
774            &home.join(".aws/amazonq/default.json"),
775        ),
776        "jetbrains" => install_jetbrains_hook(),
777        "kiro" => install_kiro_hook(),
778        "verdent" => install_mcp_json_agent(
779            "Verdent",
780            "~/.verdent/mcp.json",
781            &home.join(".verdent/mcp.json"),
782        ),
783        "opencode" => install_opencode_hook_with_mode(mode),
784        "amp" => install_amp_hook(),
785        "crush" => install_crush_hook_with_mode(mode),
786        "openclaw" => install_openclaw_hook(),
787        "hermes" => install_hermes_hook_with_mode(global, mode),
788        "zed" => {
789            let zed_path = crate::core::editor_registry::zed_settings_path(&home);
790            let binary = resolve_binary_path();
791            let entry = full_server_entry(&binary);
792            install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
793        }
794        "aider" => {
795            install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
796        }
797        "continue" => install_mcp_json_agent(
798            "Continue",
799            "~/.continue/mcp.json",
800            &home.join(".continue/mcp.json"),
801        ),
802        "neovim" => install_mcp_json_agent(
803            "Neovim (mcphub.nvim)",
804            "~/.config/mcphub/servers.json",
805            &home.join(".config/mcphub/servers.json"),
806        ),
807        "emacs" => install_mcp_json_agent(
808            "Emacs (mcp.el)",
809            "~/.emacs.d/mcp.json",
810            &home.join(".emacs.d/mcp.json"),
811        ),
812        "sublime" => install_mcp_json_agent(
813            "Sublime Text",
814            "~/.config/sublime-text/mcp.json",
815            &home.join(".config/sublime-text/mcp.json"),
816        ),
817        _ => {
818            eprintln!("Unknown agent: {agent}");
819            eprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
820            eprintln!(
821                "    claude, cline, codebuddy, codex, continue, copilot, crush, cursor, emacs, gemini,"
822            );
823            eprintln!("    hermes, jetbrains, kiro, neovim, openclaw, opencode, pi, qoder,");
824            eprintln!("    qoderwork, qwen, roo, sublime, trae, verdent, vscode, windsurf, zed");
825            std::process::exit(1);
826        }
827    }
828}
829
830pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
831    match agent {
832        "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
833        "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
834        _ => {}
835    }
836}
837
838fn write_file(path: &std::path::Path, content: &str) {
839    // Skip identical rewrites: re-running setup/init must not churn mtimes or
840    // leave .bak files behind for content that did not change (GL #558).
841    if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
842        return;
843    }
844    if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
845        tracing::error!("Error writing {}: {e}", path.display());
846    }
847}
848
849/// Create a setup directory, surfacing a clear error instead of silently
850/// swallowing it (#596).
851///
852/// A user may symlink `~/.claude` / `~/.codex` (or a child) into a dotfiles
853/// repo; [`crate::config_io::ensure_dir`] follows such a symlink to its real
854/// in-`$HOME` target and tolerates a dangling one. Returns `false` (after
855/// printing the reason) when the directory cannot be prepared, so the caller can
856/// skip the now-impossible writes rather than failing confusingly downstream.
857fn ensure_state_dir(dir: &std::path::Path) -> bool {
858    match crate::config_io::ensure_dir(dir) {
859        Ok(()) => true,
860        Err(e) => {
861            // Always surface — a swallowed dir failure was the #596 footgun.
862            eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
863            false
864        }
865    }
866}
867
868fn is_inside_git_repo(path: &std::path::Path) -> bool {
869    let mut p = path;
870    loop {
871        if p.join(".git").exists() {
872            return true;
873        }
874        match p.parent() {
875            Some(parent) => p = parent,
876            None => return false,
877        }
878    }
879}
880
881#[cfg(unix)]
882fn make_executable(path: &PathBuf) {
883    use std::os::unix::fs::PermissionsExt;
884    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
885}
886
887#[cfg(not(unix))]
888fn make_executable(_path: &PathBuf) {}
889
890/// Env key/value pairs for the lean-ctx MCP server entry written into agent
891/// configs (Codex TOML + the JSON agents).
892///
893/// Deliberately does NOT pin `LEAN_CTX_DATA_DIR`: lean-ctx auto-detects its
894/// per-category dirs (config/data/state/cache) at runtime, and pinning the data
895/// dir would set that var in the server's environment, forcing single-dir mode
896/// and collapsing config/state/cache onto the data dir — defeating the XDG split
897/// (GH #408). Emits `LEAN_CTX_PROJECT_ROOT` and `LEAN_CTX_EXTRA_ROOTS` when known
898/// (process env first, then config). Without these, a long-lived MCP server
899/// spawned by the agent loses the project / worktree scope captured at `init`,
900/// so an explicit path under a sibling worktree is wrongly rejected as a jail
901/// escape (#403). Single source of truth so every agent installer stays consistent.
902pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
903    let mut pairs = Vec::new();
904
905    let cfg = crate::core::config::Config::load();
906
907    let project_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
908        .ok()
909        .filter(|v| !v.trim().is_empty())
910        .or_else(|| cfg.project_root.clone().filter(|v| !v.trim().is_empty()));
911    if let Some(root) = project_root {
912        pairs.push(("LEAN_CTX_PROJECT_ROOT".to_string(), root));
913    }
914
915    // Env override is already a platform path-list; config is a Vec we join the
916    // same way `LEAN_CTX_EXTRA_ROOTS` is parsed (`std::env::split_paths`).
917    let extra_roots = std::env::var("LEAN_CTX_EXTRA_ROOTS")
918        .ok()
919        .filter(|v| !v.trim().is_empty())
920        .or_else(|| {
921            let roots: Vec<&str> = cfg
922                .extra_roots
923                .iter()
924                .map(String::as_str)
925                .filter(|s| !s.trim().is_empty())
926                .collect();
927            if roots.is_empty() {
928                return None;
929            }
930            std::env::join_paths(roots)
931                .ok()
932                .map(|s| s.to_string_lossy().to_string())
933        });
934    if let Some(extra) = extra_roots {
935        pairs.push(("LEAN_CTX_EXTRA_ROOTS".to_string(), extra));
936    }
937
938    pairs
939}
940
941/// The MCP server env block as a JSON object, for the JSON-config agents.
942pub(crate) fn mcp_server_env_json() -> serde_json::Value {
943    let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
944        .into_iter()
945        .map(|(k, v)| (k, serde_json::Value::String(v)))
946        .collect();
947    serde_json::Value::Object(map)
948}
949
950fn full_server_entry(binary: &str) -> serde_json::Value {
951    // No LEAN_CTX_FULL_TOOLS here: forcing the full toolset (69+ schemas,
952    // ~15k tokens of tool definitions resent every turn) made lean-ctx one of
953    // the biggest token consumers in users' sessions (GitHub #385). The server
954    // defaults to the core toolset + ctx_call/ctx_expand for on-demand access;
955    // power users opt in via `tool_profile = "power"` in config.toml.
956    serde_json::json!({
957        "command": binary,
958        "env": mcp_server_env_json()
959    })
960}
961
962pub(crate) fn install_mcp_json_agent(
963    name: &str,
964    display_path: &str,
965    config_path: &std::path::Path,
966) {
967    let binary = resolve_binary_path();
968    let entry = full_server_entry(&binary);
969    install_named_json_server(name, display_path, config_path, "mcpServers", entry);
970}
971
972#[cfg(test)]
973mod tests {
974    use super::*;
975
976    #[test]
977    fn refresh_covers_every_hybrid_agent() {
978        // Every Hybrid agent must be in exactly one of the two sets, so a newly
979        // added agent can never silently skip the post-update hook refresh.
980        for agent in HYBRID_AGENTS {
981            let refreshed = REFRESHABLE_HOOK_AGENTS.contains(agent);
982            let exempt = REFRESH_EXEMPT_HYBRID_AGENTS.contains(agent);
983            assert!(
984                refreshed ^ exempt,
985                "hybrid agent `{agent}` must be either refreshed or explicitly exempt (exactly one)"
986            );
987        }
988    }
989
990    #[test]
991    fn refresh_sets_reference_only_hybrid_agents() {
992        for agent in REFRESHABLE_HOOK_AGENTS {
993            assert!(
994                HYBRID_AGENTS.contains(agent),
995                "refreshable agent `{agent}` is not a Hybrid agent"
996            );
997        }
998        for agent in REFRESH_EXEMPT_HYBRID_AGENTS {
999            assert!(
1000                HYBRID_AGENTS.contains(agent),
1001                "exempt agent `{agent}` is not a Hybrid agent (stale exemption?)"
1002            );
1003        }
1004    }
1005
1006    // ── #555: .github/copilot-instructions.md ──────────────────────────────
1007
1008    #[test]
1009    fn copilot_instructions_created_with_lean_ctx_block() {
1010        let _iso = crate::core::data_dir::isolated_data_dir();
1011        let tmp = tempfile::tempdir().unwrap();
1012        ensure_copilot_instructions(tmp.path());
1013
1014        let path = tmp.path().join(".github/copilot-instructions.md");
1015        let content = std::fs::read_to_string(&path).expect("copilot-instructions.md created");
1016        assert!(content.contains(crate::core::rules_canonical::START_MARK));
1017        assert!(content.contains(crate::core::rules_canonical::END_MARK));
1018        assert!(content.contains("lean-ctx"));
1019    }
1020
1021    #[test]
1022    fn copilot_instructions_idempotent() {
1023        let _iso = crate::core::data_dir::isolated_data_dir();
1024        let tmp = tempfile::tempdir().unwrap();
1025        let path = tmp.path().join(".github/copilot-instructions.md");
1026
1027        ensure_copilot_instructions(tmp.path());
1028        let first = std::fs::read_to_string(&path).unwrap();
1029        ensure_copilot_instructions(tmp.path());
1030        let second = std::fs::read_to_string(&path).unwrap();
1031
1032        assert_eq!(first, second, "re-running must produce identical bytes");
1033        assert_eq!(
1034            first
1035                .matches(crate::core::rules_canonical::START_MARK)
1036                .count(),
1037            1,
1038            "exactly one lean-ctx block, no duplication"
1039        );
1040    }
1041
1042    #[test]
1043    fn copilot_instructions_preserve_user_content() {
1044        let _iso = crate::core::data_dir::isolated_data_dir();
1045        let tmp = tempfile::tempdir().unwrap();
1046        let path = tmp.path().join(".github/copilot-instructions.md");
1047        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1048        std::fs::write(&path, "# House rules\n\nAlways write tests.\n").unwrap();
1049
1050        ensure_copilot_instructions(tmp.path());
1051        let content = std::fs::read_to_string(&path).unwrap();
1052        assert!(content.contains("# House rules"));
1053        assert!(content.contains("Always write tests."));
1054        assert!(content.contains(crate::core::rules_canonical::START_MARK));
1055
1056        // Idempotent on a user-authored file as well.
1057        ensure_copilot_instructions(tmp.path());
1058        let again = std::fs::read_to_string(&path).unwrap();
1059        assert_eq!(content, again);
1060        assert_eq!(
1061            again
1062                .matches(crate::core::rules_canonical::START_MARK)
1063                .count(),
1064            1
1065        );
1066    }
1067
1068    #[test]
1069    fn copilot_instructions_block_is_removable() {
1070        // Mirrors the uninstall path: the marked block must be strippable while
1071        // user content survives.
1072        let _iso = crate::core::data_dir::isolated_data_dir();
1073        let tmp = tempfile::tempdir().unwrap();
1074        let path = tmp.path().join(".github/copilot-instructions.md");
1075        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1076        std::fs::write(&path, "# House rules\n\nKeep it tidy.\n").unwrap();
1077        ensure_copilot_instructions(tmp.path());
1078
1079        let content = std::fs::read_to_string(&path).unwrap();
1080        let cleaned = crate::marked_block::remove_content(
1081            &content,
1082            crate::core::rules_canonical::START_MARK,
1083            crate::core::rules_canonical::END_MARK,
1084        );
1085        assert!(!cleaned.contains(crate::core::rules_canonical::START_MARK));
1086        assert!(cleaned.contains("# House rules"));
1087    }
1088
1089    #[test]
1090    fn vscode_instruction_setting_set_when_absent_and_preserves() {
1091        let tmp = tempfile::tempdir().unwrap();
1092        let vscode = tmp.path().join(".vscode");
1093        std::fs::create_dir_all(&vscode).unwrap();
1094        let settings = vscode.join("settings.json");
1095        std::fs::write(&settings, "{\n  \"editor.fontSize\": 13\n}\n").unwrap();
1096
1097        ensure_vscode_instruction_files_setting(tmp.path());
1098        let v: serde_json::Value =
1099            serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
1100        assert_eq!(v["editor.fontSize"], 13);
1101        assert_eq!(
1102            v["github.copilot.chat.codeGeneration.useInstructionFiles"],
1103            true
1104        );
1105    }
1106
1107    #[test]
1108    fn vscode_instruction_setting_respects_explicit_user_value() {
1109        let tmp = tempfile::tempdir().unwrap();
1110        let vscode = tmp.path().join(".vscode");
1111        std::fs::create_dir_all(&vscode).unwrap();
1112        let settings = vscode.join("settings.json");
1113        std::fs::write(
1114            &settings,
1115            "{\n  \"github.copilot.chat.codeGeneration.useInstructionFiles\": false\n}\n",
1116        )
1117        .unwrap();
1118
1119        ensure_vscode_instruction_files_setting(tmp.path());
1120        let v: serde_json::Value =
1121            serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
1122        assert_eq!(
1123            v["github.copilot.chat.codeGeneration.useInstructionFiles"], false,
1124            "an explicit user value must not be overridden"
1125        );
1126    }
1127
1128    #[test]
1129    fn mcp_env_pairs_propagate_project_and_extra_roots_from_env() {
1130        // #403: init must bake the captured project/worktree scope into the MCP
1131        // server entry, otherwise the long-lived server rejects explicit paths
1132        // under sibling worktrees as jail escapes.
1133        let _iso = crate::core::data_dir::isolated_data_dir();
1134        crate::test_env::set_var("LEAN_CTX_PROJECT_ROOT", "/work/main");
1135        crate::test_env::set_var("LEAN_CTX_EXTRA_ROOTS", "/work/wt-a:/work/wt-b");
1136
1137        let pairs = mcp_server_env_pairs();
1138        let get = |k: &str| pairs.iter().find(|(p, _)| p == k).map(|(_, v)| v.as_str());
1139        assert!(
1140            get("LEAN_CTX_DATA_DIR").is_none(),
1141            "data dir is auto-detected at runtime, never pinned into the config (GH #408)"
1142        );
1143        assert_eq!(get("LEAN_CTX_PROJECT_ROOT"), Some("/work/main"));
1144        assert_eq!(get("LEAN_CTX_EXTRA_ROOTS"), Some("/work/wt-a:/work/wt-b"));
1145
1146        // The JSON view mirrors the pairs for the JSON-config agents.
1147        let json = mcp_server_env_json();
1148        assert_eq!(json["LEAN_CTX_PROJECT_ROOT"].as_str(), Some("/work/main"));
1149
1150        crate::test_env::remove_var("LEAN_CTX_PROJECT_ROOT");
1151        crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1152    }
1153
1154    #[test]
1155    fn mcp_env_pairs_omit_roots_when_unset() {
1156        // No project context configured anywhere ⇒ no env vars are emitted: the
1157        // data dir is auto-detected (never pinned, GH #408) and we never write
1158        // empty/placeholder root keys into agent configs.
1159        let _iso = crate::core::data_dir::isolated_data_dir();
1160        crate::test_env::remove_var("LEAN_CTX_PROJECT_ROOT");
1161        crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1162
1163        let pairs = mcp_server_env_pairs();
1164        let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
1165        assert!(!keys.contains(&"LEAN_CTX_DATA_DIR"));
1166        assert!(!keys.contains(&"LEAN_CTX_PROJECT_ROOT"));
1167        assert!(!keys.contains(&"LEAN_CTX_EXTRA_ROOTS"));
1168    }
1169
1170    #[test]
1171    fn hooks_installed_for_is_false_without_artifacts() {
1172        let tmp = unique_tmp_dir("leanctx_refresh_empty");
1173        for agent in REFRESHABLE_HOOK_AGENTS {
1174            // `codex` resolves its dir via the global CODEX_HOME-aware resolver
1175            // (not the passed home), so it cannot be isolated to a temp dir here;
1176            // its detection is exercised by the marker-content test instead.
1177            if *agent == "codex" {
1178                continue;
1179            }
1180            assert!(
1181                !hooks_installed_for(agent, &tmp),
1182                "`{agent}` should not be detected as installed in an empty home"
1183            );
1184        }
1185        let _ = std::fs::remove_dir_all(&tmp);
1186    }
1187
1188    #[test]
1189    fn hooks_installed_for_detects_marker_content() {
1190        let tmp = unique_tmp_dir("leanctx_refresh_marker");
1191        let hooks = tmp.join(".codeium/windsurf/hooks.json");
1192        std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
1193
1194        // A foreign hooks.json must not trigger a refresh.
1195        std::fs::write(&hooks, "{\"hooks\":{}}").unwrap();
1196        assert!(!hooks_installed_for("windsurf", &tmp));
1197
1198        // Once it mentions lean-ctx, it is ours and must be refreshed.
1199        std::fs::write(&hooks, "{\"hooks\":{\"cmd\":\"lean-ctx hook rewrite\"}}").unwrap();
1200        assert!(hooks_installed_for("windsurf", &tmp));
1201
1202        let _ = std::fs::remove_dir_all(&tmp);
1203    }
1204
1205    fn unique_tmp_dir(prefix: &str) -> std::path::PathBuf {
1206        let nanos = std::time::SystemTime::now()
1207            .duration_since(std::time::UNIX_EPOCH)
1208            .map_or(0, |d| d.as_nanos());
1209        let dir = std::env::temp_dir().join(format!("{prefix}_{}_{nanos}", std::process::id()));
1210        std::fs::create_dir_all(&dir).unwrap();
1211        dir
1212    }
1213
1214    #[test]
1215    fn bash_path_unix_unchanged() {
1216        assert_eq!(
1217            to_bash_compatible_path("/usr/local/bin/lean-ctx"),
1218            "/usr/local/bin/lean-ctx"
1219        );
1220    }
1221
1222    #[test]
1223    fn bash_path_home_unchanged() {
1224        assert_eq!(
1225            to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
1226            "/home/user/.cargo/bin/lean-ctx"
1227        );
1228    }
1229
1230    #[test]
1231    fn bash_path_windows_drive_converted() {
1232        assert_eq!(
1233            to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
1234            "/c/Users/Fraser/bin/lean-ctx.exe"
1235        );
1236    }
1237
1238    #[test]
1239    fn bash_path_windows_lowercase_drive() {
1240        assert_eq!(
1241            to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
1242            "/d/tools/lean-ctx.exe"
1243        );
1244    }
1245
1246    #[test]
1247    fn bash_path_windows_forward_slashes() {
1248        assert_eq!(
1249            to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
1250            "/c/Users/Fraser/bin/lean-ctx.exe"
1251        );
1252    }
1253
1254    #[test]
1255    fn bash_path_bare_name_unchanged() {
1256        assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
1257    }
1258
1259    // MSYS2 drive mapping applies on Windows hosts only — on Linux/macOS
1260    // /c/… is a literal directory and must pass through (GH #397).
1261    #[cfg(windows)]
1262    #[test]
1263    fn normalize_msys2_path() {
1264        assert_eq!(
1265            normalize_tool_path("/c/Users/game/Downloads/project"),
1266            "C:/Users/game/Downloads/project"
1267        );
1268        assert_eq!(
1269            normalize_tool_path("/d/Projects/app/src"),
1270            "D:/Projects/app/src"
1271        );
1272    }
1273
1274    #[cfg(not(windows))]
1275    #[test]
1276    fn normalize_msys2_path_untouched_on_unix() {
1277        assert_eq!(
1278            crate::core::pathutil::normalize_tool_path_lexical("/c/Users/game/Downloads/project"),
1279            "/c/Users/game/Downloads/project"
1280        );
1281    }
1282
1283    #[test]
1284    fn normalize_backslashes() {
1285        assert_eq!(
1286            normalize_tool_path("C:\\Users\\game\\project\\src"),
1287            "C:/Users/game/project/src"
1288        );
1289    }
1290
1291    #[test]
1292    fn normalize_mixed_separators() {
1293        assert_eq!(
1294            normalize_tool_path("C:\\Users/game\\project/src"),
1295            "C:/Users/game/project/src"
1296        );
1297    }
1298
1299    #[test]
1300    fn normalize_double_slashes() {
1301        assert_eq!(
1302            normalize_tool_path("/home/user//project///src"),
1303            "/home/user/project/src"
1304        );
1305    }
1306
1307    #[test]
1308    fn normalize_trailing_slash() {
1309        assert_eq!(
1310            normalize_tool_path("/home/user/project/"),
1311            "/home/user/project"
1312        );
1313    }
1314
1315    #[test]
1316    fn normalize_root_preserved() {
1317        assert_eq!(normalize_tool_path("/"), "/");
1318    }
1319
1320    #[test]
1321    fn normalize_windows_root_preserved() {
1322        assert_eq!(normalize_tool_path("C:/"), "C:/");
1323    }
1324
1325    #[test]
1326    fn normalize_unix_path_unchanged() {
1327        assert_eq!(
1328            normalize_tool_path("/home/user/project/src/main.rs"),
1329            "/home/user/project/src/main.rs"
1330        );
1331    }
1332
1333    #[test]
1334    fn normalize_relative_path_unchanged() {
1335        assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
1336    }
1337
1338    #[test]
1339    fn normalize_dot_unchanged() {
1340        assert_eq!(normalize_tool_path("."), ".");
1341    }
1342
1343    #[test]
1344    fn normalize_unc_path_preserved() {
1345        assert_eq!(
1346            normalize_tool_path("//server/share/file"),
1347            "//server/share/file"
1348        );
1349    }
1350
1351    #[test]
1352    fn cursor_hook_config_has_version_and_object_hooks() {
1353        let config = serde_json::json!({
1354            "version": 1,
1355            "hooks": {
1356                "preToolUse": [
1357                    {
1358                        "matcher": "terminal_command",
1359                        "command": "lean-ctx hook rewrite"
1360                    },
1361                    {
1362                        "matcher": "read_file|grep|search|list_files|list_directory",
1363                        "command": "lean-ctx hook redirect"
1364                    }
1365                ]
1366            }
1367        });
1368
1369        let json_str = serde_json::to_string_pretty(&config).unwrap();
1370        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1371
1372        assert_eq!(parsed["version"], 1);
1373        assert!(parsed["hooks"].is_object());
1374        assert!(parsed["hooks"]["preToolUse"].is_array());
1375        assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
1376        assert_eq!(
1377            parsed["hooks"]["preToolUse"][0]["matcher"],
1378            "terminal_command"
1379        );
1380    }
1381
1382    #[test]
1383    fn cursor_hook_detects_old_format_needs_migration() {
1384        let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
1385        let has_correct =
1386            old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
1387        assert!(
1388            !has_correct,
1389            "Old format should be detected as needing migration"
1390        );
1391    }
1392
1393    #[test]
1394    fn gemini_hook_config_has_type_command() {
1395        let binary = "lean-ctx";
1396        let rewrite_cmd = format!("{binary} hook rewrite");
1397        let redirect_cmd = format!("{binary} hook redirect");
1398
1399        let hook_config = serde_json::json!({
1400            "hooks": {
1401                "BeforeTool": [
1402                    {
1403                        "hooks": [{
1404                            "type": "command",
1405                            "command": rewrite_cmd
1406                        }]
1407                    },
1408                    {
1409                        "hooks": [{
1410                            "type": "command",
1411                            "command": redirect_cmd
1412                        }]
1413                    }
1414                ]
1415            }
1416        });
1417
1418        let parsed = hook_config;
1419        let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
1420        assert_eq!(before_tool.len(), 2);
1421
1422        let first_hook = &before_tool[0]["hooks"][0];
1423        assert_eq!(first_hook["type"], "command");
1424        assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
1425
1426        let second_hook = &before_tool[1]["hooks"][0];
1427        assert_eq!(second_hook["type"], "command");
1428        assert_eq!(second_hook["command"], "lean-ctx hook redirect");
1429    }
1430
1431    #[test]
1432    fn gemini_hook_old_format_detected() {
1433        let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
1434        let has_new = old_format.contains("hook rewrite")
1435            && old_format.contains("hook redirect")
1436            && old_format.contains("\"type\"");
1437        assert!(!has_new, "Missing 'type' field should trigger migration");
1438    }
1439
1440    #[test]
1441    fn rewrite_script_uses_registry_pattern() {
1442        let script = generate_rewrite_script("/usr/bin/lean-ctx");
1443        assert!(script.contains(r"git\ *"), "script missing git pattern");
1444        assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
1445        assert!(script.contains(r"npm\ *"), "script missing npm pattern");
1446        assert!(script.contains(r"rg\ *"), "script missing rg pattern");
1447        assert!(script.contains(r"ls\ *"), "script missing ls pattern");
1448        assert!(
1449            script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
1450            "script missing binary path"
1451        );
1452        assert!(
1453            script.contains("PowerShell|powershell"),
1454            "rewrite script must accept PowerShell tool names for Windows compatibility"
1455        );
1456    }
1457
1458    #[test]
1459    fn compact_rewrite_script_uses_registry_pattern() {
1460        let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
1461        assert!(script.contains(r"git\ *"), "compact script missing git");
1462        assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
1463        assert!(script.contains(r"rg\ *"), "compact script missing rg");
1464    }
1465
1466    #[test]
1467    fn rewrite_scripts_contain_all_registry_commands() {
1468        let script = generate_rewrite_script("lean-ctx");
1469        let compact = generate_compact_rewrite_script("lean-ctx");
1470        for entry in crate::rewrite_registry::REWRITE_COMMANDS {
1471            if matches!(entry.category, crate::rewrite_registry::Category::FileRead) {
1472                continue;
1473            }
1474            let pattern = if entry.command.contains('-') {
1475                format!("{}*", entry.command.replace('-', r"\-"))
1476            } else {
1477                format!(r"{}\ *", entry.command)
1478            };
1479            assert!(
1480                script.contains(&pattern),
1481                "rewrite_script missing '{}' (pattern: {})",
1482                entry.command,
1483                pattern
1484            );
1485            assert!(
1486                compact.contains(&pattern),
1487                "compact_rewrite_script missing '{}' (pattern: {})",
1488                entry.command,
1489                pattern
1490            );
1491        }
1492    }
1493
1494    #[test]
1495    fn codex_is_hybrid() {
1496        assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
1497    }
1498
1499    #[test]
1500    fn cursor_is_hybrid() {
1501        assert_eq!(recommend_hook_mode("cursor"), HookMode::Hybrid);
1502    }
1503
1504    #[test]
1505    fn gemini_is_hybrid() {
1506        assert_eq!(recommend_hook_mode("gemini"), HookMode::Hybrid);
1507    }
1508
1509    #[test]
1510    fn claude_is_hybrid() {
1511        assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
1512    }
1513
1514    #[test]
1515    fn unknown_agent_falls_back_to_mcp() {
1516        assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
1517    }
1518
1519    // Drive translation only applies on Windows hosts (GH #397).
1520    #[cfg(windows)]
1521    #[test]
1522    fn from_bash_to_native_converts_msys_drive() {
1523        assert_eq!(
1524            from_bash_to_native_path("/c/Users/ABC/lean-ctx"),
1525            "C:/Users/ABC/lean-ctx"
1526        );
1527        assert_eq!(
1528            from_bash_to_native_path("/d/Program Files/lean-ctx.exe"),
1529            "D:/Program Files/lean-ctx.exe"
1530        );
1531    }
1532
1533    #[test]
1534    fn from_bash_to_native_unix_path_unchanged() {
1535        assert_eq!(
1536            from_bash_to_native_path("/usr/local/bin/lean-ctx"),
1537            "/usr/local/bin/lean-ctx"
1538        );
1539    }
1540
1541    #[test]
1542    fn from_bash_to_native_bare_name() {
1543        assert_eq!(from_bash_to_native_path("lean-ctx"), "lean-ctx");
1544    }
1545
1546    #[test]
1547    fn windows_path_to_bash_form() {
1548        let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1549        let bash = to_bash_compatible_path(native);
1550        assert_eq!(bash, "/c/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1551    }
1552
1553    // The bash→native return leg only translates on Windows hosts (GH #397).
1554    #[cfg(windows)]
1555    #[test]
1556    fn roundtrip_windows_path() {
1557        let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1558        let bash = to_bash_compatible_path(native);
1559        let back = from_bash_to_native_path(&bash);
1560        assert_eq!(back, "C:/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1561    }
1562
1563    #[test]
1564    fn roundtrip_unix_path() {
1565        let native = "/usr/local/bin/lean-ctx";
1566        let bash = to_bash_compatible_path(native);
1567        assert_eq!(bash, native);
1568        let back = from_bash_to_native_path(&bash);
1569        assert_eq!(back, native);
1570    }
1571}