1use std::path::PathBuf;
2
3pub mod agents;
4mod support;
5
6#[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
44pub 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 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_codex_hook, install_copilot_hook,
92 install_crush_hook_with_mode, install_cursor_hook_config, install_cursor_hook_scripts,
93 install_cursor_hook_with_mode, install_gemini_hook, install_gemini_hook_config,
94 install_gemini_hook_scripts, install_hermes_hook_with_mode, install_jetbrains_hook,
95 install_kiro_hook, install_openclaw_hook, install_opencode_hook_with_mode,
96 install_pi_hook_with_mode, install_qoder_hook, install_qoder_hook_with_mode,
97 install_windsurf_hooks, install_windsurf_rules,
98};
99use support::{
100 ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
101 upsert_lean_ctx_codex_hook_entries,
102};
103
104fn mcp_server_quiet_mode() -> bool {
105 std::env::var_os("LEAN_CTX_MCP_SERVER").is_some()
106 || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(value) if value.trim() == "1")
107}
108
109const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
117 "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder",
118];
119
120#[cfg(test)]
125const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
126 "claude-code",
128 "pi",
130 "cline",
133 "roo",
134 "kiro",
135 "antigravity",
138 "antigravity-cli",
139 "amp",
140 "crush",
141 "hermes",
142 "opencode",
143 "openclaw",
144 "qwen",
145 "trae",
146 "amazonq",
147 "verdent",
148];
149
150pub fn refresh_installed_hooks() {
155 let Some(home) = crate::core::home::resolve_home_dir() else {
156 return;
157 };
158 for agent in REFRESHABLE_HOOK_AGENTS {
159 if hooks_installed_for(agent, &home) {
160 refresh_agent_hooks(agent, &home);
161 }
162 }
163}
164
165fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
167 match agent {
168 "claude" => {
169 let dir = crate::setup::claude_config_dir(home);
170 dir.join("hooks/lean-ctx-rewrite.sh").exists()
171 || file_contains_lean_ctx(&dir.join("settings.json"))
172 }
173 "cursor" => {
174 home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
175 || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
176 }
177 "gemini" => {
178 home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
179 .exists()
180 || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
181 }
182 "codex" => {
183 let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
184 dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
185 || file_contains_lean_ctx(&dir.join("hooks.json"))
186 }
187 "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
188 "copilot" => {
189 file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
192 || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
193 }
194 "qoder" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
195 _ => false,
196 }
197}
198
199fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
202 match agent {
203 "claude" => {
204 install_claude_hook_scripts(home);
205 install_claude_hook_config(home);
206 }
207 "cursor" => {
208 install_cursor_hook_scripts(home);
209 install_cursor_hook_config(home);
210 }
211 "gemini" => {
212 install_gemini_hook_scripts(home);
213 install_gemini_hook_config(home);
214 }
215 "codex" => install_codex_hook(),
216 "windsurf" => install_windsurf_hooks(home),
217 "copilot" => install_copilot_hook(true),
218 "qoder" => install_qoder_hook(),
219 _ => {}
220 }
221}
222
223fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
224 std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
225}
226
227fn resolve_binary_path() -> String {
238 crate::core::portable_binary::resolve_portable_binary()
239}
240
241fn resolve_binary_path_for_bash() -> String {
242 let path = resolve_binary_path();
243 to_bash_compatible_path(&path)
244}
245
246pub fn to_bash_compatible_path(path: &str) -> String {
247 let path = match crate::core::pathutil::strip_verbatim_str(path) {
248 Some(stripped) => stripped,
249 None => path.replace('\\', "/"),
250 };
251 if path.len() >= 2 && path.as_bytes()[1] == b':' {
252 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
253 format!("/{drive}{}", &path[2..])
254 } else {
255 path
256 }
257}
258
259pub fn from_bash_to_native_path(path: &str) -> String {
262 crate::core::pathutil::normalize_tool_path(path)
263}
264
265pub fn normalize_tool_path(path: &str) -> String {
268 crate::core::pathutil::normalize_tool_path(path)
269}
270
271pub fn generate_rewrite_script(binary: &str) -> String {
272 let case_pattern = crate::rewrite_registry::bash_case_pattern();
273 format!(
274 r#"#!/usr/bin/env bash
275# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
276set -euo pipefail
277
278LEAN_CTX_BIN="{binary}"
279
280INPUT=$(cat)
281TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
282
283case "$TOOL" in
284 Bash|bash|PowerShell|powershell) ;;
285 *) exit 0 ;;
286esac
287
288CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
289
290if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
291 exit 0
292fi
293
294case "$CMD" in
295 {case_pattern})
296 # Shell-escape then JSON-escape (two passes)
297 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
298 REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
299 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
300 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
301 ;;
302 *) exit 0 ;;
303esac
304"#
305 )
306}
307
308pub fn generate_compact_rewrite_script(binary: &str) -> String {
309 let case_pattern = crate::rewrite_registry::bash_case_pattern();
310 format!(
311 r#"#!/usr/bin/env bash
312# lean-ctx hook — rewrites shell commands
313set -euo pipefail
314LEAN_CTX_BIN="{binary}"
315INPUT=$(cat)
316CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
317if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
318case "$CMD" in
319 {case_pattern})
320 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
321 REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
322 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
323 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
324 *) exit 0 ;;
325esac
326"#
327 )
328}
329
330const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
331# lean-ctx PreToolUse hook — all native tools pass through
332# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
333# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
334exit 0
335";
336
337const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
338# lean-ctx hook — all native tools pass through
339exit 0
340";
341
342pub(crate) const HYBRID_RULES: &str = "\
343# lean-ctx — Hybrid Mode (MCP reads + CLI commands)
344
345Use MCP tools for reads (cache benefit), CLI commands for everything else (no schema overhead):
346
347## MCP tools (keep using):
348| Tool | Why MCP |
349|------|---------|
350| `ctx_read(path, mode)` | In-process cache, re-reads ~13 tokens |
351
352## CLI commands (via Shell/Bash):
353| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
354|---------------------|-------------------|-----|
355| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | No MCP schema overhead |
356| `lean-ctx grep <pattern> [path]` | `ctx_search` | No MCP schema overhead |
357| `lean-ctx ls [path]` | `ctx_tree` | No MCP schema overhead |
358
359## File editing:
360Use native Edit/StrReplace — lean-ctx only handles READ operations.
361Write, Delete, Glob → use normally.
362";
363
364pub fn install_project_rules() {
365 install_project_rules_for_agents(&[]);
366}
367
368pub fn install_project_rules_for_agents(agents: &[&str]) {
371 if crate::core::config::Config::load().rules_scope_effective()
372 == crate::core::config::RulesScope::Global
373 {
374 return;
375 }
376
377 let cwd = std::env::current_dir().unwrap_or_default();
378
379 if !is_inside_git_repo(&cwd) {
380 eprintln!(
381 " Skipping project files: not inside a git repository.\n \
382 Run this command from your project root to create CLAUDE.md / AGENTS.md."
383 );
384 return;
385 }
386
387 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
388 if cwd == home {
389 eprintln!(
390 " Skipping project files: current directory is your home folder.\n \
391 Run this command from a project directory instead."
392 );
393 return;
394 }
395
396 let all = agents.is_empty();
397 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
398
399 ensure_project_agents_integration(&cwd);
400
401 if wants("cursor") || wants("windsurf") {
402 let cursorrules = cwd.join(".cursorrules");
403 if !cursorrules.exists()
404 || !std::fs::read_to_string(&cursorrules)
405 .unwrap_or_default()
406 .contains("lean-ctx")
407 {
408 let content = CURSORRULES_TEMPLATE;
409 if cursorrules.exists() {
410 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
411 if !existing.ends_with('\n') {
412 existing.push('\n');
413 }
414 existing.push('\n');
415 existing.push_str(content);
416 write_file(&cursorrules, &existing);
417 } else {
418 write_file(&cursorrules, content);
419 }
420 if !mcp_server_quiet_mode() {
421 eprintln!("Created/updated .cursorrules in project root.");
422 }
423 }
424 }
425
426 if wants("claude") {
427 let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
433 if let Ok(existing) = std::fs::read_to_string(&claude_rules_file) {
434 if existing.contains("<!-- lean-ctx-rules-")
435 && std::fs::remove_file(&claude_rules_file).is_ok()
436 && !mcp_server_quiet_mode()
437 {
438 eprintln!(
439 "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
440 );
441 }
442 }
443
444 install_claude_project_hooks(&cwd);
445 }
446
447 if wants("kiro") {
448 let kiro_dir = cwd.join(".kiro");
449 if kiro_dir.exists() {
450 let steering_dir = kiro_dir.join("steering");
451 let steering_file = steering_dir.join("lean-ctx.md");
452 if !steering_file.exists()
453 || !std::fs::read_to_string(&steering_file)
454 .unwrap_or_default()
455 .contains("lean-ctx")
456 {
457 let _ = std::fs::create_dir_all(&steering_dir);
458 write_file(&steering_file, KIRO_STEERING_TEMPLATE);
459 if !mcp_server_quiet_mode() {
460 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
461 }
462 }
463 }
464 }
465}
466
467const PROJECT_LEAN_CTX_MD_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
468const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
469const PROJECT_AGENTS_MD: &str = "AGENTS.md";
470const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
471const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
472
473fn ensure_project_agents_integration(cwd: &std::path::Path) {
474 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
475 let desired = format!(
476 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
477 crate::rules_inject::rules_dedicated_markdown()
478 );
479
480 if !lean_ctx_md.exists() {
481 write_file(&lean_ctx_md, &desired);
482 } else if std::fs::read_to_string(&lean_ctx_md)
483 .unwrap_or_default()
484 .contains(PROJECT_LEAN_CTX_MD_MARKER)
485 {
486 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
487 if !current.contains(crate::rules_inject::RULES_VERSION_STR) {
488 write_file(&lean_ctx_md, &desired);
489 }
490 }
491
492 let block = format!(
497 "{AGENTS_BLOCK_START}\n\
498## lean-ctx\n\n\
499Prefer lean-ctx MCP tools over native equivalents for token savings:\n\
500`ctx_read` > Read/cat, `ctx_search` > Grep/rg, `ctx_shell` > bash, `ctx_tree` > ls/find.\n\
501Native Edit/Write/Glob stay as-is; use `ctx_edit` only when Edit needs an unavailable Read.\n\
502Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
503{AGENTS_BLOCK_END}\n"
504 );
505
506 let agents_md = cwd.join(PROJECT_AGENTS_MD);
507 if !agents_md.exists() {
508 let content = format!("# Agent Instructions\n\n{block}");
509 write_file(&agents_md, &content);
510 if !mcp_server_quiet_mode() {
511 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
512 }
513 return;
514 }
515
516 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
517
518 if existing.contains("CLI-first Token Optimization for Pi")
519 && !existing.contains(AGENTS_BLOCK_START)
520 {
521 let content = format!("# Agent Instructions\n\n{block}");
522 write_file(&agents_md, &content);
523 return;
524 }
525
526 if existing.contains(AGENTS_BLOCK_START) {
527 let updated = crate::marked_block::replace_marked_block(
528 &existing,
529 AGENTS_BLOCK_START,
530 AGENTS_BLOCK_END,
531 &block,
532 );
533 if updated != existing {
534 write_file(&agents_md, &updated);
535 }
536 return;
537 }
538
539 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
540 return;
541 }
542
543 let mut out = existing;
544 if !out.ends_with('\n') {
545 out.push('\n');
546 }
547 out.push('\n');
548 out.push_str(&block);
549 write_file(&agents_md, &out);
550 if !mcp_server_quiet_mode() {
551 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
552 }
553}
554
555const CURSORRULES_TEMPLATE: &str = "\
559<!-- lean-ctx -->
560# lean-ctx
561
562Prefer lean-ctx MCP tools: ctx_read > Read/cat, ctx_search > Grep/rg, ctx_shell > bash, ctx_tree > ls/find.
563Edit/Write/Glob stay native; ctx_edit only when Edit needs an unavailable Read.
564Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) — do not duplicate here.
565<!-- /lean-ctx -->
566";
567
568pub const KIRO_STEERING_TEMPLATE: &str = "\
569---
570inclusion: always
571---
572
573# lean-ctx — Context Engineering Layer
574
575The workspace has the `lean-ctx` MCP server installed. You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.
576
577## Mandatory Tool Preferences
578
579| Use this | Instead of | Why |
580|----------|-----------|-----|
581| `mcp_lean_ctx_ctx_read` | `readFile`, `readCode` | Cached reads, 10 compression modes, re-reads cost ~13 tokens |
582| `mcp_lean_ctx_ctx_multi_read` | `readMultipleFiles` | Batch cached reads in one call |
583| `mcp_lean_ctx_ctx_shell` | `executeBash` | Pattern compression for git/npm/test output |
584| `mcp_lean_ctx_ctx_search` | `grepSearch` | Compact, .gitignore-aware results |
585| `mcp_lean_ctx_ctx_tree` | `listDirectory` | Compact directory maps with file counts |
586
587## When to use native Kiro tools instead
588
589- `fsWrite` / `fsAppend` — always use native (lean-ctx doesn't write files)
590- `strReplace` — always use native (precise string replacement)
591- `semanticRename` / `smartRelocate` — always use native (IDE integration)
592- `getDiagnostics` — always use native (language server diagnostics)
593- `deleteFile` — always use native
594
595## Session management
596
597- At the start of a long task, call `mcp_lean_ctx_ctx_preload` with a task description to warm the cache
598- Use `mcp_lean_ctx_ctx_compress` periodically in long conversations to checkpoint context
599- Use `mcp_lean_ctx_ctx_knowledge` to persist important discoveries across sessions
600
601## Rules
602
603- NEVER loop on edit failures — switch to `mcp_lean_ctx_ctx_edit` immediately
604- For large files, use `mcp_lean_ctx_ctx_read` with `mode: \"signatures\"` or `mode: \"map\"` first
605- For re-reading a file you already read, just call `mcp_lean_ctx_ctx_read` again (cache hit = ~13 tokens)
606- When running tests or build commands, use `mcp_lean_ctx_ctx_shell` for compressed output
607";
608
609pub fn install_agent_hook(agent: &str, global: bool) {
610 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
611}
612
613pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
614 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
615 match agent {
616 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
617 "cursor" => install_cursor_hook_with_mode(global, mode),
618 "gemini" => {
619 install_gemini_hook();
620 install_antigravity_cli_hook();
626 }
627 "antigravity" => install_antigravity_hook(),
628 "antigravity-cli" => install_antigravity_cli_hook(),
629 "augment" => install_mcp_json_agent(
630 "Augment CLI",
631 "~/.augment/settings.json",
632 &crate::core::editor_registry::augment_cli_settings_path(&home),
633 ),
634 "codex" => install_codex_hook(),
635 "windsurf" => install_windsurf_rules(global),
636 "cline" | "roo" => install_cline_rules(global),
637 "copilot" | "vscode" => install_copilot_hook(global),
638 "pi" => install_pi_hook_with_mode(global, mode),
639 "qoder" => install_qoder_hook_with_mode(mode),
640 "qoderwork" => install_mcp_json_agent(
641 "QoderWork",
642 "~/.qoderwork/mcp.json",
643 &home.join(".qoderwork/mcp.json"),
644 ),
645 "qwen" => install_mcp_json_agent(
646 "Qwen Code",
647 "~/.qwen/settings.json",
648 &home.join(".qwen/settings.json"),
649 ),
650 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
651 "amazonq" => install_mcp_json_agent(
652 "Amazon Q Developer",
653 "~/.aws/amazonq/default.json",
654 &home.join(".aws/amazonq/default.json"),
655 ),
656 "jetbrains" => install_jetbrains_hook(),
657 "kiro" => install_kiro_hook(),
658 "verdent" => install_mcp_json_agent(
659 "Verdent",
660 "~/.verdent/mcp.json",
661 &home.join(".verdent/mcp.json"),
662 ),
663 "opencode" => install_opencode_hook_with_mode(mode),
664 "amp" => install_amp_hook(),
665 "crush" => install_crush_hook_with_mode(mode),
666 "openclaw" => install_openclaw_hook(),
667 "hermes" => install_hermes_hook_with_mode(global, mode),
668 "zed" => {
669 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
670 let binary = resolve_binary_path();
671 let entry = full_server_entry(&binary);
672 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
673 }
674 "aider" => {
675 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
676 }
677 "continue" => install_mcp_json_agent(
678 "Continue",
679 "~/.continue/mcp.json",
680 &home.join(".continue/mcp.json"),
681 ),
682 "neovim" => install_mcp_json_agent(
683 "Neovim (mcphub.nvim)",
684 "~/.config/mcphub/servers.json",
685 &home.join(".config/mcphub/servers.json"),
686 ),
687 "emacs" => install_mcp_json_agent(
688 "Emacs (mcp.el)",
689 "~/.emacs.d/mcp.json",
690 &home.join(".emacs.d/mcp.json"),
691 ),
692 "sublime" => install_mcp_json_agent(
693 "Sublime Text",
694 "~/.config/sublime-text/mcp.json",
695 &home.join(".config/sublime-text/mcp.json"),
696 ),
697 _ => {
698 eprintln!("Unknown agent: {agent}");
699 eprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
700 eprintln!(" claude, cline, codex, continue, copilot, crush, cursor, emacs, gemini,");
701 eprintln!(" hermes, jetbrains, kiro, neovim, openclaw, opencode, pi, qoder,");
702 eprintln!(" qoderwork, qwen, roo, sublime, trae, verdent, vscode, windsurf, zed");
703 std::process::exit(1);
704 }
705 }
706}
707
708pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
709 match agent {
710 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
711 _ => {}
712 }
713}
714
715fn write_file(path: &std::path::Path, content: &str) {
716 if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
719 return;
720 }
721 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
722 tracing::error!("Error writing {}: {e}", path.display());
723 }
724}
725
726fn is_inside_git_repo(path: &std::path::Path) -> bool {
727 let mut p = path;
728 loop {
729 if p.join(".git").exists() {
730 return true;
731 }
732 match p.parent() {
733 Some(parent) => p = parent,
734 None => return false,
735 }
736 }
737}
738
739#[cfg(unix)]
740fn make_executable(path: &PathBuf) {
741 use std::os::unix::fs::PermissionsExt;
742 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
743}
744
745#[cfg(not(unix))]
746fn make_executable(_path: &PathBuf) {}
747
748fn full_server_entry(binary: &str) -> serde_json::Value {
749 let data_dir = crate::core::data_dir::lean_ctx_data_dir()
750 .map(|d| d.to_string_lossy().to_string())
751 .unwrap_or_default();
752 serde_json::json!({
758 "command": binary,
759 "env": {
760 "LEAN_CTX_DATA_DIR": data_dir
761 }
762 })
763}
764
765pub(crate) fn install_mcp_json_agent(
766 name: &str,
767 display_path: &str,
768 config_path: &std::path::Path,
769) {
770 let binary = resolve_binary_path();
771 let entry = full_server_entry(&binary);
772 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778
779 #[test]
780 fn refresh_covers_every_hybrid_agent() {
781 for agent in HYBRID_AGENTS {
784 let refreshed = REFRESHABLE_HOOK_AGENTS.contains(agent);
785 let exempt = REFRESH_EXEMPT_HYBRID_AGENTS.contains(agent);
786 assert!(
787 refreshed ^ exempt,
788 "hybrid agent `{agent}` must be either refreshed or explicitly exempt (exactly one)"
789 );
790 }
791 }
792
793 #[test]
794 fn refresh_sets_reference_only_hybrid_agents() {
795 for agent in REFRESHABLE_HOOK_AGENTS {
796 assert!(
797 HYBRID_AGENTS.contains(agent),
798 "refreshable agent `{agent}` is not a Hybrid agent"
799 );
800 }
801 for agent in REFRESH_EXEMPT_HYBRID_AGENTS {
802 assert!(
803 HYBRID_AGENTS.contains(agent),
804 "exempt agent `{agent}` is not a Hybrid agent (stale exemption?)"
805 );
806 }
807 }
808
809 #[test]
810 fn hooks_installed_for_is_false_without_artifacts() {
811 let tmp = unique_tmp_dir("leanctx_refresh_empty");
812 for agent in REFRESHABLE_HOOK_AGENTS {
813 if *agent == "codex" {
817 continue;
818 }
819 assert!(
820 !hooks_installed_for(agent, &tmp),
821 "`{agent}` should not be detected as installed in an empty home"
822 );
823 }
824 let _ = std::fs::remove_dir_all(&tmp);
825 }
826
827 #[test]
828 fn hooks_installed_for_detects_marker_content() {
829 let tmp = unique_tmp_dir("leanctx_refresh_marker");
830 let hooks = tmp.join(".codeium/windsurf/hooks.json");
831 std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
832
833 std::fs::write(&hooks, "{\"hooks\":{}}").unwrap();
835 assert!(!hooks_installed_for("windsurf", &tmp));
836
837 std::fs::write(&hooks, "{\"hooks\":{\"cmd\":\"lean-ctx hook rewrite\"}}").unwrap();
839 assert!(hooks_installed_for("windsurf", &tmp));
840
841 let _ = std::fs::remove_dir_all(&tmp);
842 }
843
844 fn unique_tmp_dir(prefix: &str) -> std::path::PathBuf {
845 let nanos = std::time::SystemTime::now()
846 .duration_since(std::time::UNIX_EPOCH)
847 .map_or(0, |d| d.as_nanos());
848 let dir = std::env::temp_dir().join(format!("{prefix}_{}_{nanos}", std::process::id()));
849 std::fs::create_dir_all(&dir).unwrap();
850 dir
851 }
852
853 #[test]
854 fn bash_path_unix_unchanged() {
855 assert_eq!(
856 to_bash_compatible_path("/usr/local/bin/lean-ctx"),
857 "/usr/local/bin/lean-ctx"
858 );
859 }
860
861 #[test]
862 fn bash_path_home_unchanged() {
863 assert_eq!(
864 to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
865 "/home/user/.cargo/bin/lean-ctx"
866 );
867 }
868
869 #[test]
870 fn bash_path_windows_drive_converted() {
871 assert_eq!(
872 to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
873 "/c/Users/Fraser/bin/lean-ctx.exe"
874 );
875 }
876
877 #[test]
878 fn bash_path_windows_lowercase_drive() {
879 assert_eq!(
880 to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
881 "/d/tools/lean-ctx.exe"
882 );
883 }
884
885 #[test]
886 fn bash_path_windows_forward_slashes() {
887 assert_eq!(
888 to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
889 "/c/Users/Fraser/bin/lean-ctx.exe"
890 );
891 }
892
893 #[test]
894 fn bash_path_bare_name_unchanged() {
895 assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
896 }
897
898 #[cfg(windows)]
901 #[test]
902 fn normalize_msys2_path() {
903 assert_eq!(
904 normalize_tool_path("/c/Users/game/Downloads/project"),
905 "C:/Users/game/Downloads/project"
906 );
907 assert_eq!(
908 normalize_tool_path("/d/Projects/app/src"),
909 "D:/Projects/app/src"
910 );
911 }
912
913 #[cfg(not(windows))]
914 #[test]
915 fn normalize_msys2_path_untouched_on_unix() {
916 assert_eq!(
917 crate::core::pathutil::normalize_tool_path_lexical("/c/Users/game/Downloads/project"),
918 "/c/Users/game/Downloads/project"
919 );
920 }
921
922 #[test]
923 fn normalize_backslashes() {
924 assert_eq!(
925 normalize_tool_path("C:\\Users\\game\\project\\src"),
926 "C:/Users/game/project/src"
927 );
928 }
929
930 #[test]
931 fn normalize_mixed_separators() {
932 assert_eq!(
933 normalize_tool_path("C:\\Users/game\\project/src"),
934 "C:/Users/game/project/src"
935 );
936 }
937
938 #[test]
939 fn normalize_double_slashes() {
940 assert_eq!(
941 normalize_tool_path("/home/user//project///src"),
942 "/home/user/project/src"
943 );
944 }
945
946 #[test]
947 fn normalize_trailing_slash() {
948 assert_eq!(
949 normalize_tool_path("/home/user/project/"),
950 "/home/user/project"
951 );
952 }
953
954 #[test]
955 fn normalize_root_preserved() {
956 assert_eq!(normalize_tool_path("/"), "/");
957 }
958
959 #[test]
960 fn normalize_windows_root_preserved() {
961 assert_eq!(normalize_tool_path("C:/"), "C:/");
962 }
963
964 #[test]
965 fn normalize_unix_path_unchanged() {
966 assert_eq!(
967 normalize_tool_path("/home/user/project/src/main.rs"),
968 "/home/user/project/src/main.rs"
969 );
970 }
971
972 #[test]
973 fn normalize_relative_path_unchanged() {
974 assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
975 }
976
977 #[test]
978 fn normalize_dot_unchanged() {
979 assert_eq!(normalize_tool_path("."), ".");
980 }
981
982 #[test]
983 fn normalize_unc_path_preserved() {
984 assert_eq!(
985 normalize_tool_path("//server/share/file"),
986 "//server/share/file"
987 );
988 }
989
990 #[test]
991 fn cursor_hook_config_has_version_and_object_hooks() {
992 let config = serde_json::json!({
993 "version": 1,
994 "hooks": {
995 "preToolUse": [
996 {
997 "matcher": "terminal_command",
998 "command": "lean-ctx hook rewrite"
999 },
1000 {
1001 "matcher": "read_file|grep|search|list_files|list_directory",
1002 "command": "lean-ctx hook redirect"
1003 }
1004 ]
1005 }
1006 });
1007
1008 let json_str = serde_json::to_string_pretty(&config).unwrap();
1009 let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
1010
1011 assert_eq!(parsed["version"], 1);
1012 assert!(parsed["hooks"].is_object());
1013 assert!(parsed["hooks"]["preToolUse"].is_array());
1014 assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
1015 assert_eq!(
1016 parsed["hooks"]["preToolUse"][0]["matcher"],
1017 "terminal_command"
1018 );
1019 }
1020
1021 #[test]
1022 fn cursor_hook_detects_old_format_needs_migration() {
1023 let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
1024 let has_correct =
1025 old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
1026 assert!(
1027 !has_correct,
1028 "Old format should be detected as needing migration"
1029 );
1030 }
1031
1032 #[test]
1033 fn gemini_hook_config_has_type_command() {
1034 let binary = "lean-ctx";
1035 let rewrite_cmd = format!("{binary} hook rewrite");
1036 let redirect_cmd = format!("{binary} hook redirect");
1037
1038 let hook_config = serde_json::json!({
1039 "hooks": {
1040 "BeforeTool": [
1041 {
1042 "hooks": [{
1043 "type": "command",
1044 "command": rewrite_cmd
1045 }]
1046 },
1047 {
1048 "hooks": [{
1049 "type": "command",
1050 "command": redirect_cmd
1051 }]
1052 }
1053 ]
1054 }
1055 });
1056
1057 let parsed = hook_config;
1058 let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
1059 assert_eq!(before_tool.len(), 2);
1060
1061 let first_hook = &before_tool[0]["hooks"][0];
1062 assert_eq!(first_hook["type"], "command");
1063 assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
1064
1065 let second_hook = &before_tool[1]["hooks"][0];
1066 assert_eq!(second_hook["type"], "command");
1067 assert_eq!(second_hook["command"], "lean-ctx hook redirect");
1068 }
1069
1070 #[test]
1071 fn gemini_hook_old_format_detected() {
1072 let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
1073 let has_new = old_format.contains("hook rewrite")
1074 && old_format.contains("hook redirect")
1075 && old_format.contains("\"type\"");
1076 assert!(!has_new, "Missing 'type' field should trigger migration");
1077 }
1078
1079 #[test]
1080 fn rewrite_script_uses_registry_pattern() {
1081 let script = generate_rewrite_script("/usr/bin/lean-ctx");
1082 assert!(script.contains(r"git\ *"), "script missing git pattern");
1083 assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
1084 assert!(script.contains(r"npm\ *"), "script missing npm pattern");
1085 assert!(script.contains(r"rg\ *"), "script missing rg pattern");
1086 assert!(script.contains(r"ls\ *"), "script missing ls pattern");
1087 assert!(
1088 script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
1089 "script missing binary path"
1090 );
1091 assert!(
1092 script.contains("PowerShell|powershell"),
1093 "rewrite script must accept PowerShell tool names for Windows compatibility"
1094 );
1095 }
1096
1097 #[test]
1098 fn compact_rewrite_script_uses_registry_pattern() {
1099 let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
1100 assert!(script.contains(r"git\ *"), "compact script missing git");
1101 assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
1102 assert!(script.contains(r"rg\ *"), "compact script missing rg");
1103 }
1104
1105 #[test]
1106 fn rewrite_scripts_contain_all_registry_commands() {
1107 let script = generate_rewrite_script("lean-ctx");
1108 let compact = generate_compact_rewrite_script("lean-ctx");
1109 for entry in crate::rewrite_registry::REWRITE_COMMANDS {
1110 if matches!(entry.category, crate::rewrite_registry::Category::FileRead) {
1111 continue;
1112 }
1113 let pattern = if entry.command.contains('-') {
1114 format!("{}*", entry.command.replace('-', r"\-"))
1115 } else {
1116 format!(r"{}\ *", entry.command)
1117 };
1118 assert!(
1119 script.contains(&pattern),
1120 "rewrite_script missing '{}' (pattern: {})",
1121 entry.command,
1122 pattern
1123 );
1124 assert!(
1125 compact.contains(&pattern),
1126 "compact_rewrite_script missing '{}' (pattern: {})",
1127 entry.command,
1128 pattern
1129 );
1130 }
1131 }
1132
1133 #[test]
1134 fn codex_is_hybrid() {
1135 assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
1136 }
1137
1138 #[test]
1139 fn cursor_is_hybrid() {
1140 assert_eq!(recommend_hook_mode("cursor"), HookMode::Hybrid);
1141 }
1142
1143 #[test]
1144 fn gemini_is_hybrid() {
1145 assert_eq!(recommend_hook_mode("gemini"), HookMode::Hybrid);
1146 }
1147
1148 #[test]
1149 fn claude_is_hybrid() {
1150 assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
1151 }
1152
1153 #[test]
1154 fn unknown_agent_falls_back_to_mcp() {
1155 assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
1156 }
1157
1158 #[cfg(windows)]
1160 #[test]
1161 fn from_bash_to_native_converts_msys_drive() {
1162 assert_eq!(
1163 from_bash_to_native_path("/c/Users/ABC/lean-ctx"),
1164 "C:/Users/ABC/lean-ctx"
1165 );
1166 assert_eq!(
1167 from_bash_to_native_path("/d/Program Files/lean-ctx.exe"),
1168 "D:/Program Files/lean-ctx.exe"
1169 );
1170 }
1171
1172 #[test]
1173 fn from_bash_to_native_unix_path_unchanged() {
1174 assert_eq!(
1175 from_bash_to_native_path("/usr/local/bin/lean-ctx"),
1176 "/usr/local/bin/lean-ctx"
1177 );
1178 }
1179
1180 #[test]
1181 fn from_bash_to_native_bare_name() {
1182 assert_eq!(from_bash_to_native_path("lean-ctx"), "lean-ctx");
1183 }
1184
1185 #[test]
1186 fn windows_path_to_bash_form() {
1187 let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1188 let bash = to_bash_compatible_path(native);
1189 assert_eq!(bash, "/c/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1190 }
1191
1192 #[cfg(windows)]
1194 #[test]
1195 fn roundtrip_windows_path() {
1196 let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1197 let bash = to_bash_compatible_path(native);
1198 let back = from_bash_to_native_path(&bash);
1199 assert_eq!(back, "C:/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1200 }
1201
1202 #[test]
1203 fn roundtrip_unix_path() {
1204 let native = "/usr/local/bin/lean-ctx";
1205 let bash = to_bash_compatible_path(native);
1206 assert_eq!(bash, native);
1207 let back = from_bash_to_native_path(&bash);
1208 assert_eq!(back, native);
1209 }
1210}