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 = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
492const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
493const PROJECT_AGENTS_MD: &str = "AGENTS.md";
494// The AGENTS.md pointer block keeps its own marker pair, independent of the
495// dedicated rules-file `START_MARK`: pointer-only files must not be counted as
496// duplicate lean-ctx sources (doctor overhead, #684).
497const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
498const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
499
500fn ensure_project_agents_integration(cwd: &std::path::Path) {
501    let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
502    let desired = format!(
503        "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
504        crate::rules_inject::rules_dedicated_markdown()
505    );
506
507    if !lean_ctx_md.exists() {
508        write_file(&lean_ctx_md, &desired);
509    } else if std::fs::read_to_string(&lean_ctx_md)
510        .unwrap_or_default()
511        .contains(PROJECT_LEAN_CTX_MD_MARKER)
512    {
513        let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
514        let version_str = format!(
515            "<!-- version: {} -->",
516            crate::core::rules_canonical::RULES_VERSION
517        );
518        if !current.contains(&version_str) {
519            write_file(&lean_ctx_md, &desired);
520        }
521    }
522
523    // No `@` import: Claude Code expands `@file` references inline at session
524    // start, so pointing at LEAN-CTX.md re-loaded the full ruleset into every
525    // session on top of this block (GL #555). The block is self-contained;
526    // the full ruleset stays in LEAN-CTX.md for on-demand reading.
527    let block = format!(
528        "{AGENTS_BLOCK_START}\n\
529## lean-ctx\n\n\
530lean-ctx is active — the MCP tools replace native equivalents.\n\
531Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
532{AGENTS_BLOCK_END}\n"
533    );
534
535    let agents_md = cwd.join(PROJECT_AGENTS_MD);
536    if !agents_md.exists() {
537        let content = format!("# Agent Instructions\n\n{block}");
538        write_file(&agents_md, &content);
539        if !mcp_server_quiet_mode() {
540            eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
541        }
542        return;
543    }
544
545    let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
546
547    if existing.contains("CLI-first Token Optimization for Pi")
548        && !existing.contains(AGENTS_BLOCK_START)
549    {
550        let content = format!("# Agent Instructions\n\n{block}");
551        write_file(&agents_md, &content);
552        return;
553    }
554
555    if existing.contains(AGENTS_BLOCK_START) {
556        let updated = crate::marked_block::replace_marked_block(
557            &existing,
558            AGENTS_BLOCK_START,
559            AGENTS_BLOCK_END,
560            &block,
561        );
562        if updated != existing {
563            write_file(&agents_md, &updated);
564        }
565        return;
566    }
567
568    if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
569        return;
570    }
571
572    let mut out = existing;
573    if !out.ends_with('\n') {
574        out.push('\n');
575    }
576    out.push('\n');
577    out.push_str(&block);
578    write_file(&agents_md, &out);
579    if !mcp_server_quiet_mode() {
580        eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
581    }
582}
583
584/// #555: VS Code Copilot Chat auto-applies `.github/copilot-instructions.md` to
585/// every request, but `init --agent copilot` previously wrote only a weak
586/// AGENTS.md pointer — Claude-family models then ignored the lean-ctx tool
587/// mapping while GPT-5.x mostly followed it. Write the strong dedicated ruleset
588/// into a `<!-- lean-ctx-rules -->` marked block so it merges idempotently and
589/// never clobbers the user's own instructions.
590fn ensure_copilot_instructions(cwd: &std::path::Path) {
591    let path = cwd.join(".github").join("copilot-instructions.md");
592    let block = crate::rules_inject::rules_dedicated_markdown();
593    let start = crate::core::rules_canonical::START_MARK;
594    let end = crate::core::rules_canonical::END_MARK;
595    let owned = format!("{}\n", block.trim_end());
596
597    let existing = std::fs::read_to_string(&path).unwrap_or_default();
598    let desired = if existing.trim().is_empty() {
599        owned
600    } else if existing.contains(start) {
601        // Refresh our block; keep any surrounding user-authored content.
602        let user = crate::marked_block::remove_content(&existing, start, end);
603        if user.trim().is_empty() {
604            owned
605        } else {
606            format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
607        }
608    } else {
609        // User-authored file with no lean-ctx block yet: append ours once.
610        format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
611    };
612
613    if desired == existing {
614        return;
615    }
616    if let Some(parent) = path.parent()
617        && std::fs::create_dir_all(parent).is_err()
618    {
619        return;
620    }
621    write_file(&path, &desired);
622    if !mcp_server_quiet_mode() {
623        eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
624    }
625}
626
627/// #555 safety net: VS Code applies instruction files when
628/// `github.copilot.chat.codeGeneration.useInstructionFiles` is on (the default).
629/// A user or org policy may have disabled it globally, so pin it on for this
630/// project. Set only when the key is absent — an explicit user value is honoured.
631fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
632    const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
633    let path = cwd.join(".vscode").join("settings.json");
634
635    let existing = std::fs::read_to_string(&path).unwrap_or_default();
636    let mut json = if existing.trim().is_empty() {
637        serde_json::json!({})
638    } else {
639        match crate::core::jsonc::parse_jsonc(&existing) {
640            Ok(v) if v.is_object() => v,
641            // Never clobber an unparseable or non-object settings file.
642            _ => return,
643        }
644    };
645    let Some(obj) = json.as_object_mut() else {
646        return;
647    };
648    if obj.contains_key(KEY) {
649        return;
650    }
651    obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
652
653    if let Some(parent) = path.parent()
654        && std::fs::create_dir_all(parent).is_err()
655    {
656        return;
657    }
658    let Ok(formatted) = serde_json::to_string_pretty(&json) else {
659        return;
660    };
661    if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
662        && !mcp_server_quiet_mode()
663    {
664        eprintln!("Set {KEY} in .vscode/settings.json.");
665    }
666}
667
668/// Compact pointer only (#578): Cursor already auto-loads the canonical full
669/// ruleset from `~/.cursor/rules/lean-ctx.mdc`, so a project `.cursorrules`
670/// that repeats it bills the same guidance twice in every session.
671pub fn cursorrules_content() -> String {
672    let start = crate::core::rules_canonical::START_MARK;
673    let end = crate::core::rules_canonical::END_MARK;
674    let version = crate::core::rules_canonical::RULES_VERSION;
675    format!(
676        "{start}\n<!-- version: {version} -->\n\n\
677# lean-ctx\n\n\
678{bullets}\n\n\
679{never}\n\
680Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
681{end}",
682        bullets = crate::core::rules_canonical::BULLETS,
683        never = crate::core::rules_canonical::NEVER,
684    )
685}
686
687pub fn kiro_steering_content() -> String {
688    use crate::core::rules_canonical;
689    format!(
690        "---\n\
691inclusion: always\n\
692---\n\n\
693# Context Engineering Layer\n\n\
694{start}\n\
695<!-- version: {version} -->\n\n\
696The workspace has the `lean-ctx` MCP server installed. \
697You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
698{bullets}\n\n\
699{never}\n\n\
700## When to use native Kiro tools instead\n\n\
701- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
702- `strReplace` \u{2014} always use native (precise string replacement)\n\
703- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
704- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
705- `deleteFile` \u{2014} always use native\n\
706- Glob \u{2014} always use native glob\n\n\
707{end}",
708        start = rules_canonical::START_MARK,
709        version = rules_canonical::RULES_VERSION,
710        bullets = rules_canonical::BULLETS,
711        never = rules_canonical::NEVER,
712        end = rules_canonical::END_MARK,
713    )
714}
715/// #281: whether the hooks layer may register the lean-ctx MCP server in an
716/// agent's config. Honors `[setup] auto_update_mcp`. Hooks, rules and skills
717/// still install when this is `false` — only the MCP-server writes are gated, so
718/// MCP-disabled environments stay free of MCP entries. Centralised here so every
719/// per-agent writer shares one source of truth (the shared JSON writer in
720/// `support.rs` enforces the same gate for `mcpServers`-style agents).
721pub(crate) fn should_register_mcp() -> bool {
722    crate::core::config::Config::load()
723        .setup
724        .should_update_mcp()
725}
726
727pub fn install_agent_hook(agent: &str, global: bool) {
728    install_agent_hook_with_mode(agent, global, HookMode::Mcp);
729}
730
731pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
732    let home = crate::core::home::resolve_home_dir().unwrap_or_default();
733    match agent {
734        "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
735        "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
736        "cursor" => install_cursor_hook_with_mode(global, mode),
737        "gemini" => {
738            install_gemini_hook();
739            // Google is transitioning Gemini CLI → Antigravity CLI (`agy`), and
740            // `gemini` setup also configures the Antigravity CLI MCP target. The
741            // hooks must follow: `agy` reads hooks only from its plugin dir
742            // (`~/.gemini/config/plugins/lean-ctx`), never from the legacy
743            // `~/.gemini/settings.json`, so install the plugin too (#284).
744            install_antigravity_cli_hook();
745        }
746        "antigravity" => install_antigravity_hook(),
747        "antigravity-cli" => install_antigravity_cli_hook(),
748        "augment" => install_mcp_json_agent(
749            "Augment CLI",
750            "~/.augment/settings.json",
751            &crate::core::editor_registry::augment_cli_settings_path(&home),
752        ),
753        "codex" => install_codex_hook(),
754        "windsurf" => install_windsurf_rules(global),
755        "cline" | "roo" => install_cline_rules(global),
756        "copilot" | "vscode" => install_copilot_hook(global),
757        "pi" => install_pi_hook_with_mode(global, mode),
758        "qoder" => install_qoder_hook_with_mode(mode),
759        "qoderwork" => install_mcp_json_agent(
760            "QoderWork",
761            "~/.qoderwork/mcp.json",
762            &home.join(".qoderwork/mcp.json"),
763        ),
764        "qwen" => install_mcp_json_agent(
765            "Qwen Code",
766            "~/.qwen/settings.json",
767            &home.join(".qwen/settings.json"),
768        ),
769        "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
770        "amazonq" => install_mcp_json_agent(
771            "Amazon Q Developer",
772            "~/.aws/amazonq/default.json",
773            &home.join(".aws/amazonq/default.json"),
774        ),
775        "jetbrains" => install_jetbrains_hook(),
776        "kiro" => install_kiro_hook(),
777        "verdent" => install_mcp_json_agent(
778            "Verdent",
779            "~/.verdent/mcp.json",
780            &home.join(".verdent/mcp.json"),
781        ),
782        "opencode" => install_opencode_hook_with_mode(mode),
783        "amp" => install_amp_hook(),
784        "crush" => install_crush_hook_with_mode(mode),
785        "openclaw" => install_openclaw_hook(),
786        "hermes" => install_hermes_hook_with_mode(global, mode),
787        "zed" => {
788            let zed_path = crate::core::editor_registry::zed_settings_path(&home);
789            let binary = resolve_binary_path();
790            let entry = full_server_entry(&binary);
791            install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
792        }
793        "aider" => {
794            install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
795        }
796        "continue" => install_mcp_json_agent(
797            "Continue",
798            "~/.continue/mcp.json",
799            &home.join(".continue/mcp.json"),
800        ),
801        "neovim" => install_mcp_json_agent(
802            "Neovim (mcphub.nvim)",
803            "~/.config/mcphub/servers.json",
804            &home.join(".config/mcphub/servers.json"),
805        ),
806        "emacs" => install_mcp_json_agent(
807            "Emacs (mcp.el)",
808            "~/.emacs.d/mcp.json",
809            &home.join(".emacs.d/mcp.json"),
810        ),
811        "sublime" => install_mcp_json_agent(
812            "Sublime Text",
813            "~/.config/sublime-text/mcp.json",
814            &home.join(".config/sublime-text/mcp.json"),
815        ),
816        _ => {
817            eprintln!("Unknown agent: {agent}");
818            eprintln!("  Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
819            eprintln!(
820                "    claude, cline, codebuddy, codex, continue, copilot, crush, cursor, emacs, gemini,"
821            );
822            eprintln!("    hermes, jetbrains, kiro, neovim, openclaw, opencode, pi, qoder,");
823            eprintln!("    qoderwork, qwen, roo, sublime, trae, verdent, vscode, windsurf, zed");
824            std::process::exit(1);
825        }
826    }
827}
828
829pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
830    match agent {
831        "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
832        "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
833        _ => {}
834    }
835}
836
837fn write_file(path: &std::path::Path, content: &str) {
838    // Skip identical rewrites: re-running setup/init must not churn mtimes or
839    // leave .bak files behind for content that did not change (GL #558).
840    if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
841        return;
842    }
843    if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
844        tracing::error!("Error writing {}: {e}", path.display());
845    }
846}
847
848fn is_inside_git_repo(path: &std::path::Path) -> bool {
849    let mut p = path;
850    loop {
851        if p.join(".git").exists() {
852            return true;
853        }
854        match p.parent() {
855            Some(parent) => p = parent,
856            None => return false,
857        }
858    }
859}
860
861#[cfg(unix)]
862fn make_executable(path: &PathBuf) {
863    use std::os::unix::fs::PermissionsExt;
864    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
865}
866
867#[cfg(not(unix))]
868fn make_executable(_path: &PathBuf) {}
869
870/// Env key/value pairs for the lean-ctx MCP server entry written into agent
871/// configs (Codex TOML + the JSON agents).
872///
873/// Deliberately does NOT pin `LEAN_CTX_DATA_DIR`: lean-ctx auto-detects its
874/// per-category dirs (config/data/state/cache) at runtime, and pinning the data
875/// dir would set that var in the server's environment, forcing single-dir mode
876/// and collapsing config/state/cache onto the data dir — defeating the XDG split
877/// (GH #408). Emits `LEAN_CTX_PROJECT_ROOT` and `LEAN_CTX_EXTRA_ROOTS` when known
878/// (process env first, then config). Without these, a long-lived MCP server
879/// spawned by the agent loses the project / worktree scope captured at `init`,
880/// so an explicit path under a sibling worktree is wrongly rejected as a jail
881/// escape (#403). Single source of truth so every agent installer stays consistent.
882pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
883    let mut pairs = Vec::new();
884
885    let cfg = crate::core::config::Config::load();
886
887    let project_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
888        .ok()
889        .filter(|v| !v.trim().is_empty())
890        .or_else(|| cfg.project_root.clone().filter(|v| !v.trim().is_empty()));
891    if let Some(root) = project_root {
892        pairs.push(("LEAN_CTX_PROJECT_ROOT".to_string(), root));
893    }
894
895    // Env override is already a platform path-list; config is a Vec we join the
896    // same way `LEAN_CTX_EXTRA_ROOTS` is parsed (`std::env::split_paths`).
897    let extra_roots = std::env::var("LEAN_CTX_EXTRA_ROOTS")
898        .ok()
899        .filter(|v| !v.trim().is_empty())
900        .or_else(|| {
901            let roots: Vec<&str> = cfg
902                .extra_roots
903                .iter()
904                .map(String::as_str)
905                .filter(|s| !s.trim().is_empty())
906                .collect();
907            if roots.is_empty() {
908                return None;
909            }
910            std::env::join_paths(roots)
911                .ok()
912                .map(|s| s.to_string_lossy().to_string())
913        });
914    if let Some(extra) = extra_roots {
915        pairs.push(("LEAN_CTX_EXTRA_ROOTS".to_string(), extra));
916    }
917
918    pairs
919}
920
921/// The MCP server env block as a JSON object, for the JSON-config agents.
922pub(crate) fn mcp_server_env_json() -> serde_json::Value {
923    let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
924        .into_iter()
925        .map(|(k, v)| (k, serde_json::Value::String(v)))
926        .collect();
927    serde_json::Value::Object(map)
928}
929
930fn full_server_entry(binary: &str) -> serde_json::Value {
931    // No LEAN_CTX_FULL_TOOLS here: forcing the full toolset (69+ schemas,
932    // ~15k tokens of tool definitions resent every turn) made lean-ctx one of
933    // the biggest token consumers in users' sessions (GitHub #385). The server
934    // defaults to the core toolset + ctx_call/ctx_expand for on-demand access;
935    // power users opt in via `tool_profile = "power"` in config.toml.
936    serde_json::json!({
937        "command": binary,
938        "env": mcp_server_env_json()
939    })
940}
941
942pub(crate) fn install_mcp_json_agent(
943    name: &str,
944    display_path: &str,
945    config_path: &std::path::Path,
946) {
947    let binary = resolve_binary_path();
948    let entry = full_server_entry(&binary);
949    install_named_json_server(name, display_path, config_path, "mcpServers", entry);
950}
951
952#[cfg(test)]
953mod tests {
954    use super::*;
955
956    #[test]
957    fn refresh_covers_every_hybrid_agent() {
958        // Every Hybrid agent must be in exactly one of the two sets, so a newly
959        // added agent can never silently skip the post-update hook refresh.
960        for agent in HYBRID_AGENTS {
961            let refreshed = REFRESHABLE_HOOK_AGENTS.contains(agent);
962            let exempt = REFRESH_EXEMPT_HYBRID_AGENTS.contains(agent);
963            assert!(
964                refreshed ^ exempt,
965                "hybrid agent `{agent}` must be either refreshed or explicitly exempt (exactly one)"
966            );
967        }
968    }
969
970    #[test]
971    fn refresh_sets_reference_only_hybrid_agents() {
972        for agent in REFRESHABLE_HOOK_AGENTS {
973            assert!(
974                HYBRID_AGENTS.contains(agent),
975                "refreshable agent `{agent}` is not a Hybrid agent"
976            );
977        }
978        for agent in REFRESH_EXEMPT_HYBRID_AGENTS {
979            assert!(
980                HYBRID_AGENTS.contains(agent),
981                "exempt agent `{agent}` is not a Hybrid agent (stale exemption?)"
982            );
983        }
984    }
985
986    // ── #555: .github/copilot-instructions.md ──────────────────────────────
987
988    #[test]
989    fn copilot_instructions_created_with_lean_ctx_block() {
990        let _iso = crate::core::data_dir::isolated_data_dir();
991        let tmp = tempfile::tempdir().unwrap();
992        ensure_copilot_instructions(tmp.path());
993
994        let path = tmp.path().join(".github/copilot-instructions.md");
995        let content = std::fs::read_to_string(&path).expect("copilot-instructions.md created");
996        assert!(content.contains(crate::core::rules_canonical::START_MARK));
997        assert!(content.contains(crate::core::rules_canonical::END_MARK));
998        assert!(content.contains("lean-ctx"));
999    }
1000
1001    #[test]
1002    fn copilot_instructions_idempotent() {
1003        let _iso = crate::core::data_dir::isolated_data_dir();
1004        let tmp = tempfile::tempdir().unwrap();
1005        let path = tmp.path().join(".github/copilot-instructions.md");
1006
1007        ensure_copilot_instructions(tmp.path());
1008        let first = std::fs::read_to_string(&path).unwrap();
1009        ensure_copilot_instructions(tmp.path());
1010        let second = std::fs::read_to_string(&path).unwrap();
1011
1012        assert_eq!(first, second, "re-running must produce identical bytes");
1013        assert_eq!(
1014            first
1015                .matches(crate::core::rules_canonical::START_MARK)
1016                .count(),
1017            1,
1018            "exactly one lean-ctx block, no duplication"
1019        );
1020    }
1021
1022    #[test]
1023    fn copilot_instructions_preserve_user_content() {
1024        let _iso = crate::core::data_dir::isolated_data_dir();
1025        let tmp = tempfile::tempdir().unwrap();
1026        let path = tmp.path().join(".github/copilot-instructions.md");
1027        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1028        std::fs::write(&path, "# House rules\n\nAlways write tests.\n").unwrap();
1029
1030        ensure_copilot_instructions(tmp.path());
1031        let content = std::fs::read_to_string(&path).unwrap();
1032        assert!(content.contains("# House rules"));
1033        assert!(content.contains("Always write tests."));
1034        assert!(content.contains(crate::core::rules_canonical::START_MARK));
1035
1036        // Idempotent on a user-authored file as well.
1037        ensure_copilot_instructions(tmp.path());
1038        let again = std::fs::read_to_string(&path).unwrap();
1039        assert_eq!(content, again);
1040        assert_eq!(
1041            again
1042                .matches(crate::core::rules_canonical::START_MARK)
1043                .count(),
1044            1
1045        );
1046    }
1047
1048    #[test]
1049    fn copilot_instructions_block_is_removable() {
1050        // Mirrors the uninstall path: the marked block must be strippable while
1051        // user content survives.
1052        let _iso = crate::core::data_dir::isolated_data_dir();
1053        let tmp = tempfile::tempdir().unwrap();
1054        let path = tmp.path().join(".github/copilot-instructions.md");
1055        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1056        std::fs::write(&path, "# House rules\n\nKeep it tidy.\n").unwrap();
1057        ensure_copilot_instructions(tmp.path());
1058
1059        let content = std::fs::read_to_string(&path).unwrap();
1060        let cleaned = crate::marked_block::remove_content(
1061            &content,
1062            crate::core::rules_canonical::START_MARK,
1063            crate::core::rules_canonical::END_MARK,
1064        );
1065        assert!(!cleaned.contains(crate::core::rules_canonical::START_MARK));
1066        assert!(cleaned.contains("# House rules"));
1067    }
1068
1069    #[test]
1070    fn vscode_instruction_setting_set_when_absent_and_preserves() {
1071        let tmp = tempfile::tempdir().unwrap();
1072        let vscode = tmp.path().join(".vscode");
1073        std::fs::create_dir_all(&vscode).unwrap();
1074        let settings = vscode.join("settings.json");
1075        std::fs::write(&settings, "{\n  \"editor.fontSize\": 13\n}\n").unwrap();
1076
1077        ensure_vscode_instruction_files_setting(tmp.path());
1078        let v: serde_json::Value =
1079            serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
1080        assert_eq!(v["editor.fontSize"], 13);
1081        assert_eq!(
1082            v["github.copilot.chat.codeGeneration.useInstructionFiles"],
1083            true
1084        );
1085    }
1086
1087    #[test]
1088    fn vscode_instruction_setting_respects_explicit_user_value() {
1089        let tmp = tempfile::tempdir().unwrap();
1090        let vscode = tmp.path().join(".vscode");
1091        std::fs::create_dir_all(&vscode).unwrap();
1092        let settings = vscode.join("settings.json");
1093        std::fs::write(
1094            &settings,
1095            "{\n  \"github.copilot.chat.codeGeneration.useInstructionFiles\": false\n}\n",
1096        )
1097        .unwrap();
1098
1099        ensure_vscode_instruction_files_setting(tmp.path());
1100        let v: serde_json::Value =
1101            serde_json::from_str(&std::fs::read_to_string(&settings).unwrap()).unwrap();
1102        assert_eq!(
1103            v["github.copilot.chat.codeGeneration.useInstructionFiles"], false,
1104            "an explicit user value must not be overridden"
1105        );
1106    }
1107
1108    #[test]
1109    fn mcp_env_pairs_propagate_project_and_extra_roots_from_env() {
1110        // #403: init must bake the captured project/worktree scope into the MCP
1111        // server entry, otherwise the long-lived server rejects explicit paths
1112        // under sibling worktrees as jail escapes.
1113        let _iso = crate::core::data_dir::isolated_data_dir();
1114        crate::test_env::set_var("LEAN_CTX_PROJECT_ROOT", "/work/main");
1115        crate::test_env::set_var("LEAN_CTX_EXTRA_ROOTS", "/work/wt-a:/work/wt-b");
1116
1117        let pairs = mcp_server_env_pairs();
1118        let get = |k: &str| pairs.iter().find(|(p, _)| p == k).map(|(_, v)| v.as_str());
1119        assert!(
1120            get("LEAN_CTX_DATA_DIR").is_none(),
1121            "data dir is auto-detected at runtime, never pinned into the config (GH #408)"
1122        );
1123        assert_eq!(get("LEAN_CTX_PROJECT_ROOT"), Some("/work/main"));
1124        assert_eq!(get("LEAN_CTX_EXTRA_ROOTS"), Some("/work/wt-a:/work/wt-b"));
1125
1126        // The JSON view mirrors the pairs for the JSON-config agents.
1127        let json = mcp_server_env_json();
1128        assert_eq!(json["LEAN_CTX_PROJECT_ROOT"].as_str(), Some("/work/main"));
1129
1130        crate::test_env::remove_var("LEAN_CTX_PROJECT_ROOT");
1131        crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1132    }
1133
1134    #[test]
1135    fn mcp_env_pairs_omit_roots_when_unset() {
1136        // No project context configured anywhere ⇒ no env vars are emitted: the
1137        // data dir is auto-detected (never pinned, GH #408) and we never write
1138        // empty/placeholder root keys into agent configs.
1139        let _iso = crate::core::data_dir::isolated_data_dir();
1140        crate::test_env::remove_var("LEAN_CTX_PROJECT_ROOT");
1141        crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
1142
1143        let pairs = mcp_server_env_pairs();
1144        let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect();
1145        assert!(!keys.contains(&"LEAN_CTX_DATA_DIR"));
1146        assert!(!keys.contains(&"LEAN_CTX_PROJECT_ROOT"));
1147        assert!(!keys.contains(&"LEAN_CTX_EXTRA_ROOTS"));
1148    }
1149
1150    #[test]
1151    fn hooks_installed_for_is_false_without_artifacts() {
1152        let tmp = unique_tmp_dir("leanctx_refresh_empty");
1153        for agent in REFRESHABLE_HOOK_AGENTS {
1154            // `codex` resolves its dir via the global CODEX_HOME-aware resolver
1155            // (not the passed home), so it cannot be isolated to a temp dir here;
1156            // its detection is exercised by the marker-content test instead.
1157            if *agent == "codex" {
1158                continue;
1159            }
1160            assert!(
1161                !hooks_installed_for(agent, &tmp),
1162                "`{agent}` should not be detected as installed in an empty home"
1163            );
1164        }
1165        let _ = std::fs::remove_dir_all(&tmp);
1166    }
1167
1168    #[test]
1169    fn hooks_installed_for_detects_marker_content() {
1170        let tmp = unique_tmp_dir("leanctx_refresh_marker");
1171        let hooks = tmp.join(".codeium/windsurf/hooks.json");
1172        std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
1173
1174        // A foreign hooks.json must not trigger a refresh.
1175        std::fs::write(&hooks, "{\"hooks\":{}}").unwrap();
1176        assert!(!hooks_installed_for("windsurf", &tmp));
1177
1178        // Once it mentions lean-ctx, it is ours and must be refreshed.
1179        std::fs::write(&hooks, "{\"hooks\":{\"cmd\":\"lean-ctx hook rewrite\"}}").unwrap();
1180        assert!(hooks_installed_for("windsurf", &tmp));
1181
1182        let _ = std::fs::remove_dir_all(&tmp);
1183    }
1184
1185    fn unique_tmp_dir(prefix: &str) -> std::path::PathBuf {
1186        let nanos = std::time::SystemTime::now()
1187            .duration_since(std::time::UNIX_EPOCH)
1188            .map_or(0, |d| d.as_nanos());
1189        let dir = std::env::temp_dir().join(format!("{prefix}_{}_{nanos}", std::process::id()));
1190        std::fs::create_dir_all(&dir).unwrap();
1191        dir
1192    }
1193
1194    #[test]
1195    fn bash_path_unix_unchanged() {
1196        assert_eq!(
1197            to_bash_compatible_path("/usr/local/bin/lean-ctx"),
1198            "/usr/local/bin/lean-ctx"
1199        );
1200    }
1201
1202    #[test]
1203    fn bash_path_home_unchanged() {
1204        assert_eq!(
1205            to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
1206            "/home/user/.cargo/bin/lean-ctx"
1207        );
1208    }
1209
1210    #[test]
1211    fn bash_path_windows_drive_converted() {
1212        assert_eq!(
1213            to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
1214            "/c/Users/Fraser/bin/lean-ctx.exe"
1215        );
1216    }
1217
1218    #[test]
1219    fn bash_path_windows_lowercase_drive() {
1220        assert_eq!(
1221            to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
1222            "/d/tools/lean-ctx.exe"
1223        );
1224    }
1225
1226    #[test]
1227    fn bash_path_windows_forward_slashes() {
1228        assert_eq!(
1229            to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
1230            "/c/Users/Fraser/bin/lean-ctx.exe"
1231        );
1232    }
1233
1234    #[test]
1235    fn bash_path_bare_name_unchanged() {
1236        assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
1237    }
1238
1239    // MSYS2 drive mapping applies on Windows hosts only — on Linux/macOS
1240    // /c/… is a literal directory and must pass through (GH #397).
1241    #[cfg(windows)]
1242    #[test]
1243    fn normalize_msys2_path() {
1244        assert_eq!(
1245            normalize_tool_path("/c/Users/game/Downloads/project"),
1246            "C:/Users/game/Downloads/project"
1247        );
1248        assert_eq!(
1249            normalize_tool_path("/d/Projects/app/src"),
1250            "D:/Projects/app/src"
1251        );
1252    }
1253
1254    #[cfg(not(windows))]
1255    #[test]
1256    fn normalize_msys2_path_untouched_on_unix() {
1257        assert_eq!(
1258            crate::core::pathutil::normalize_tool_path_lexical("/c/Users/game/Downloads/project"),
1259            "/c/Users/game/Downloads/project"
1260        );
1261    }
1262
1263    #[test]
1264    fn normalize_backslashes() {
1265        assert_eq!(
1266            normalize_tool_path("C:\\Users\\game\\project\\src"),
1267            "C:/Users/game/project/src"
1268        );
1269    }
1270
1271    #[test]
1272    fn normalize_mixed_separators() {
1273        assert_eq!(
1274            normalize_tool_path("C:\\Users/game\\project/src"),
1275            "C:/Users/game/project/src"
1276        );
1277    }
1278
1279    #[test]
1280    fn normalize_double_slashes() {
1281        assert_eq!(
1282            normalize_tool_path("/home/user//project///src"),
1283            "/home/user/project/src"
1284        );
1285    }
1286
1287    #[test]
1288    fn normalize_trailing_slash() {
1289        assert_eq!(
1290            normalize_tool_path("/home/user/project/"),
1291            "/home/user/project"
1292        );
1293    }
1294
1295    #[test]
1296    fn normalize_root_preserved() {
1297        assert_eq!(normalize_tool_path("/"), "/");
1298    }
1299
1300    #[test]
1301    fn normalize_windows_root_preserved() {
1302        assert_eq!(normalize_tool_path("C:/"), "C:/");
1303    }
1304
1305    #[test]
1306    fn normalize_unix_path_unchanged() {
1307        assert_eq!(
1308            normalize_tool_path("/home/user/project/src/main.rs"),
1309            "/home/user/project/src/main.rs"
1310        );
1311    }
1312
1313    #[test]
1314    fn normalize_relative_path_unchanged() {
1315        assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
1316    }
1317
1318    #[test]
1319    fn normalize_dot_unchanged() {
1320        assert_eq!(normalize_tool_path("."), ".");
1321    }
1322
1323    #[test]
1324    fn normalize_unc_path_preserved() {
1325        assert_eq!(
1326            normalize_tool_path("//server/share/file"),
1327            "//server/share/file"
1328        );
1329    }
1330
1331    #[test]
1332    fn cursor_hook_config_has_version_and_object_hooks() {
1333        let config = serde_json::json!({
1334            "version": 1,
1335            "hooks": {
1336                "preToolUse": [
1337                    {
1338                        "matcher": "terminal_command",
1339                        "command": "lean-ctx hook rewrite"
1340                    },
1341                    {
1342                        "matcher": "read_file|grep|search|list_files|list_directory",
1343                        "command": "lean-ctx hook redirect"
1344                    }
1345                ]
1346            }
1347        });
1348
1349        let json_str = serde_json::to_string_pretty(&config).unwrap();
1350        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1351
1352        assert_eq!(parsed["version"], 1);
1353        assert!(parsed["hooks"].is_object());
1354        assert!(parsed["hooks"]["preToolUse"].is_array());
1355        assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
1356        assert_eq!(
1357            parsed["hooks"]["preToolUse"][0]["matcher"],
1358            "terminal_command"
1359        );
1360    }
1361
1362    #[test]
1363    fn cursor_hook_detects_old_format_needs_migration() {
1364        let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
1365        let has_correct =
1366            old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
1367        assert!(
1368            !has_correct,
1369            "Old format should be detected as needing migration"
1370        );
1371    }
1372
1373    #[test]
1374    fn gemini_hook_config_has_type_command() {
1375        let binary = "lean-ctx";
1376        let rewrite_cmd = format!("{binary} hook rewrite");
1377        let redirect_cmd = format!("{binary} hook redirect");
1378
1379        let hook_config = serde_json::json!({
1380            "hooks": {
1381                "BeforeTool": [
1382                    {
1383                        "hooks": [{
1384                            "type": "command",
1385                            "command": rewrite_cmd
1386                        }]
1387                    },
1388                    {
1389                        "hooks": [{
1390                            "type": "command",
1391                            "command": redirect_cmd
1392                        }]
1393                    }
1394                ]
1395            }
1396        });
1397
1398        let parsed = hook_config;
1399        let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
1400        assert_eq!(before_tool.len(), 2);
1401
1402        let first_hook = &before_tool[0]["hooks"][0];
1403        assert_eq!(first_hook["type"], "command");
1404        assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
1405
1406        let second_hook = &before_tool[1]["hooks"][0];
1407        assert_eq!(second_hook["type"], "command");
1408        assert_eq!(second_hook["command"], "lean-ctx hook redirect");
1409    }
1410
1411    #[test]
1412    fn gemini_hook_old_format_detected() {
1413        let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
1414        let has_new = old_format.contains("hook rewrite")
1415            && old_format.contains("hook redirect")
1416            && old_format.contains("\"type\"");
1417        assert!(!has_new, "Missing 'type' field should trigger migration");
1418    }
1419
1420    #[test]
1421    fn rewrite_script_uses_registry_pattern() {
1422        let script = generate_rewrite_script("/usr/bin/lean-ctx");
1423        assert!(script.contains(r"git\ *"), "script missing git pattern");
1424        assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
1425        assert!(script.contains(r"npm\ *"), "script missing npm pattern");
1426        assert!(script.contains(r"rg\ *"), "script missing rg pattern");
1427        assert!(script.contains(r"ls\ *"), "script missing ls pattern");
1428        assert!(
1429            script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
1430            "script missing binary path"
1431        );
1432        assert!(
1433            script.contains("PowerShell|powershell"),
1434            "rewrite script must accept PowerShell tool names for Windows compatibility"
1435        );
1436    }
1437
1438    #[test]
1439    fn compact_rewrite_script_uses_registry_pattern() {
1440        let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
1441        assert!(script.contains(r"git\ *"), "compact script missing git");
1442        assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
1443        assert!(script.contains(r"rg\ *"), "compact script missing rg");
1444    }
1445
1446    #[test]
1447    fn rewrite_scripts_contain_all_registry_commands() {
1448        let script = generate_rewrite_script("lean-ctx");
1449        let compact = generate_compact_rewrite_script("lean-ctx");
1450        for entry in crate::rewrite_registry::REWRITE_COMMANDS {
1451            if matches!(entry.category, crate::rewrite_registry::Category::FileRead) {
1452                continue;
1453            }
1454            let pattern = if entry.command.contains('-') {
1455                format!("{}*", entry.command.replace('-', r"\-"))
1456            } else {
1457                format!(r"{}\ *", entry.command)
1458            };
1459            assert!(
1460                script.contains(&pattern),
1461                "rewrite_script missing '{}' (pattern: {})",
1462                entry.command,
1463                pattern
1464            );
1465            assert!(
1466                compact.contains(&pattern),
1467                "compact_rewrite_script missing '{}' (pattern: {})",
1468                entry.command,
1469                pattern
1470            );
1471        }
1472    }
1473
1474    #[test]
1475    fn codex_is_hybrid() {
1476        assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
1477    }
1478
1479    #[test]
1480    fn cursor_is_hybrid() {
1481        assert_eq!(recommend_hook_mode("cursor"), HookMode::Hybrid);
1482    }
1483
1484    #[test]
1485    fn gemini_is_hybrid() {
1486        assert_eq!(recommend_hook_mode("gemini"), HookMode::Hybrid);
1487    }
1488
1489    #[test]
1490    fn claude_is_hybrid() {
1491        assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
1492    }
1493
1494    #[test]
1495    fn unknown_agent_falls_back_to_mcp() {
1496        assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
1497    }
1498
1499    // Drive translation only applies on Windows hosts (GH #397).
1500    #[cfg(windows)]
1501    #[test]
1502    fn from_bash_to_native_converts_msys_drive() {
1503        assert_eq!(
1504            from_bash_to_native_path("/c/Users/ABC/lean-ctx"),
1505            "C:/Users/ABC/lean-ctx"
1506        );
1507        assert_eq!(
1508            from_bash_to_native_path("/d/Program Files/lean-ctx.exe"),
1509            "D:/Program Files/lean-ctx.exe"
1510        );
1511    }
1512
1513    #[test]
1514    fn from_bash_to_native_unix_path_unchanged() {
1515        assert_eq!(
1516            from_bash_to_native_path("/usr/local/bin/lean-ctx"),
1517            "/usr/local/bin/lean-ctx"
1518        );
1519    }
1520
1521    #[test]
1522    fn from_bash_to_native_bare_name() {
1523        assert_eq!(from_bash_to_native_path("lean-ctx"), "lean-ctx");
1524    }
1525
1526    #[test]
1527    fn windows_path_to_bash_form() {
1528        let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1529        let bash = to_bash_compatible_path(native);
1530        assert_eq!(bash, "/c/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1531    }
1532
1533    // The bash→native return leg only translates on Windows hosts (GH #397).
1534    #[cfg(windows)]
1535    #[test]
1536    fn roundtrip_windows_path() {
1537        let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1538        let bash = to_bash_compatible_path(native);
1539        let back = from_bash_to_native_path(&bash);
1540        assert_eq!(back, "C:/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1541    }
1542
1543    #[test]
1544    fn roundtrip_unix_path() {
1545        let native = "/usr/local/bin/lean-ctx";
1546        let bash = to_bash_compatible_path(native);
1547        assert_eq!(bash, native);
1548        let back = from_bash_to_native_path(&bash);
1549        assert_eq!(back, native);
1550    }
1551}