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 fn recommend_hook_mode(agent_key: &str) -> HookMode {
51 match agent_key {
52 "cursor" | "gemini" | "codex" | "claude" | "claude-code" | "crush" | "hermes"
59 | "opencode" | "openclaw" | "pi" | "qoder" | "windsurf" | "amp" | "cline" | "roo"
60 | "copilot" | "kiro" | "qwen" | "trae" | "antigravity" | "amazonq" | "verdent" => {
61 HookMode::Hybrid
62 }
63
64 _ => HookMode::Mcp,
66 }
67}
68use agents::{
69 install_amp_hook, install_antigravity_hook, install_claude_hook_config,
70 install_claude_hook_scripts, install_claude_hook_with_mode, install_claude_project_hooks,
71 install_cline_rules, install_codex_hook, install_copilot_hook, install_crush_hook_with_mode,
72 install_cursor_hook_config, install_cursor_hook_scripts, install_cursor_hook_with_mode,
73 install_gemini_hook, install_gemini_hook_config, install_gemini_hook_scripts,
74 install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
75 install_openclaw_hook, install_opencode_hook_with_mode, install_pi_hook_with_mode,
76 install_qoder_hook_with_mode, install_windsurf_rules,
77};
78use support::{
79 ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
80 upsert_lean_ctx_codex_hook_entries,
81};
82
83fn mcp_server_quiet_mode() -> bool {
84 std::env::var_os("LEAN_CTX_MCP_SERVER").is_some()
85 || matches!(std::env::var("LEAN_CTX_QUIET"), Ok(value) if value.trim() == "1")
86}
87
88pub fn refresh_installed_hooks() {
91 let Some(home) = crate::core::home::resolve_home_dir() else {
92 return;
93 };
94
95 let claude_dir = crate::setup::claude_config_dir(&home);
96 let claude_hooks = claude_dir.join("hooks/lean-ctx-rewrite.sh").exists()
97 || claude_dir.join("settings.json").exists()
98 && std::fs::read_to_string(claude_dir.join("settings.json"))
99 .unwrap_or_default()
100 .contains("lean-ctx");
101
102 if claude_hooks {
103 install_claude_hook_scripts(&home);
104 install_claude_hook_config(&home);
105 }
106
107 let cursor_hooks = home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
108 || home.join(".cursor/hooks.json").exists()
109 && std::fs::read_to_string(home.join(".cursor/hooks.json"))
110 .unwrap_or_default()
111 .contains("lean-ctx");
112
113 if cursor_hooks {
114 install_cursor_hook_scripts(&home);
115 install_cursor_hook_config(&home);
116 }
117
118 let gemini_rewrite = home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh");
119 let gemini_legacy = home.join(".gemini/hooks/lean-ctx-hook-gemini.sh");
120 if gemini_rewrite.exists() || gemini_legacy.exists() {
121 install_gemini_hook_scripts(&home);
122 install_gemini_hook_config(&home);
123 }
124
125 let codex_dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
126 let codex_hooks = codex_dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
127 || codex_dir.join("hooks.json").exists()
128 && std::fs::read_to_string(codex_dir.join("hooks.json"))
129 .unwrap_or_default()
130 .contains("lean-ctx");
131
132 if codex_hooks {
133 install_codex_hook();
134 }
135}
136
137fn resolve_binary_path() -> String {
138 if is_lean_ctx_in_path() {
139 return "lean-ctx".to_string();
140 }
141 crate::core::portable_binary::resolve_portable_binary()
142}
143
144fn is_lean_ctx_in_path() -> bool {
145 let which_cmd = if cfg!(windows) { "where" } else { "which" };
146 std::process::Command::new(which_cmd)
147 .arg("lean-ctx")
148 .stdout(std::process::Stdio::null())
149 .stderr(std::process::Stdio::null())
150 .status()
151 .is_ok_and(|s| s.success())
152}
153
154fn resolve_binary_path_for_bash() -> String {
155 let path = resolve_binary_path();
156 to_bash_compatible_path(&path)
157}
158
159pub fn to_bash_compatible_path(path: &str) -> String {
160 let path = match crate::core::pathutil::strip_verbatim_str(path) {
161 Some(stripped) => stripped,
162 None => path.replace('\\', "/"),
163 };
164 if path.len() >= 2 && path.as_bytes()[1] == b':' {
165 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
166 format!("/{drive}{}", &path[2..])
167 } else {
168 path
169 }
170}
171
172pub fn from_bash_to_native_path(path: &str) -> String {
175 crate::core::pathutil::normalize_tool_path(path)
176}
177
178pub fn normalize_tool_path(path: &str) -> String {
181 crate::core::pathutil::normalize_tool_path(path)
182}
183
184pub fn generate_rewrite_script(binary: &str) -> String {
185 let case_pattern = crate::rewrite_registry::bash_case_pattern();
186 format!(
187 r#"#!/usr/bin/env bash
188# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
189set -euo pipefail
190
191LEAN_CTX_BIN="{binary}"
192
193INPUT=$(cat)
194TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
195
196case "$TOOL" in
197 Bash|bash|PowerShell|powershell) ;;
198 *) exit 0 ;;
199esac
200
201CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
202
203if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then
204 exit 0
205fi
206
207case "$CMD" in
208 {case_pattern})
209 # Shell-escape then JSON-escape (two passes)
210 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
211 REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
212 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
213 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
214 ;;
215 *) exit 0 ;;
216esac
217"#
218 )
219}
220
221pub fn generate_compact_rewrite_script(binary: &str) -> String {
222 let case_pattern = crate::rewrite_registry::bash_case_pattern();
223 format!(
224 r#"#!/usr/bin/env bash
225# lean-ctx hook — rewrites shell commands
226set -euo pipefail
227LEAN_CTX_BIN="{binary}"
228INPUT=$(cat)
229CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
230if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |$LEAN_CTX_BIN )"; then exit 0; fi
231case "$CMD" in
232 {case_pattern})
233 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
234 REWRITE="$LEAN_CTX_BIN -c \"$SHELL_ESC\""
235 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
236 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
237 *) exit 0 ;;
238esac
239"#
240 )
241}
242
243const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
244# lean-ctx PreToolUse hook — all native tools pass through
245# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
246# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
247exit 0
248";
249
250const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
251# lean-ctx hook — all native tools pass through
252exit 0
253";
254
255pub(crate) const HYBRID_RULES: &str = "\
256# lean-ctx — Hybrid Mode (MCP reads + CLI commands)
257
258Use MCP tools for reads (cache benefit), CLI commands for everything else (no schema overhead):
259
260## MCP tools (keep using):
261| Tool | Why MCP |
262|------|---------|
263| `ctx_read(path, mode)` | In-process cache, re-reads ~13 tokens |
264
265## CLI commands (via Shell/Bash):
266| USE (via Shell/Bash) | INSTEAD OF (MCP) | Why |
267|---------------------|-------------------|-----|
268| `lean-ctx -c \"<cmd>\"` | `ctx_shell` | No MCP schema overhead |
269| `lean-ctx grep <pattern> [path]` | `ctx_search` | No MCP schema overhead |
270| `lean-ctx ls [path]` | `ctx_tree` | No MCP schema overhead |
271
272## File editing:
273Use native Edit/StrReplace — lean-ctx only handles READ operations.
274Write, Delete, Glob → use normally.
275";
276
277pub fn install_project_rules() {
278 install_project_rules_for_agents(&[]);
279}
280
281pub fn install_project_rules_for_agents(agents: &[&str]) {
284 if crate::core::config::Config::load().rules_scope_effective()
285 == crate::core::config::RulesScope::Global
286 {
287 return;
288 }
289
290 let cwd = std::env::current_dir().unwrap_or_default();
291
292 if !is_inside_git_repo(&cwd) {
293 eprintln!(
294 " Skipping project files: not inside a git repository.\n \
295 Run this command from your project root to create CLAUDE.md / AGENTS.md."
296 );
297 return;
298 }
299
300 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
301 if cwd == home {
302 eprintln!(
303 " Skipping project files: current directory is your home folder.\n \
304 Run this command from a project directory instead."
305 );
306 return;
307 }
308
309 let all = agents.is_empty();
310 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
311
312 ensure_project_agents_integration(&cwd);
313
314 if wants("cursor") || wants("windsurf") {
315 let cursorrules = cwd.join(".cursorrules");
316 if !cursorrules.exists()
317 || !std::fs::read_to_string(&cursorrules)
318 .unwrap_or_default()
319 .contains("lean-ctx")
320 {
321 let content = CURSORRULES_TEMPLATE;
322 if cursorrules.exists() {
323 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
324 if !existing.ends_with('\n') {
325 existing.push('\n');
326 }
327 existing.push('\n');
328 existing.push_str(content);
329 write_file(&cursorrules, &existing);
330 } else {
331 write_file(&cursorrules, content);
332 }
333 if !mcp_server_quiet_mode() {
334 eprintln!("Created/updated .cursorrules in project root.");
335 }
336 }
337 }
338
339 if wants("claude") {
340 let claude_rules_dir = cwd.join(".claude").join("rules");
341 let claude_rules_file = claude_rules_dir.join("lean-ctx.md");
342 if !claude_rules_file.exists()
343 || !std::fs::read_to_string(&claude_rules_file)
344 .unwrap_or_default()
345 .contains(crate::rules_inject::RULES_VERSION_STR)
346 {
347 let _ = std::fs::create_dir_all(&claude_rules_dir);
348 write_file(
349 &claude_rules_file,
350 crate::rules_inject::rules_dedicated_markdown(),
351 );
352 if !mcp_server_quiet_mode() {
353 eprintln!("Created .claude/rules/lean-ctx.md (Claude Code project rules).");
354 }
355 }
356
357 install_claude_project_hooks(&cwd);
358 }
359
360 if wants("kiro") {
361 let kiro_dir = cwd.join(".kiro");
362 if kiro_dir.exists() {
363 let steering_dir = kiro_dir.join("steering");
364 let steering_file = steering_dir.join("lean-ctx.md");
365 if !steering_file.exists()
366 || !std::fs::read_to_string(&steering_file)
367 .unwrap_or_default()
368 .contains("lean-ctx")
369 {
370 let _ = std::fs::create_dir_all(&steering_dir);
371 write_file(&steering_file, KIRO_STEERING_TEMPLATE);
372 if !mcp_server_quiet_mode() {
373 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
374 }
375 }
376 }
377 }
378}
379
380const PROJECT_LEAN_CTX_MD_MARKER: &str = "<!-- lean-ctx-owned: PROJECT-LEAN-CTX.md v1 -->";
381const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
382const PROJECT_AGENTS_MD: &str = "AGENTS.md";
383const AGENTS_BLOCK_START: &str = "<!-- lean-ctx -->";
384const AGENTS_BLOCK_END: &str = "<!-- /lean-ctx -->";
385
386fn ensure_project_agents_integration(cwd: &std::path::Path) {
387 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
388 let desired = format!(
389 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
390 crate::rules_inject::rules_dedicated_markdown()
391 );
392
393 if !lean_ctx_md.exists() {
394 write_file(&lean_ctx_md, &desired);
395 } else if std::fs::read_to_string(&lean_ctx_md)
396 .unwrap_or_default()
397 .contains(PROJECT_LEAN_CTX_MD_MARKER)
398 {
399 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
400 if !current.contains(crate::rules_inject::RULES_VERSION_STR) {
401 write_file(&lean_ctx_md, &desired);
402 }
403 }
404
405 let block = format!(
406 "{AGENTS_BLOCK_START}\n\
407## lean-ctx\n\n\
408Prefer lean-ctx MCP tools over native equivalents for token savings.\n\
409Full rules: @{PROJECT_LEAN_CTX_MD}\n\
410{AGENTS_BLOCK_END}\n"
411 );
412
413 let agents_md = cwd.join(PROJECT_AGENTS_MD);
414 if !agents_md.exists() {
415 let content = format!("# Agent Instructions\n\n{block}");
416 write_file(&agents_md, &content);
417 if !mcp_server_quiet_mode() {
418 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
419 }
420 return;
421 }
422
423 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
424
425 if existing.contains("CLI-first Token Optimization for Pi")
426 && !existing.contains(AGENTS_BLOCK_START)
427 {
428 let content = format!("# Agent Instructions\n\n{block}");
429 write_file(&agents_md, &content);
430 return;
431 }
432
433 if existing.contains(AGENTS_BLOCK_START) {
434 let updated = crate::marked_block::replace_marked_block(
435 &existing,
436 AGENTS_BLOCK_START,
437 AGENTS_BLOCK_END,
438 &block,
439 );
440 if updated != existing {
441 write_file(&agents_md, &updated);
442 }
443 return;
444 }
445
446 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
447 return;
448 }
449
450 let mut out = existing;
451 if !out.ends_with('\n') {
452 out.push('\n');
453 }
454 out.push('\n');
455 out.push_str(&block);
456 write_file(&agents_md, &out);
457 if !mcp_server_quiet_mode() {
458 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
459 }
460}
461
462const CURSORRULES_TEMPLATE: &str = "\
463# lean-ctx — Context Engineering Layer
464
465CRITICAL: ALWAYS use lean-ctx tools instead of native equivalents. This is NOT optional.
466
467| MUST USE | NEVER USE | Why |
468|----------|-----------|-----|
469| `ctx_read(path, mode)` | `Read` / `cat` / `head` / `tail` | Cached, 10 read modes, re-reads ~13 tokens |
470| `ctx_search(pattern, path)` | `Grep` / `rg` | Compact, token-efficient results |
471| `lean-ctx -c \"<cmd>\"` (via Shell) | `ctx_shell` / raw `Shell` | CLI compression, no MCP overhead |
472
473File editing: use native Edit/StrReplace. Write, Delete, Glob → use normally.
474NEVER loop on Edit failures — switch to ctx_edit immediately.
475REMINDER: You MUST use lean-ctx tools. NEVER use native Read, Grep, or Shell directly.
476";
477
478pub const KIRO_STEERING_TEMPLATE: &str = "\
479---
480inclusion: always
481---
482
483# lean-ctx — Context Engineering Layer
484
485The workspace has the `lean-ctx` MCP server installed. You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.
486
487## Mandatory Tool Preferences
488
489| Use this | Instead of | Why |
490|----------|-----------|-----|
491| `mcp_lean_ctx_ctx_read` | `readFile`, `readCode` | Cached reads, 10 compression modes, re-reads cost ~13 tokens |
492| `mcp_lean_ctx_ctx_multi_read` | `readMultipleFiles` | Batch cached reads in one call |
493| `mcp_lean_ctx_ctx_shell` | `executeBash` | Pattern compression for git/npm/test output |
494| `mcp_lean_ctx_ctx_search` | `grepSearch` | Compact, .gitignore-aware results |
495| `mcp_lean_ctx_ctx_tree` | `listDirectory` | Compact directory maps with file counts |
496
497## When to use native Kiro tools instead
498
499- `fsWrite` / `fsAppend` — always use native (lean-ctx doesn't write files)
500- `strReplace` — always use native (precise string replacement)
501- `semanticRename` / `smartRelocate` — always use native (IDE integration)
502- `getDiagnostics` — always use native (language server diagnostics)
503- `deleteFile` — always use native
504
505## Session management
506
507- At the start of a long task, call `mcp_lean_ctx_ctx_preload` with a task description to warm the cache
508- Use `mcp_lean_ctx_ctx_compress` periodically in long conversations to checkpoint context
509- Use `mcp_lean_ctx_ctx_knowledge` to persist important discoveries across sessions
510
511## Rules
512
513- NEVER loop on edit failures — switch to `mcp_lean_ctx_ctx_edit` immediately
514- For large files, use `mcp_lean_ctx_ctx_read` with `mode: \"signatures\"` or `mode: \"map\"` first
515- For re-reading a file you already read, just call `mcp_lean_ctx_ctx_read` again (cache hit = ~13 tokens)
516- When running tests or build commands, use `mcp_lean_ctx_ctx_shell` for compressed output
517";
518
519pub fn install_agent_hook(agent: &str, global: bool) {
520 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
521}
522
523pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
524 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
525 match agent {
526 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
527 "cursor" => install_cursor_hook_with_mode(global, mode),
528 "gemini" => install_gemini_hook(),
529 "antigravity" => install_antigravity_hook(),
530 "augment" => install_mcp_json_agent(
531 "Augment CLI",
532 "~/.augment/settings.json",
533 &crate::core::editor_registry::augment_cli_settings_path(&home),
534 ),
535 "codex" => install_codex_hook(),
536 "windsurf" => install_windsurf_rules(global),
537 "cline" | "roo" => install_cline_rules(global),
538 "copilot" | "vscode" => install_copilot_hook(global),
539 "pi" => install_pi_hook_with_mode(global, mode),
540 "qoder" => install_qoder_hook_with_mode(mode),
541 "qoderwork" => install_mcp_json_agent(
542 "QoderWork",
543 "~/.qoderwork/mcp.json",
544 &home.join(".qoderwork/mcp.json"),
545 ),
546 "qwen" => install_mcp_json_agent(
547 "Qwen Code",
548 "~/.qwen/settings.json",
549 &home.join(".qwen/settings.json"),
550 ),
551 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
552 "amazonq" => install_mcp_json_agent(
553 "Amazon Q Developer",
554 "~/.aws/amazonq/default.json",
555 &home.join(".aws/amazonq/default.json"),
556 ),
557 "jetbrains" => install_jetbrains_hook(),
558 "kiro" => install_kiro_hook(),
559 "verdent" => install_mcp_json_agent(
560 "Verdent",
561 "~/.verdent/mcp.json",
562 &home.join(".verdent/mcp.json"),
563 ),
564 "opencode" => install_opencode_hook_with_mode(mode),
565 "amp" => install_amp_hook(),
566 "crush" => install_crush_hook_with_mode(mode),
567 "openclaw" => install_openclaw_hook(),
568 "hermes" => install_hermes_hook_with_mode(global, mode),
569 "zed" => {
570 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
571 let binary = resolve_binary_path();
572 let entry = full_server_entry(&binary);
573 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
574 }
575 "aider" => {
576 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
577 }
578 "continue" => install_mcp_json_agent(
579 "Continue",
580 "~/.continue/mcp.json",
581 &home.join(".continue/mcp.json"),
582 ),
583 "neovim" => install_mcp_json_agent(
584 "Neovim (mcphub.nvim)",
585 "~/.config/mcphub/servers.json",
586 &home.join(".config/mcphub/servers.json"),
587 ),
588 "emacs" => install_mcp_json_agent(
589 "Emacs (mcp.el)",
590 "~/.emacs.d/mcp.json",
591 &home.join(".emacs.d/mcp.json"),
592 ),
593 "sublime" => install_mcp_json_agent(
594 "Sublime Text",
595 "~/.config/sublime-text/mcp.json",
596 &home.join(".config/sublime-text/mcp.json"),
597 ),
598 _ => {
599 eprintln!("Unknown agent: {agent}");
600 eprintln!(" Supported: aider, amazonq, amp, antigravity, augment, claude, cline,");
601 eprintln!(" codex, continue, copilot, crush, cursor, emacs, gemini, hermes,");
602 eprintln!(" jetbrains, kiro, neovim, openclaw, opencode, pi, qoder, qoderwork,");
603 eprintln!(" qwen, roo, sublime, trae, verdent, vscode, windsurf, zed");
604 std::process::exit(1);
605 }
606 }
607}
608
609pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
610 match agent {
611 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
612 _ => {}
613 }
614}
615
616fn write_file(path: &std::path::Path, content: &str) {
617 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
618 tracing::error!("Error writing {}: {e}", path.display());
619 }
620}
621
622fn is_inside_git_repo(path: &std::path::Path) -> bool {
623 let mut p = path;
624 loop {
625 if p.join(".git").exists() {
626 return true;
627 }
628 match p.parent() {
629 Some(parent) => p = parent,
630 None => return false,
631 }
632 }
633}
634
635#[cfg(unix)]
636fn make_executable(path: &PathBuf) {
637 use std::os::unix::fs::PermissionsExt;
638 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
639}
640
641#[cfg(not(unix))]
642fn make_executable(_path: &PathBuf) {}
643
644fn full_server_entry(binary: &str) -> serde_json::Value {
645 let data_dir = crate::core::data_dir::lean_ctx_data_dir()
646 .map(|d| d.to_string_lossy().to_string())
647 .unwrap_or_default();
648 serde_json::json!({
649 "command": binary,
650 "env": {
651 "LEAN_CTX_DATA_DIR": data_dir,
652 "LEAN_CTX_FULL_TOOLS": "1"
653 }
654 })
655}
656
657pub(crate) fn install_mcp_json_agent(
658 name: &str,
659 display_path: &str,
660 config_path: &std::path::Path,
661) {
662 let binary = resolve_binary_path();
663 let entry = full_server_entry(&binary);
664 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670
671 #[test]
672 fn bash_path_unix_unchanged() {
673 assert_eq!(
674 to_bash_compatible_path("/usr/local/bin/lean-ctx"),
675 "/usr/local/bin/lean-ctx"
676 );
677 }
678
679 #[test]
680 fn bash_path_home_unchanged() {
681 assert_eq!(
682 to_bash_compatible_path("/home/user/.cargo/bin/lean-ctx"),
683 "/home/user/.cargo/bin/lean-ctx"
684 );
685 }
686
687 #[test]
688 fn bash_path_windows_drive_converted() {
689 assert_eq!(
690 to_bash_compatible_path("C:\\Users\\Fraser\\bin\\lean-ctx.exe"),
691 "/c/Users/Fraser/bin/lean-ctx.exe"
692 );
693 }
694
695 #[test]
696 fn bash_path_windows_lowercase_drive() {
697 assert_eq!(
698 to_bash_compatible_path("D:\\tools\\lean-ctx.exe"),
699 "/d/tools/lean-ctx.exe"
700 );
701 }
702
703 #[test]
704 fn bash_path_windows_forward_slashes() {
705 assert_eq!(
706 to_bash_compatible_path("C:/Users/Fraser/bin/lean-ctx.exe"),
707 "/c/Users/Fraser/bin/lean-ctx.exe"
708 );
709 }
710
711 #[test]
712 fn bash_path_bare_name_unchanged() {
713 assert_eq!(to_bash_compatible_path("lean-ctx"), "lean-ctx");
714 }
715
716 #[test]
717 fn normalize_msys2_path() {
718 assert_eq!(
719 normalize_tool_path("/c/Users/game/Downloads/project"),
720 "C:/Users/game/Downloads/project"
721 );
722 }
723
724 #[test]
725 fn normalize_msys2_drive_d() {
726 assert_eq!(
727 normalize_tool_path("/d/Projects/app/src"),
728 "D:/Projects/app/src"
729 );
730 }
731
732 #[test]
733 fn normalize_backslashes() {
734 assert_eq!(
735 normalize_tool_path("C:\\Users\\game\\project\\src"),
736 "C:/Users/game/project/src"
737 );
738 }
739
740 #[test]
741 fn normalize_mixed_separators() {
742 assert_eq!(
743 normalize_tool_path("C:\\Users/game\\project/src"),
744 "C:/Users/game/project/src"
745 );
746 }
747
748 #[test]
749 fn normalize_double_slashes() {
750 assert_eq!(
751 normalize_tool_path("/home/user//project///src"),
752 "/home/user/project/src"
753 );
754 }
755
756 #[test]
757 fn normalize_trailing_slash() {
758 assert_eq!(
759 normalize_tool_path("/home/user/project/"),
760 "/home/user/project"
761 );
762 }
763
764 #[test]
765 fn normalize_root_preserved() {
766 assert_eq!(normalize_tool_path("/"), "/");
767 }
768
769 #[test]
770 fn normalize_windows_root_preserved() {
771 assert_eq!(normalize_tool_path("C:/"), "C:/");
772 }
773
774 #[test]
775 fn normalize_unix_path_unchanged() {
776 assert_eq!(
777 normalize_tool_path("/home/user/project/src/main.rs"),
778 "/home/user/project/src/main.rs"
779 );
780 }
781
782 #[test]
783 fn normalize_relative_path_unchanged() {
784 assert_eq!(normalize_tool_path("src/main.rs"), "src/main.rs");
785 }
786
787 #[test]
788 fn normalize_dot_unchanged() {
789 assert_eq!(normalize_tool_path("."), ".");
790 }
791
792 #[test]
793 fn normalize_unc_path_preserved() {
794 assert_eq!(
795 normalize_tool_path("//server/share/file"),
796 "//server/share/file"
797 );
798 }
799
800 #[test]
801 fn cursor_hook_config_has_version_and_object_hooks() {
802 let config = serde_json::json!({
803 "version": 1,
804 "hooks": {
805 "preToolUse": [
806 {
807 "matcher": "terminal_command",
808 "command": "lean-ctx hook rewrite"
809 },
810 {
811 "matcher": "read_file|grep|search|list_files|list_directory",
812 "command": "lean-ctx hook redirect"
813 }
814 ]
815 }
816 });
817
818 let json_str = serde_json::to_string_pretty(&config).unwrap();
819 let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
820
821 assert_eq!(parsed["version"], 1);
822 assert!(parsed["hooks"].is_object());
823 assert!(parsed["hooks"]["preToolUse"].is_array());
824 assert_eq!(parsed["hooks"]["preToolUse"].as_array().unwrap().len(), 2);
825 assert_eq!(
826 parsed["hooks"]["preToolUse"][0]["matcher"],
827 "terminal_command"
828 );
829 }
830
831 #[test]
832 fn cursor_hook_detects_old_format_needs_migration() {
833 let old_format = r#"{"hooks":[{"event":"preToolUse","command":"lean-ctx hook rewrite"}]}"#;
834 let has_correct =
835 old_format.contains("\"version\"") && old_format.contains("\"preToolUse\"");
836 assert!(
837 !has_correct,
838 "Old format should be detected as needing migration"
839 );
840 }
841
842 #[test]
843 fn gemini_hook_config_has_type_command() {
844 let binary = "lean-ctx";
845 let rewrite_cmd = format!("{binary} hook rewrite");
846 let redirect_cmd = format!("{binary} hook redirect");
847
848 let hook_config = serde_json::json!({
849 "hooks": {
850 "BeforeTool": [
851 {
852 "hooks": [{
853 "type": "command",
854 "command": rewrite_cmd
855 }]
856 },
857 {
858 "hooks": [{
859 "type": "command",
860 "command": redirect_cmd
861 }]
862 }
863 ]
864 }
865 });
866
867 let parsed = hook_config;
868 let before_tool = parsed["hooks"]["BeforeTool"].as_array().unwrap();
869 assert_eq!(before_tool.len(), 2);
870
871 let first_hook = &before_tool[0]["hooks"][0];
872 assert_eq!(first_hook["type"], "command");
873 assert_eq!(first_hook["command"], "lean-ctx hook rewrite");
874
875 let second_hook = &before_tool[1]["hooks"][0];
876 assert_eq!(second_hook["type"], "command");
877 assert_eq!(second_hook["command"], "lean-ctx hook redirect");
878 }
879
880 #[test]
881 fn gemini_hook_old_format_detected() {
882 let old_format = r#"{"hooks":{"BeforeTool":[{"command":"lean-ctx hook rewrite"}]}}"#;
883 let has_new = old_format.contains("hook rewrite")
884 && old_format.contains("hook redirect")
885 && old_format.contains("\"type\"");
886 assert!(!has_new, "Missing 'type' field should trigger migration");
887 }
888
889 #[test]
890 fn rewrite_script_uses_registry_pattern() {
891 let script = generate_rewrite_script("/usr/bin/lean-ctx");
892 assert!(script.contains(r"git\ *"), "script missing git pattern");
893 assert!(script.contains(r"cargo\ *"), "script missing cargo pattern");
894 assert!(script.contains(r"npm\ *"), "script missing npm pattern");
895 assert!(script.contains(r"rg\ *"), "script missing rg pattern");
896 assert!(script.contains(r"ls\ *"), "script missing ls pattern");
897 assert!(
898 script.contains("LEAN_CTX_BIN=\"/usr/bin/lean-ctx\""),
899 "script missing binary path"
900 );
901 assert!(
902 script.contains("PowerShell|powershell"),
903 "rewrite script must accept PowerShell tool names for Windows compatibility"
904 );
905 }
906
907 #[test]
908 fn compact_rewrite_script_uses_registry_pattern() {
909 let script = generate_compact_rewrite_script("/usr/bin/lean-ctx");
910 assert!(script.contains(r"git\ *"), "compact script missing git");
911 assert!(script.contains(r"cargo\ *"), "compact script missing cargo");
912 assert!(script.contains(r"rg\ *"), "compact script missing rg");
913 }
914
915 #[test]
916 fn rewrite_scripts_contain_all_registry_commands() {
917 let script = generate_rewrite_script("lean-ctx");
918 let compact = generate_compact_rewrite_script("lean-ctx");
919 for entry in crate::rewrite_registry::REWRITE_COMMANDS {
920 if matches!(entry.category, crate::rewrite_registry::Category::FileRead) {
921 continue;
922 }
923 let pattern = if entry.command.contains('-') {
924 format!("{}*", entry.command.replace('-', r"\-"))
925 } else {
926 format!(r"{}\ *", entry.command)
927 };
928 assert!(
929 script.contains(&pattern),
930 "rewrite_script missing '{}' (pattern: {})",
931 entry.command,
932 pattern
933 );
934 assert!(
935 compact.contains(&pattern),
936 "compact_rewrite_script missing '{}' (pattern: {})",
937 entry.command,
938 pattern
939 );
940 }
941 }
942
943 #[test]
944 fn codex_is_hybrid() {
945 assert_eq!(recommend_hook_mode("codex"), HookMode::Hybrid);
946 }
947
948 #[test]
949 fn cursor_is_hybrid() {
950 assert_eq!(recommend_hook_mode("cursor"), HookMode::Hybrid);
951 }
952
953 #[test]
954 fn gemini_is_hybrid() {
955 assert_eq!(recommend_hook_mode("gemini"), HookMode::Hybrid);
956 }
957
958 #[test]
959 fn claude_is_hybrid() {
960 assert_eq!(recommend_hook_mode("claude"), HookMode::Hybrid);
961 }
962
963 #[test]
964 fn unknown_agent_falls_back_to_mcp() {
965 assert_eq!(recommend_hook_mode("unknown-agent"), HookMode::Mcp);
966 }
967
968 #[test]
969 fn from_bash_to_native_converts_msys_drive() {
970 assert_eq!(
971 from_bash_to_native_path("/c/Users/ABC/lean-ctx"),
972 "C:/Users/ABC/lean-ctx"
973 );
974 }
975
976 #[test]
977 fn from_bash_to_native_drive_d() {
978 assert_eq!(
979 from_bash_to_native_path("/d/Program Files/lean-ctx.exe"),
980 "D:/Program Files/lean-ctx.exe"
981 );
982 }
983
984 #[test]
985 fn from_bash_to_native_unix_path_unchanged() {
986 assert_eq!(
987 from_bash_to_native_path("/usr/local/bin/lean-ctx"),
988 "/usr/local/bin/lean-ctx"
989 );
990 }
991
992 #[test]
993 fn from_bash_to_native_bare_name() {
994 assert_eq!(from_bash_to_native_path("lean-ctx"), "lean-ctx");
995 }
996
997 #[test]
998 fn roundtrip_windows_path() {
999 let native = r"C:\Users\ABC\AppData\Local\lean-ctx\lean-ctx.exe";
1000 let bash = to_bash_compatible_path(native);
1001 assert_eq!(bash, "/c/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1002 let back = from_bash_to_native_path(&bash);
1003 assert_eq!(back, "C:/Users/ABC/AppData/Local/lean-ctx/lean-ctx.exe");
1004 }
1005
1006 #[test]
1007 fn roundtrip_unix_path() {
1008 let native = "/usr/local/bin/lean-ctx";
1009 let bash = to_bash_compatible_path(native);
1010 assert_eq!(bash, native);
1011 let back = from_bash_to_native_path(&bash);
1012 assert_eq!(back, native);
1013 }
1014}