1use std::path::PathBuf;
2
3pub mod agents;
4mod support;
5
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum HookMode {
15 #[default]
16 Mcp,
17 Hybrid,
18 Replace,
19}
20
21impl std::fmt::Display for HookMode {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 match self {
24 Self::Mcp => write!(f, "MCP"),
25 Self::Hybrid => write!(f, "Hybrid"),
26 Self::Replace => write!(f, "Replace"),
27 }
28 }
29}
30
31impl HookMode {
32 pub fn from_str_loose(s: &str) -> Option<Self> {
33 match s.to_lowercase().replace('-', "").as_str() {
34 "mcp" => Some(Self::Mcp),
35 "hybrid" => Some(Self::Hybrid),
36 "replace" => Some(Self::Replace),
37 _ => None,
38 }
39 }
40
41 pub fn cap_at_hybrid(self) -> Self {
43 if matches!(self, Self::Replace) {
44 Self::Hybrid
45 } else {
46 self
47 }
48 }
49
50 pub fn description(&self) -> &'static str {
51 match self {
52 Self::Mcp => "MCP server only (extension/plugin-based agents without reliable shell)",
53 Self::Hybrid => "MCP server + shell hooks for command compression (best of both)",
54 Self::Replace => {
55 "Native tools denied — lean-ctx MCP is the only path (zero tool drift)"
56 }
57 }
58 }
59}
60
61pub const REPLACE_AGENTS: &[&str] = &[
65 "cursor",
66 "claude",
67 "claude-code",
68 "codebuddy",
69 "codex",
70 "windsurf",
71 "opencode",
72 "gemini",
73];
74
75pub const HYBRID_AGENTS: &[&str] = &[
78 "cursor",
79 "gemini",
80 "codex",
81 "claude",
82 "claude-code",
83 "crush",
84 "hermes",
85 "opencode",
86 "openclaw",
87 "pi",
88 "omp",
89 "qoder",
90 "qodercli",
91 "windsurf",
92 "amp",
93 "cline",
94 "roo",
95 "copilot",
96 "kiro",
97 "qwen",
98 "trae",
99 "antigravity",
100 "antigravity-cli",
101 "amazonq",
102 "verdent",
103];
104
105pub const MCP_ONLY_AGENTS: &[&str] = &["codewhale"];
115
116pub fn is_supported_agent(agent: &str) -> bool {
121 let key = agent.to_ascii_lowercase();
122 REPLACE_AGENTS.contains(&key.as_str())
123 || HYBRID_AGENTS.contains(&key.as_str())
124 || MCP_ONLY_AGENTS.contains(&key.as_str())
125}
126
127pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
137 let deny_suppressed = is_deny_suppressed();
138 if let Some(override_mode) = crate::core::config::Config::load().hook_mode_override() {
139 return if deny_suppressed {
140 override_mode.cap_at_hybrid()
141 } else {
142 override_mode
143 };
144 }
145 if deny_suppressed {
146 if REPLACE_AGENTS.contains(&agent_key) || HYBRID_AGENTS.contains(&agent_key) {
147 return HookMode::Hybrid;
148 }
149 return HookMode::Mcp;
150 }
151 if REPLACE_AGENTS.contains(&agent_key) {
152 HookMode::Replace
153 } else if HYBRID_AGENTS.contains(&agent_key) {
154 HookMode::Hybrid
155 } else {
156 HookMode::Mcp
157 }
158}
159
160fn is_deny_suppressed() -> bool {
162 if std::env::var("LEAN_CTX_DISABLED").is_ok() {
163 return true;
164 }
165 if matches!(std::env::var("LEAN_CTX_SHADOW_MODE"), Ok(v) if v.trim() == "false" || v.trim() == "0")
166 {
167 return true;
168 }
169 if matches!(std::env::var("LEAN_CTX_HEAL"), Ok(v) if v.trim().eq_ignore_ascii_case("off") || v.trim() == "0")
170 {
171 return true;
172 }
173 let cfg = crate::core::config::Config::load();
174 !cfg.shadow_mode
175}
176use agents::{
177 install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
178 install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
179 install_claude_permissions_allow_mcp, install_claude_permissions_deny_replace,
180 install_claude_project_hooks, install_claude_statusline, install_cline_rules,
181 install_codebuddy_hook_config, install_codebuddy_hook_scripts,
182 install_codebuddy_hook_with_mode, install_codebuddy_permissions_deny_replace,
183 install_codebuddy_project_hooks, install_codex_hook, install_codex_runtime_hook,
184 install_copilot_hook, install_copilot_runtime_hook, install_crush_hook_with_mode,
185 install_cursor_deny_hook, install_cursor_hook_config, install_cursor_hook_scripts,
186 install_cursor_hook_with_mode, install_gemini_deny_hook, install_gemini_hook,
187 install_gemini_hook_config, install_gemini_hook_scripts, install_grok_mcp,
188 install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
189 install_openclaw_hook, install_opencode_hook_with_mode, install_pi_hook_with_mode,
190 install_qoder_hook_with_mode, install_qoder_runtime_hook_with_mode, install_vibe_hook,
191 install_windsurf_hooks, install_windsurf_hooks_replace, install_windsurf_rules,
192};
193use support::{
194 ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
195 upsert_lean_ctx_codex_hook_entries,
196};
197
198fn mcp_server_quiet_mode() -> bool {
199 crate::core::runtime_flags::mcp_server_enabled() || crate::core::runtime_flags::quiet_enabled()
200}
201
202const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
210 "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder", "qodercli",
211];
212
213#[cfg(test)]
218const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
219 "claude-code",
221 "pi",
223 "omp",
225 "cline",
228 "roo",
229 "kiro",
230 "antigravity",
233 "antigravity-cli",
234 "amp",
235 "crush",
236 "hermes",
237 "opencode",
238 "openclaw",
239 "qwen",
240 "trae",
241 "amazonq",
242 "verdent",
243];
244
245pub fn refresh_installed_hooks() {
250 let Some(home) = crate::core::home::resolve_home_dir() else {
251 return;
252 };
253 for agent in REFRESHABLE_HOOK_AGENTS {
254 if hooks_installed_for(agent, &home) {
255 refresh_agent_hooks(agent, &home);
256 }
257 }
258}
259
260fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
262 match agent {
263 "claude" => {
264 let dir = crate::setup::claude_config_dir(home);
265 dir.join("hooks/lean-ctx-rewrite.sh").exists()
266 || file_contains_lean_ctx(&dir.join("settings.json"))
267 }
268 "codebuddy" => {
269 let dir = crate::core::editor_registry::codebuddy_state_dir(home);
270 dir.join("hooks/lean-ctx-rewrite.sh").exists()
271 || file_contains_lean_ctx(&dir.join("settings.json"))
272 }
273 "cursor" => {
274 home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
275 || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
276 }
277 "gemini" => {
278 home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
279 .exists()
280 || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
281 }
282 "codex" => {
283 let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
284 dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
285 || file_contains_lean_ctx(&dir.join("hooks.json"))
286 }
287 "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
288 "copilot" => {
289 file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
292 || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
293 }
294 "qoder" | "qodercli" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
295 _ => false,
296 }
297}
298
299fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
304 let mode = recommend_hook_mode(agent);
305 match agent {
306 "claude" => {
307 install_claude_hook_scripts(home);
308 install_claude_hook_config(home);
309 install_claude_statusline(home);
312 if mode == HookMode::Replace {
313 install_claude_permissions_deny_replace(home);
314 }
315 }
316 "codebuddy" => {
317 install_codebuddy_hook_scripts(home);
318 install_codebuddy_hook_config(home);
319 if mode == HookMode::Replace {
320 install_codebuddy_permissions_deny_replace(home);
321 }
322 }
323 "cursor" => {
324 install_cursor_hook_scripts(home);
325 install_cursor_hook_config(home);
326 if mode == HookMode::Replace {
327 install_cursor_deny_hook(true);
328 }
329 }
330 "gemini" => {
331 install_gemini_hook_scripts(home);
332 install_gemini_hook_config(home);
333 if mode == HookMode::Replace {
334 install_gemini_deny_hook(home);
335 }
336 }
337 "codex" => install_codex_runtime_hook(),
338 "windsurf" => {
339 if mode == HookMode::Replace {
340 install_windsurf_hooks_replace(home);
341 } else {
342 install_windsurf_hooks(home);
343 }
344 }
345 "copilot" => install_copilot_runtime_hook(true),
346 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
347 _ => {}
348 }
349}
350
351fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
352 std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
353}
354
355fn resolve_binary_path() -> String {
371 crate::core::portable_binary::resolve_agent_binary()
372}
373
374fn resolve_hook_command_binary() -> String {
385 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
386 return portable;
387 }
388 resolve_binary_path()
389}
390
391fn resolve_binary_path_for_bash() -> String {
392 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
393 return portable;
394 }
395 to_bash_compatible_path(&resolve_binary_path())
396}
397
398pub(crate) fn shell_quoted_binary(binary: &str) -> String {
405 let escaped = binary.replace('"', "\\\"").replace('`', "\\`");
406 format!("\"{escaped}\"")
407}
408
409fn wrapper_is_portable_and_working(path: &std::path::Path, home: &std::path::Path) -> bool {
418 std::fs::read_to_string(path)
419 .is_ok_and(|content| wrapper_content_is_portable_and_working(&content, home))
420}
421
422pub(crate) fn wrapper_content_is_portable_and_working(
423 content: &str,
424 home: &std::path::Path,
425) -> bool {
426 let Some(token) = wrapper_binary_token(content) else {
427 return false;
428 };
429 if !(token.contains("$HOME") || token.contains("${HOME}") || token.contains("%USERPROFILE%")) {
430 return false;
431 }
432 let home_s = home.to_string_lossy();
433 let expanded = token
434 .replace("${HOME}", &home_s)
435 .replace("$HOME", &home_s)
436 .replace("%USERPROFILE%", &home_s);
437 std::path::Path::new(&from_bash_to_native_path(&expanded)).exists()
438}
439
440pub(crate) fn wrapper_binary_token(content: &str) -> Option<String> {
444 for line in content.lines() {
445 let t = line.trim();
446 if let Some(rest) = t.strip_prefix("LEAN_CTX_BIN=") {
447 let rest = rest.trim();
448 let tok = rest
449 .strip_prefix('"')
450 .map_or(rest, |r| r.split('"').next().unwrap_or_default());
451 if !tok.is_empty() {
452 return Some(tok.to_string());
453 }
454 }
455 if let Some(rest) = t.strip_prefix("exec ") {
456 let rest = rest.trim();
457 let tok = match rest.strip_prefix('"') {
458 Some(r) => r.split('"').next().unwrap_or_default().to_string(),
459 None => rest
460 .split_whitespace()
461 .next()
462 .unwrap_or_default()
463 .to_string(),
464 };
465 if !tok.is_empty() {
466 return Some(tok);
467 }
468 }
469 }
470 None
471}
472
473fn write_wrapper_file(path: &std::path::Path, content: &str, home: &std::path::Path) {
478 if crate::core::portable_binary::hook_binary_override().is_none()
479 && wrapper_is_portable_and_working(path, home)
480 {
481 return;
482 }
483 write_file(path, content);
484}
485
486pub fn to_bash_compatible_path(path: &str) -> String {
487 let path = match crate::core::pathutil::strip_verbatim_str(path) {
488 Some(stripped) => stripped,
489 None => path.replace('\\', "/"),
490 };
491 if path.len() >= 2 && path.as_bytes()[1] == b':' {
492 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
493 format!("/{drive}{}", &path[2..])
494 } else {
495 path
496 }
497}
498
499pub fn from_bash_to_native_path(path: &str) -> String {
502 crate::core::pathutil::normalize_tool_path(path)
503}
504
505pub fn normalize_tool_path(path: &str) -> String {
508 crate::core::pathutil::normalize_tool_path(path)
509}
510
511pub fn generate_rewrite_script(binary: &str) -> String {
512 let case_pattern = crate::rewrite_registry::bash_case_pattern();
513 let quoted_binary = shell_quoted_binary(binary);
517 format!(
518 r#"#!/usr/bin/env bash
519# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
520set -euo pipefail
521
522LEAN_CTX_BIN={quoted_binary}
523
524INPUT=$(cat)
525TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
526
527case "$TOOL" in
528 Bash|bash|PowerShell|powershell) ;;
529 *) exit 0 ;;
530esac
531
532CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
533
534if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then
535 exit 0
536fi
537
538# Skip multi-line commands: the grep/sed extraction above does not decode
539# JSON \n into real newlines, so lean-ctx -c would receive fused lines (#787).
540if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
541
542case "$CMD" in
543 {case_pattern})
544 # Shell-escape then JSON-escape (two passes)
545 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
546 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
547 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
548 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
549 ;;
550 *) exit 0 ;;
551esac
552"#
553 )
554}
555
556pub fn generate_compact_rewrite_script(binary: &str) -> String {
557 let case_pattern = crate::rewrite_registry::bash_case_pattern();
558 let quoted_binary = shell_quoted_binary(binary);
559 format!(
560 r#"#!/usr/bin/env bash
561# lean-ctx hook — rewrites shell commands
562set -euo pipefail
563LEAN_CTX_BIN={quoted_binary}
564INPUT=$(cat)
565CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
566if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then exit 0; fi
567if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
568case "$CMD" in
569 {case_pattern})
570 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
571 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
572 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
573 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
574 *) exit 0 ;;
575esac
576"#
577 )
578}
579
580const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
581# lean-ctx PreToolUse hook — all native tools pass through
582# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
583# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
584exit 0
585";
586
587const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
588# lean-ctx hook — all native tools pass through
589exit 0
590";
591
592pub fn hybrid_rules_content() -> String {
593 use crate::core::rules_canonical;
594 format!(
595 "{start}\n<!-- version: {version} -->\n\n\
596# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
597{bullets}\n\n\
598{never}\n\n\
599{end}",
600 start = rules_canonical::START_MARK,
601 version = rules_canonical::RULES_VERSION,
602 bullets = rules_canonical::BULLETS,
603 never = rules_canonical::NEVER,
604 end = rules_canonical::END_MARK,
605 )
606}
607
608pub fn replace_rules_content() -> String {
609 use crate::core::rules_canonical;
610 format!(
611 "{start}\n<!-- version: {version} -->\n\n\
612# lean-ctx \u{2014} Replace Mode (native tools denied)\n\n\
613Native Read/Grep/Glob/Bash are denied by policy. Use ONLY ctx_* MCP tools:\n\
614- ctx_read for ALL file reads (cached, 10 modes, unchanged full/auto re-reads ~13 tokens)\n\
615- ctx_shell for ALL shell commands (95+ compression patterns)\n\
616- ctx_search instead of Grep/rg (compact results)\n\
617- ctx_tree instead of ls/find (compact directory maps)\n\
618- ctx_glob instead of Glob (file pattern matching)\n\n\
619Do NOT attempt native Read, Grep, Glob, or Bash \u{2014} they will be denied.\n\n\
620{end}",
621 start = rules_canonical::START_MARK,
622 version = rules_canonical::RULES_VERSION,
623 end = rules_canonical::END_MARK,
624 )
625}
626
627pub fn install_project_rules() {
628 install_project_rules_for_agents(&[]);
629}
630
631pub fn install_project_rules_for_agents(agents: &[&str]) {
634 if crate::core::config::Config::load().rules_scope_effective()
635 == crate::core::config::RulesScope::Global
636 {
637 return;
638 }
639
640 let cwd = std::env::current_dir().unwrap_or_default();
641
642 if !is_inside_git_repo(&cwd) {
643 eprintln!(
644 " Skipping project files: not inside a git repository.\n \
645 Run this command from your project root to create CLAUDE.md / AGENTS.md."
646 );
647 return;
648 }
649
650 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
651 if cwd == home {
652 eprintln!(
653 " Skipping project files: current directory is your home folder.\n \
654 Run this command from a project directory instead."
655 );
656 return;
657 }
658
659 let all = agents.is_empty();
660 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
661
662 ensure_project_agents_integration(&cwd);
663
664 if wants("cursor") || wants("windsurf") {
665 let cursorrules = cwd.join(".cursorrules");
666 if !cursorrules.exists()
667 || !std::fs::read_to_string(&cursorrules)
668 .unwrap_or_default()
669 .contains("lean-ctx")
670 {
671 let content = cursorrules_content();
672 if cursorrules.exists() {
673 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
674 if !existing.ends_with('\n') {
675 existing.push('\n');
676 }
677 existing.push('\n');
678 existing.push_str(&content);
679 write_file(&cursorrules, &existing);
680 } else {
681 write_file(&cursorrules, &content);
682 }
683 if !mcp_server_quiet_mode() {
684 eprintln!("Created/updated .cursorrules in project root.");
685 }
686 }
687 }
688
689 if wants("claude") {
690 let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
696 if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
697 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
698 && std::fs::remove_file(&claude_rules_file).is_ok()
699 && !mcp_server_quiet_mode()
700 {
701 eprintln!(
702 "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
703 );
704 }
705
706 install_claude_project_hooks(&cwd);
707 }
708
709 if wants("codebuddy") {
710 let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
711 if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
712 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
713 && std::fs::remove_file(&codebuddy_rules_file).is_ok()
714 && !mcp_server_quiet_mode()
715 {
716 eprintln!(
717 "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
718 );
719 }
720
721 install_codebuddy_project_hooks(&cwd);
722 }
723
724 if wants("kiro") {
725 let kiro_dir = cwd.join(".kiro");
726 if kiro_dir.exists() {
727 let steering_dir = kiro_dir.join("steering");
728 let steering_file = steering_dir.join("lean-ctx.md");
729 if !steering_file.exists()
730 || !std::fs::read_to_string(&steering_file)
731 .unwrap_or_default()
732 .contains("lean-ctx")
733 {
734 let _ = std::fs::create_dir_all(&steering_dir);
735 write_file(&steering_file, &kiro_steering_content());
736 if !mcp_server_quiet_mode() {
737 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
738 }
739 }
740 }
741 }
742
743 if wants("copilot") || wants("vscode") {
744 ensure_copilot_instructions(&cwd);
745 ensure_vscode_instruction_files_setting(&cwd);
746 }
747}
748
749const PROJECT_LEAN_CTX_MD_MARKER: &str =
750 crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
751const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
752const PROJECT_AGENTS_MD: &str = "AGENTS.md";
753const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
757const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
758
759fn ensure_project_agents_integration(cwd: &std::path::Path) {
760 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
761 let desired = format!(
764 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
765 crate::rules_inject::rules_longform_markdown()
766 );
767
768 if !lean_ctx_md.exists() {
769 write_file(&lean_ctx_md, &desired);
770 } else if std::fs::read_to_string(&lean_ctx_md)
771 .unwrap_or_default()
772 .contains(PROJECT_LEAN_CTX_MD_MARKER)
773 {
774 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
775 let version_str = format!(
776 "<!-- version: {} -->",
777 crate::core::rules_canonical::RULES_VERSION
778 );
779 if !current.contains(&version_str) {
780 write_file(&lean_ctx_md, &desired);
781 }
782 }
783
784 let block = format!(
789 "{AGENTS_BLOCK_START}\n\
790## lean-ctx\n\n\
791lean-ctx is active — the MCP tools replace native equivalents.\n\
792Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
793{AGENTS_BLOCK_END}\n"
794 );
795
796 let agents_md = cwd.join(PROJECT_AGENTS_MD);
797 if !agents_md.exists() {
798 let content = format!("# Agent Instructions\n\n{block}");
799 write_file(&agents_md, &content);
800 if !mcp_server_quiet_mode() {
801 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
802 }
803 return;
804 }
805
806 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
807
808 let has_block = crate::marked_block::contains_marker_line(&existing, AGENTS_BLOCK_START);
811
812 if existing.contains("CLI-first Token Optimization for Pi") && !has_block {
813 let content = format!("# Agent Instructions\n\n{block}");
814 write_file(&agents_md, &content);
815 return;
816 }
817
818 if has_block {
819 let updated = crate::marked_block::replace_marked_block(
820 &existing,
821 AGENTS_BLOCK_START,
822 AGENTS_BLOCK_END,
823 &block,
824 );
825 if updated != existing {
826 write_file(&agents_md, &updated);
827 }
828 return;
829 }
830
831 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
832 return;
833 }
834
835 let mut out = existing;
836 if !out.ends_with('\n') {
837 out.push('\n');
838 }
839 out.push('\n');
840 out.push_str(&block);
841 write_file(&agents_md, &out);
842 if !mcp_server_quiet_mode() {
843 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
844 }
845}
846
847fn ensure_copilot_instructions(cwd: &std::path::Path) {
854 let path = cwd.join(".github").join("copilot-instructions.md");
855 let block = crate::rules_inject::rules_dedicated_markdown();
856 let start = crate::core::rules_canonical::START_MARK;
857 let end = crate::core::rules_canonical::END_MARK;
858 let owned = format!("{}\n", block.trim_end());
859
860 let existing = std::fs::read_to_string(&path).unwrap_or_default();
861 let desired = if existing.trim().is_empty() {
862 owned
863 } else if existing.contains(start) {
864 let user = crate::marked_block::remove_content(&existing, start, end);
866 if user.trim().is_empty() {
867 owned
868 } else {
869 format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
870 }
871 } else {
872 format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
874 };
875
876 if desired == existing {
877 return;
878 }
879 if let Some(parent) = path.parent()
880 && std::fs::create_dir_all(parent).is_err()
881 {
882 return;
883 }
884 write_file(&path, &desired);
885 if !mcp_server_quiet_mode() {
886 eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
887 }
888}
889
890fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
895 const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
896 let path = cwd.join(".vscode").join("settings.json");
897
898 let existing = std::fs::read_to_string(&path).unwrap_or_default();
899 let mut json = if existing.trim().is_empty() {
900 serde_json::json!({})
901 } else {
902 match crate::core::jsonc::parse_jsonc(&existing) {
903 Ok(v) if v.is_object() => v,
904 _ => return,
906 }
907 };
908 let Some(obj) = json.as_object_mut() else {
909 return;
910 };
911 if obj.contains_key(KEY) {
912 return;
913 }
914 obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
915
916 if let Some(parent) = path.parent()
917 && std::fs::create_dir_all(parent).is_err()
918 {
919 return;
920 }
921 let Ok(formatted) = serde_json::to_string_pretty(&json) else {
922 return;
923 };
924 if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
925 && !mcp_server_quiet_mode()
926 {
927 eprintln!("Set {KEY} in .vscode/settings.json.");
928 }
929}
930
931pub fn cursorrules_content() -> String {
935 let start = crate::core::rules_canonical::START_MARK;
936 let end = crate::core::rules_canonical::END_MARK;
937 let version = crate::core::rules_canonical::RULES_VERSION;
938 format!(
939 "{start}\n<!-- version: {version} -->\n\n\
940# lean-ctx\n\n\
941{bullets}\n\n\
942{never}\n\
943Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
944{end}",
945 bullets = crate::core::rules_canonical::BULLETS,
946 never = crate::core::rules_canonical::NEVER,
947 )
948}
949
950pub fn kiro_steering_content() -> String {
951 use crate::core::rules_canonical;
952 format!(
953 "---\n\
954inclusion: always\n\
955---\n\n\
956# Context Engineering Layer\n\n\
957{start}\n\
958<!-- version: {version} -->\n\n\
959The workspace has the `lean-ctx` MCP server installed. \
960You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
961{bullets}\n\n\
962{never}\n\n\
963## When to use native Kiro tools instead\n\n\
964- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
965- `strReplace` \u{2014} always use native (precise string replacement)\n\
966- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
967- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
968- `deleteFile` \u{2014} always use native\n\
969- Glob \u{2014} always use native glob\n\n\
970{end}",
971 start = rules_canonical::START_MARK,
972 version = rules_canonical::RULES_VERSION,
973 bullets = rules_canonical::BULLETS,
974 never = rules_canonical::NEVER,
975 end = rules_canonical::END_MARK,
976 )
977}
978pub(crate) fn should_register_mcp() -> bool {
985 crate::core::config::Config::load()
986 .setup
987 .should_update_mcp()
988}
989
990pub fn install_agent_hook(agent: &str, global: bool) {
991 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
992}
993
994pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
995 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
996 match agent {
997 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
998 "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
999 "cursor" => install_cursor_hook_with_mode(global, mode),
1000 "gemini" => {
1001 install_gemini_hook();
1002 if mode == HookMode::Replace {
1003 install_gemini_deny_hook(&home);
1004 }
1005 install_antigravity_cli_hook();
1011 }
1012 "grok" | "grok-build" => install_grok_mcp(),
1013 "antigravity" => install_antigravity_hook(),
1014 "antigravity-cli" => install_antigravity_cli_hook(),
1015 "augment" => install_mcp_json_agent(
1016 "Augment CLI",
1017 "~/.augment/settings.json",
1018 &crate::core::editor_registry::augment_cli_settings_path(&home),
1019 ),
1020 "codex" => {
1021 install_codex_hook();
1022 }
1023 "windsurf" => {
1024 install_windsurf_rules(global);
1025 if mode == HookMode::Replace {
1026 install_windsurf_hooks_replace(&home);
1027 }
1028 }
1029 "cline" | "roo" => install_cline_rules(global),
1030 "copilot" | "vscode" => install_copilot_hook(global),
1031 "vscode-insiders" | "commandcode" | "codewhale" | "omp" => {}
1045 "pi" => install_pi_hook_with_mode(global, mode),
1046 "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
1047 "qoderwork" => install_mcp_json_agent(
1048 "QoderWork",
1049 "~/.qoderwork/mcp.json",
1050 &home.join(".qoderwork/mcp.json"),
1051 ),
1052 "qwen" => install_mcp_json_agent(
1053 "Qwen Code",
1054 "~/.qwen/settings.json",
1055 &home.join(".qwen/settings.json"),
1056 ),
1057 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
1058 "amazonq" => install_mcp_json_agent(
1059 "Amazon Q Developer",
1060 "~/.aws/amazonq/default.json",
1061 &home.join(".aws/amazonq/default.json"),
1062 ),
1063 "jetbrains" => install_jetbrains_hook(),
1064 "kiro" => install_kiro_hook(),
1065 "verdent" => install_mcp_json_agent(
1066 "Verdent",
1067 "~/.verdent/mcp.json",
1068 &home.join(".verdent/mcp.json"),
1069 ),
1070 "opencode" => install_opencode_hook_with_mode(mode),
1071 "amp" => install_amp_hook(),
1072 "crush" => install_crush_hook_with_mode(mode),
1073 "openclaw" => install_openclaw_hook(),
1074 "hermes" => install_hermes_hook_with_mode(global, mode),
1075 "vibe" => install_vibe_hook(),
1076 "zed" => {
1077 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
1078 let binary = resolve_binary_path();
1079 let entry = full_server_entry(&binary);
1080 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
1081 }
1082 "aider" => {
1083 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
1084 }
1085 "continue" => install_mcp_json_agent(
1086 "Continue",
1087 "~/.continue/mcp.json",
1088 &home.join(".continue/mcp.json"),
1089 ),
1090 "neovim" => install_mcp_json_agent(
1091 "Neovim (mcphub.nvim)",
1092 "~/.config/mcphub/servers.json",
1093 &home.join(".config/mcphub/servers.json"),
1094 ),
1095 "emacs" => install_mcp_json_agent(
1096 "Emacs (mcp.el)",
1097 "~/.emacs.d/mcp.json",
1098 &home.join(".emacs.d/mcp.json"),
1099 ),
1100 "sublime" => install_mcp_json_agent(
1101 "Sublime Text",
1102 "~/.config/sublime-text/mcp.json",
1103 &home.join(".config/sublime-text/mcp.json"),
1104 ),
1105 _ => {
1106 eprintln!("Unknown agent: {agent}");
1107 eprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
1108 eprintln!(
1109 " claude, cline, codebuddy, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, grok,"
1110 );
1111 eprintln!(
1112 " grok-build, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi, qoder,"
1113 );
1114 eprintln!(
1115 " qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vibe, vscode, windsurf, zed"
1116 );
1117 std::process::exit(1);
1118 }
1119 }
1120}
1121
1122pub(crate) fn install_agent_hook_respecting_rules_off(agent: &str, global: bool, mode: HookMode) {
1129 if crate::core::config::Config::load().rules_injection_effective()
1130 == crate::core::config::RulesInjection::Off
1131 {
1132 install_agent_runtime_hook_with_mode(agent, global, mode);
1133 } else {
1134 install_agent_hook_with_mode(agent, global, mode);
1135 }
1136}
1137
1138pub(crate) fn install_agent_runtime_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1146 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1147
1148 match agent {
1149 "claude" | "claude-code" => {
1150 install_claude_hook_scripts(&home);
1151 install_claude_hook_config(&home);
1152 install_claude_statusline(&home);
1153
1154 if mode == HookMode::Replace {
1155 install_claude_permissions_deny_replace(&home);
1156 }
1157
1158 install_claude_permissions_allow_mcp(&home);
1159 }
1160 "codebuddy" => {
1161 install_codebuddy_hook_scripts(&home);
1162 install_codebuddy_hook_config(&home);
1163
1164 if mode == HookMode::Replace {
1165 install_codebuddy_permissions_deny_replace(&home);
1166 }
1167 }
1168 "cursor" => {
1169 install_cursor_hook_scripts(&home);
1170 install_cursor_hook_config(&home);
1171
1172 if mode == HookMode::Replace {
1173 install_cursor_deny_hook(global);
1174 }
1175 }
1176 "gemini" => {
1177 install_gemini_hook_scripts(&home);
1178 install_gemini_hook_config(&home);
1179
1180 if mode == HookMode::Replace {
1181 install_gemini_deny_hook(&home);
1182 }
1183
1184 install_antigravity_cli_hook();
1188 }
1189 "codex" => install_codex_runtime_hook(),
1190 "windsurf" => {
1191 if mode == HookMode::Replace {
1192 install_windsurf_hooks_replace(&home);
1193 } else {
1194 install_windsurf_hooks(&home);
1195 }
1196 }
1197 "copilot" | "vscode" => install_copilot_runtime_hook(global),
1198 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
1199
1200 "pi" => install_pi_hook_with_mode(global, mode),
1203
1204 "antigravity" => install_antigravity_hook(),
1207 "antigravity-cli" => install_antigravity_cli_hook(),
1208 "amp" => install_amp_hook(),
1209 "jetbrains" => install_jetbrains_hook(),
1210 "openclaw" => install_openclaw_hook(),
1211 "vibe" => install_vibe_hook(),
1212 _ => {}
1217 }
1218}
1219
1220pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
1221 match agent {
1222 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
1223 "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
1224 _ => {}
1225 }
1226}
1227
1228fn write_file(path: &std::path::Path, content: &str) {
1229 if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1232 return;
1233 }
1234 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
1235 tracing::error!("Error writing {}: {e}", path.display());
1236 }
1237}
1238
1239fn ensure_state_dir(dir: &std::path::Path) -> bool {
1248 match crate::config_io::ensure_dir(dir) {
1249 Ok(()) => true,
1250 Err(e) => {
1251 eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
1253 false
1254 }
1255 }
1256}
1257
1258fn is_inside_git_repo(path: &std::path::Path) -> bool {
1259 let mut p = path;
1260 loop {
1261 if p.join(".git").exists() {
1262 return true;
1263 }
1264 match p.parent() {
1265 Some(parent) => p = parent,
1266 None => return false,
1267 }
1268 }
1269}
1270
1271#[cfg(unix)]
1272fn make_executable(path: &PathBuf) {
1273 use std::os::unix::fs::PermissionsExt;
1274 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1275}
1276
1277#[cfg(not(unix))]
1278fn make_executable(_path: &PathBuf) {}
1279
1280pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
1293 let mut pairs = Vec::new();
1294
1295 let cfg = crate::core::config::Config::load();
1296
1297 let project_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
1298 .ok()
1299 .filter(|v| !v.trim().is_empty())
1300 .or_else(|| cfg.project_root.clone().filter(|v| !v.trim().is_empty()));
1301 if let Some(root) = project_root {
1302 pairs.push(("LEAN_CTX_PROJECT_ROOT".to_string(), root));
1303 }
1304
1305 let extra_roots = std::env::var("LEAN_CTX_EXTRA_ROOTS")
1308 .ok()
1309 .filter(|v| !v.trim().is_empty())
1310 .or_else(|| {
1311 let roots: Vec<&str> = cfg
1312 .extra_roots
1313 .iter()
1314 .map(String::as_str)
1315 .filter(|s| !s.trim().is_empty())
1316 .collect();
1317 if roots.is_empty() {
1318 return None;
1319 }
1320 std::env::join_paths(roots)
1321 .ok()
1322 .map(|s| s.to_string_lossy().to_string())
1323 });
1324 if let Some(extra) = extra_roots {
1325 pairs.push(("LEAN_CTX_EXTRA_ROOTS".to_string(), extra));
1326 }
1327
1328 pairs
1329}
1330
1331pub(crate) fn mcp_server_env_json() -> serde_json::Value {
1333 let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
1334 .into_iter()
1335 .map(|(k, v)| (k, serde_json::Value::String(v)))
1336 .collect();
1337 serde_json::Value::Object(map)
1338}
1339
1340fn full_server_entry(binary: &str) -> serde_json::Value {
1341 serde_json::json!({
1347 "command": binary,
1348 "env": mcp_server_env_json()
1349 })
1350}
1351
1352pub(crate) fn install_mcp_json_agent(
1353 name: &str,
1354 display_path: &str,
1355 config_path: &std::path::Path,
1356) {
1357 let binary = resolve_binary_path();
1358 let entry = full_server_entry(&binary);
1359 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
1360}
1361
1362#[cfg(test)]
1363mod tests;