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_cline_rules, install_codebuddy_hook_config,
181 install_codebuddy_hook_scripts, install_codebuddy_hook_with_mode,
182 install_codebuddy_permissions_deny_replace, install_codebuddy_project_hooks,
183 install_codex_hook, install_codex_runtime_hook, install_copilot_hook,
184 install_copilot_runtime_hook, install_crush_hook_with_mode, install_cursor_deny_hook,
185 install_cursor_hook_config, install_cursor_hook_scripts, install_cursor_hook_with_mode,
186 install_gemini_deny_hook, install_gemini_hook, install_gemini_hook_config,
187 install_gemini_hook_scripts, install_grok_mcp, install_hermes_hook_with_mode,
188 install_jetbrains_hook, install_kiro_hook, install_openclaw_hook,
189 install_opencode_hook_with_mode, install_pi_hook_with_mode, install_qoder_hook_with_mode,
190 install_qoder_runtime_hook_with_mode, install_vibe_hook, install_windsurf_hooks,
191 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 if mode == HookMode::Replace {
310 install_claude_permissions_deny_replace(home);
311 }
312 }
313 "codebuddy" => {
314 install_codebuddy_hook_scripts(home);
315 install_codebuddy_hook_config(home);
316 if mode == HookMode::Replace {
317 install_codebuddy_permissions_deny_replace(home);
318 }
319 }
320 "cursor" => {
321 install_cursor_hook_scripts(home);
322 install_cursor_hook_config(home);
323 if mode == HookMode::Replace {
324 install_cursor_deny_hook(true);
325 }
326 }
327 "gemini" => {
328 install_gemini_hook_scripts(home);
329 install_gemini_hook_config(home);
330 if mode == HookMode::Replace {
331 install_gemini_deny_hook(home);
332 }
333 }
334 "codex" => install_codex_runtime_hook(),
335 "windsurf" => {
336 if mode == HookMode::Replace {
337 install_windsurf_hooks_replace(home);
338 } else {
339 install_windsurf_hooks(home);
340 }
341 }
342 "copilot" => install_copilot_runtime_hook(true),
343 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
344 _ => {}
345 }
346}
347
348fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
349 std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
350}
351
352fn resolve_binary_path() -> String {
368 crate::core::portable_binary::resolve_portable_binary()
369}
370
371fn resolve_hook_command_binary() -> String {
382 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
383 return portable;
384 }
385 resolve_binary_path()
386}
387
388fn resolve_binary_path_for_bash() -> String {
389 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
390 return portable;
391 }
392 to_bash_compatible_path(&resolve_binary_path())
393}
394
395pub(crate) fn shell_quoted_binary(binary: &str) -> String {
402 let escaped = binary.replace('"', "\\\"").replace('`', "\\`");
403 format!("\"{escaped}\"")
404}
405
406fn wrapper_is_portable_and_working(path: &std::path::Path, home: &std::path::Path) -> bool {
415 std::fs::read_to_string(path)
416 .is_ok_and(|content| wrapper_content_is_portable_and_working(&content, home))
417}
418
419pub(crate) fn wrapper_content_is_portable_and_working(
420 content: &str,
421 home: &std::path::Path,
422) -> bool {
423 let Some(token) = wrapper_binary_token(content) else {
424 return false;
425 };
426 if !(token.contains("$HOME") || token.contains("${HOME}") || token.contains("%USERPROFILE%")) {
427 return false;
428 }
429 let home_s = home.to_string_lossy();
430 let expanded = token
431 .replace("${HOME}", &home_s)
432 .replace("$HOME", &home_s)
433 .replace("%USERPROFILE%", &home_s);
434 std::path::Path::new(&from_bash_to_native_path(&expanded)).exists()
435}
436
437pub(crate) fn wrapper_binary_token(content: &str) -> Option<String> {
441 for line in content.lines() {
442 let t = line.trim();
443 if let Some(rest) = t.strip_prefix("LEAN_CTX_BIN=") {
444 let rest = rest.trim();
445 let tok = rest
446 .strip_prefix('"')
447 .map_or(rest, |r| r.split('"').next().unwrap_or_default());
448 if !tok.is_empty() {
449 return Some(tok.to_string());
450 }
451 }
452 if let Some(rest) = t.strip_prefix("exec ") {
453 let rest = rest.trim();
454 let tok = match rest.strip_prefix('"') {
455 Some(r) => r.split('"').next().unwrap_or_default().to_string(),
456 None => rest
457 .split_whitespace()
458 .next()
459 .unwrap_or_default()
460 .to_string(),
461 };
462 if !tok.is_empty() {
463 return Some(tok);
464 }
465 }
466 }
467 None
468}
469
470fn write_wrapper_file(path: &std::path::Path, content: &str, home: &std::path::Path) {
475 if crate::core::portable_binary::hook_binary_override().is_none()
476 && wrapper_is_portable_and_working(path, home)
477 {
478 return;
479 }
480 write_file(path, content);
481}
482
483pub fn to_bash_compatible_path(path: &str) -> String {
484 let path = match crate::core::pathutil::strip_verbatim_str(path) {
485 Some(stripped) => stripped,
486 None => path.replace('\\', "/"),
487 };
488 if path.len() >= 2 && path.as_bytes()[1] == b':' {
489 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
490 format!("/{drive}{}", &path[2..])
491 } else {
492 path
493 }
494}
495
496pub fn from_bash_to_native_path(path: &str) -> String {
499 crate::core::pathutil::normalize_tool_path(path)
500}
501
502pub fn normalize_tool_path(path: &str) -> String {
505 crate::core::pathutil::normalize_tool_path(path)
506}
507
508pub fn generate_rewrite_script(binary: &str) -> String {
509 let case_pattern = crate::rewrite_registry::bash_case_pattern();
510 let quoted_binary = shell_quoted_binary(binary);
514 format!(
515 r#"#!/usr/bin/env bash
516# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
517set -euo pipefail
518
519LEAN_CTX_BIN={quoted_binary}
520
521INPUT=$(cat)
522TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
523
524case "$TOOL" in
525 Bash|bash|PowerShell|powershell) ;;
526 *) exit 0 ;;
527esac
528
529CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
530
531if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then
532 exit 0
533fi
534
535# Skip multi-line commands: the grep/sed extraction above does not decode
536# JSON \n into real newlines, so lean-ctx -c would receive fused lines (#787).
537if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
538
539case "$CMD" in
540 {case_pattern})
541 # Shell-escape then JSON-escape (two passes)
542 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
543 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
544 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
545 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
546 ;;
547 *) exit 0 ;;
548esac
549"#
550 )
551}
552
553pub fn generate_compact_rewrite_script(binary: &str) -> String {
554 let case_pattern = crate::rewrite_registry::bash_case_pattern();
555 let quoted_binary = shell_quoted_binary(binary);
556 format!(
557 r#"#!/usr/bin/env bash
558# lean-ctx hook — rewrites shell commands
559set -euo pipefail
560LEAN_CTX_BIN={quoted_binary}
561INPUT=$(cat)
562CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
563if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then exit 0; fi
564if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
565case "$CMD" in
566 {case_pattern})
567 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
568 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
569 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
570 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
571 *) exit 0 ;;
572esac
573"#
574 )
575}
576
577const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
578# lean-ctx PreToolUse hook — all native tools pass through
579# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
580# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
581exit 0
582";
583
584const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
585# lean-ctx hook — all native tools pass through
586exit 0
587";
588
589pub fn hybrid_rules_content() -> String {
590 use crate::core::rules_canonical;
591 format!(
592 "{start}\n<!-- version: {version} -->\n\n\
593# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
594{bullets}\n\n\
595{never}\n\n\
596{end}",
597 start = rules_canonical::START_MARK,
598 version = rules_canonical::RULES_VERSION,
599 bullets = rules_canonical::BULLETS,
600 never = rules_canonical::NEVER,
601 end = rules_canonical::END_MARK,
602 )
603}
604
605pub fn replace_rules_content() -> String {
606 use crate::core::rules_canonical;
607 format!(
608 "{start}\n<!-- version: {version} -->\n\n\
609# lean-ctx \u{2014} Replace Mode (native tools denied)\n\n\
610Native Read/Grep/Glob/Bash are denied by policy. Use ONLY ctx_* MCP tools:\n\
611- ctx_read for ALL file reads (cached, 10 modes, unchanged full/auto re-reads ~13 tokens)\n\
612- ctx_shell for ALL shell commands (95+ compression patterns)\n\
613- ctx_search instead of Grep/rg (compact results)\n\
614- ctx_tree instead of ls/find (compact directory maps)\n\
615- ctx_glob instead of Glob (file pattern matching)\n\n\
616Do NOT attempt native Read, Grep, Glob, or Bash \u{2014} they will be denied.\n\n\
617{end}",
618 start = rules_canonical::START_MARK,
619 version = rules_canonical::RULES_VERSION,
620 end = rules_canonical::END_MARK,
621 )
622}
623
624pub fn install_project_rules() {
625 install_project_rules_for_agents(&[]);
626}
627
628pub fn install_project_rules_for_agents(agents: &[&str]) {
631 if crate::core::config::Config::load().rules_scope_effective()
632 == crate::core::config::RulesScope::Global
633 {
634 return;
635 }
636
637 let cwd = std::env::current_dir().unwrap_or_default();
638
639 if !is_inside_git_repo(&cwd) {
640 eprintln!(
641 " Skipping project files: not inside a git repository.\n \
642 Run this command from your project root to create CLAUDE.md / AGENTS.md."
643 );
644 return;
645 }
646
647 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
648 if cwd == home {
649 eprintln!(
650 " Skipping project files: current directory is your home folder.\n \
651 Run this command from a project directory instead."
652 );
653 return;
654 }
655
656 let all = agents.is_empty();
657 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
658
659 ensure_project_agents_integration(&cwd);
660
661 if wants("cursor") || wants("windsurf") {
662 let cursorrules = cwd.join(".cursorrules");
663 if !cursorrules.exists()
664 || !std::fs::read_to_string(&cursorrules)
665 .unwrap_or_default()
666 .contains("lean-ctx")
667 {
668 let content = cursorrules_content();
669 if cursorrules.exists() {
670 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
671 if !existing.ends_with('\n') {
672 existing.push('\n');
673 }
674 existing.push('\n');
675 existing.push_str(&content);
676 write_file(&cursorrules, &existing);
677 } else {
678 write_file(&cursorrules, &content);
679 }
680 if !mcp_server_quiet_mode() {
681 eprintln!("Created/updated .cursorrules in project root.");
682 }
683 }
684 }
685
686 if wants("claude") {
687 let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
693 if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
694 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
695 && std::fs::remove_file(&claude_rules_file).is_ok()
696 && !mcp_server_quiet_mode()
697 {
698 eprintln!(
699 "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
700 );
701 }
702
703 install_claude_project_hooks(&cwd);
704 }
705
706 if wants("codebuddy") {
707 let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
708 if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
709 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
710 && std::fs::remove_file(&codebuddy_rules_file).is_ok()
711 && !mcp_server_quiet_mode()
712 {
713 eprintln!(
714 "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
715 );
716 }
717
718 install_codebuddy_project_hooks(&cwd);
719 }
720
721 if wants("kiro") {
722 let kiro_dir = cwd.join(".kiro");
723 if kiro_dir.exists() {
724 let steering_dir = kiro_dir.join("steering");
725 let steering_file = steering_dir.join("lean-ctx.md");
726 if !steering_file.exists()
727 || !std::fs::read_to_string(&steering_file)
728 .unwrap_or_default()
729 .contains("lean-ctx")
730 {
731 let _ = std::fs::create_dir_all(&steering_dir);
732 write_file(&steering_file, &kiro_steering_content());
733 if !mcp_server_quiet_mode() {
734 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
735 }
736 }
737 }
738 }
739
740 if wants("copilot") || wants("vscode") {
741 ensure_copilot_instructions(&cwd);
742 ensure_vscode_instruction_files_setting(&cwd);
743 }
744}
745
746const PROJECT_LEAN_CTX_MD_MARKER: &str =
747 crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
748const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
749const PROJECT_AGENTS_MD: &str = "AGENTS.md";
750const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
754const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
755
756fn ensure_project_agents_integration(cwd: &std::path::Path) {
757 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
758 let desired = format!(
761 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
762 crate::rules_inject::rules_longform_markdown()
763 );
764
765 if !lean_ctx_md.exists() {
766 write_file(&lean_ctx_md, &desired);
767 } else if std::fs::read_to_string(&lean_ctx_md)
768 .unwrap_or_default()
769 .contains(PROJECT_LEAN_CTX_MD_MARKER)
770 {
771 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
772 let version_str = format!(
773 "<!-- version: {} -->",
774 crate::core::rules_canonical::RULES_VERSION
775 );
776 if !current.contains(&version_str) {
777 write_file(&lean_ctx_md, &desired);
778 }
779 }
780
781 let block = format!(
786 "{AGENTS_BLOCK_START}\n\
787## lean-ctx\n\n\
788lean-ctx is active — the MCP tools replace native equivalents.\n\
789Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
790{AGENTS_BLOCK_END}\n"
791 );
792
793 let agents_md = cwd.join(PROJECT_AGENTS_MD);
794 if !agents_md.exists() {
795 let content = format!("# Agent Instructions\n\n{block}");
796 write_file(&agents_md, &content);
797 if !mcp_server_quiet_mode() {
798 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
799 }
800 return;
801 }
802
803 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
804
805 let has_block = crate::marked_block::contains_marker_line(&existing, AGENTS_BLOCK_START);
808
809 if existing.contains("CLI-first Token Optimization for Pi") && !has_block {
810 let content = format!("# Agent Instructions\n\n{block}");
811 write_file(&agents_md, &content);
812 return;
813 }
814
815 if has_block {
816 let updated = crate::marked_block::replace_marked_block(
817 &existing,
818 AGENTS_BLOCK_START,
819 AGENTS_BLOCK_END,
820 &block,
821 );
822 if updated != existing {
823 write_file(&agents_md, &updated);
824 }
825 return;
826 }
827
828 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
829 return;
830 }
831
832 let mut out = existing;
833 if !out.ends_with('\n') {
834 out.push('\n');
835 }
836 out.push('\n');
837 out.push_str(&block);
838 write_file(&agents_md, &out);
839 if !mcp_server_quiet_mode() {
840 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
841 }
842}
843
844fn ensure_copilot_instructions(cwd: &std::path::Path) {
851 let path = cwd.join(".github").join("copilot-instructions.md");
852 let block = crate::rules_inject::rules_dedicated_markdown();
853 let start = crate::core::rules_canonical::START_MARK;
854 let end = crate::core::rules_canonical::END_MARK;
855 let owned = format!("{}\n", block.trim_end());
856
857 let existing = std::fs::read_to_string(&path).unwrap_or_default();
858 let desired = if existing.trim().is_empty() {
859 owned
860 } else if existing.contains(start) {
861 let user = crate::marked_block::remove_content(&existing, start, end);
863 if user.trim().is_empty() {
864 owned
865 } else {
866 format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
867 }
868 } else {
869 format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
871 };
872
873 if desired == existing {
874 return;
875 }
876 if let Some(parent) = path.parent()
877 && std::fs::create_dir_all(parent).is_err()
878 {
879 return;
880 }
881 write_file(&path, &desired);
882 if !mcp_server_quiet_mode() {
883 eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
884 }
885}
886
887fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
892 const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
893 let path = cwd.join(".vscode").join("settings.json");
894
895 let existing = std::fs::read_to_string(&path).unwrap_or_default();
896 let mut json = if existing.trim().is_empty() {
897 serde_json::json!({})
898 } else {
899 match crate::core::jsonc::parse_jsonc(&existing) {
900 Ok(v) if v.is_object() => v,
901 _ => return,
903 }
904 };
905 let Some(obj) = json.as_object_mut() else {
906 return;
907 };
908 if obj.contains_key(KEY) {
909 return;
910 }
911 obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
912
913 if let Some(parent) = path.parent()
914 && std::fs::create_dir_all(parent).is_err()
915 {
916 return;
917 }
918 let Ok(formatted) = serde_json::to_string_pretty(&json) else {
919 return;
920 };
921 if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
922 && !mcp_server_quiet_mode()
923 {
924 eprintln!("Set {KEY} in .vscode/settings.json.");
925 }
926}
927
928pub fn cursorrules_content() -> String {
932 let start = crate::core::rules_canonical::START_MARK;
933 let end = crate::core::rules_canonical::END_MARK;
934 let version = crate::core::rules_canonical::RULES_VERSION;
935 format!(
936 "{start}\n<!-- version: {version} -->\n\n\
937# lean-ctx\n\n\
938{bullets}\n\n\
939{never}\n\
940Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
941{end}",
942 bullets = crate::core::rules_canonical::BULLETS,
943 never = crate::core::rules_canonical::NEVER,
944 )
945}
946
947pub fn kiro_steering_content() -> String {
948 use crate::core::rules_canonical;
949 format!(
950 "---\n\
951inclusion: always\n\
952---\n\n\
953# Context Engineering Layer\n\n\
954{start}\n\
955<!-- version: {version} -->\n\n\
956The workspace has the `lean-ctx` MCP server installed. \
957You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
958{bullets}\n\n\
959{never}\n\n\
960## When to use native Kiro tools instead\n\n\
961- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
962- `strReplace` \u{2014} always use native (precise string replacement)\n\
963- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
964- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
965- `deleteFile` \u{2014} always use native\n\
966- Glob \u{2014} always use native glob\n\n\
967{end}",
968 start = rules_canonical::START_MARK,
969 version = rules_canonical::RULES_VERSION,
970 bullets = rules_canonical::BULLETS,
971 never = rules_canonical::NEVER,
972 end = rules_canonical::END_MARK,
973 )
974}
975pub(crate) fn should_register_mcp() -> bool {
982 crate::core::config::Config::load()
983 .setup
984 .should_update_mcp()
985}
986
987pub fn install_agent_hook(agent: &str, global: bool) {
988 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
989}
990
991pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
992 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
993 match agent {
994 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
995 "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
996 "cursor" => install_cursor_hook_with_mode(global, mode),
997 "gemini" => {
998 install_gemini_hook();
999 if mode == HookMode::Replace {
1000 install_gemini_deny_hook(&home);
1001 }
1002 install_antigravity_cli_hook();
1008 }
1009 "grok" | "grok-build" => install_grok_mcp(),
1010 "antigravity" => install_antigravity_hook(),
1011 "antigravity-cli" => install_antigravity_cli_hook(),
1012 "augment" => install_mcp_json_agent(
1013 "Augment CLI",
1014 "~/.augment/settings.json",
1015 &crate::core::editor_registry::augment_cli_settings_path(&home),
1016 ),
1017 "codex" => {
1018 install_codex_hook();
1019 }
1020 "windsurf" => {
1021 install_windsurf_rules(global);
1022 if mode == HookMode::Replace {
1023 install_windsurf_hooks_replace(&home);
1024 }
1025 }
1026 "cline" | "roo" => install_cline_rules(global),
1027 "copilot" | "vscode" => install_copilot_hook(global),
1028 "vscode-insiders" | "commandcode" | "codewhale" | "omp" => {}
1042 "pi" => install_pi_hook_with_mode(global, mode),
1043 "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
1044 "qoderwork" => install_mcp_json_agent(
1045 "QoderWork",
1046 "~/.qoderwork/mcp.json",
1047 &home.join(".qoderwork/mcp.json"),
1048 ),
1049 "qwen" => install_mcp_json_agent(
1050 "Qwen Code",
1051 "~/.qwen/settings.json",
1052 &home.join(".qwen/settings.json"),
1053 ),
1054 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
1055 "amazonq" => install_mcp_json_agent(
1056 "Amazon Q Developer",
1057 "~/.aws/amazonq/default.json",
1058 &home.join(".aws/amazonq/default.json"),
1059 ),
1060 "jetbrains" => install_jetbrains_hook(),
1061 "kiro" => install_kiro_hook(),
1062 "verdent" => install_mcp_json_agent(
1063 "Verdent",
1064 "~/.verdent/mcp.json",
1065 &home.join(".verdent/mcp.json"),
1066 ),
1067 "opencode" => install_opencode_hook_with_mode(mode),
1068 "amp" => install_amp_hook(),
1069 "crush" => install_crush_hook_with_mode(mode),
1070 "openclaw" => install_openclaw_hook(),
1071 "hermes" => install_hermes_hook_with_mode(global, mode),
1072 "vibe" => install_vibe_hook(),
1073 "zed" => {
1074 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
1075 let binary = resolve_binary_path();
1076 let entry = full_server_entry(&binary);
1077 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
1078 }
1079 "aider" => {
1080 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
1081 }
1082 "continue" => install_mcp_json_agent(
1083 "Continue",
1084 "~/.continue/mcp.json",
1085 &home.join(".continue/mcp.json"),
1086 ),
1087 "neovim" => install_mcp_json_agent(
1088 "Neovim (mcphub.nvim)",
1089 "~/.config/mcphub/servers.json",
1090 &home.join(".config/mcphub/servers.json"),
1091 ),
1092 "emacs" => install_mcp_json_agent(
1093 "Emacs (mcp.el)",
1094 "~/.emacs.d/mcp.json",
1095 &home.join(".emacs.d/mcp.json"),
1096 ),
1097 "sublime" => install_mcp_json_agent(
1098 "Sublime Text",
1099 "~/.config/sublime-text/mcp.json",
1100 &home.join(".config/sublime-text/mcp.json"),
1101 ),
1102 _ => {
1103 eprintln!("Unknown agent: {agent}");
1104 eprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
1105 eprintln!(
1106 " claude, cline, codebuddy, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, grok,"
1107 );
1108 eprintln!(
1109 " grok-build, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi, qoder,"
1110 );
1111 eprintln!(
1112 " qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vibe, vscode, windsurf, zed"
1113 );
1114 std::process::exit(1);
1115 }
1116 }
1117}
1118
1119pub(crate) fn install_agent_hook_respecting_rules_off(agent: &str, global: bool, mode: HookMode) {
1126 if crate::core::config::Config::load().rules_injection_effective()
1127 == crate::core::config::RulesInjection::Off
1128 {
1129 install_agent_runtime_hook_with_mode(agent, global, mode);
1130 } else {
1131 install_agent_hook_with_mode(agent, global, mode);
1132 }
1133}
1134
1135pub(crate) fn install_agent_runtime_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1143 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1144
1145 match agent {
1146 "claude" | "claude-code" => {
1147 install_claude_hook_scripts(&home);
1148 install_claude_hook_config(&home);
1149
1150 if mode == HookMode::Replace {
1151 install_claude_permissions_deny_replace(&home);
1152 }
1153
1154 install_claude_permissions_allow_mcp(&home);
1155 }
1156 "codebuddy" => {
1157 install_codebuddy_hook_scripts(&home);
1158 install_codebuddy_hook_config(&home);
1159
1160 if mode == HookMode::Replace {
1161 install_codebuddy_permissions_deny_replace(&home);
1162 }
1163 }
1164 "cursor" => {
1165 install_cursor_hook_scripts(&home);
1166 install_cursor_hook_config(&home);
1167
1168 if mode == HookMode::Replace {
1169 install_cursor_deny_hook(global);
1170 }
1171 }
1172 "gemini" => {
1173 install_gemini_hook_scripts(&home);
1174 install_gemini_hook_config(&home);
1175
1176 if mode == HookMode::Replace {
1177 install_gemini_deny_hook(&home);
1178 }
1179
1180 install_antigravity_cli_hook();
1184 }
1185 "codex" => install_codex_runtime_hook(),
1186 "windsurf" => {
1187 if mode == HookMode::Replace {
1188 install_windsurf_hooks_replace(&home);
1189 } else {
1190 install_windsurf_hooks(&home);
1191 }
1192 }
1193 "copilot" | "vscode" => install_copilot_runtime_hook(global),
1194 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
1195
1196 "pi" => install_pi_hook_with_mode(global, mode),
1199
1200 "antigravity" => install_antigravity_hook(),
1203 "antigravity-cli" => install_antigravity_cli_hook(),
1204 "amp" => install_amp_hook(),
1205 "jetbrains" => install_jetbrains_hook(),
1206 "openclaw" => install_openclaw_hook(),
1207 "vibe" => install_vibe_hook(),
1208 _ => {}
1213 }
1214}
1215
1216pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
1217 match agent {
1218 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
1219 "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
1220 _ => {}
1221 }
1222}
1223
1224fn write_file(path: &std::path::Path, content: &str) {
1225 if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1228 return;
1229 }
1230 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
1231 tracing::error!("Error writing {}: {e}", path.display());
1232 }
1233}
1234
1235fn ensure_state_dir(dir: &std::path::Path) -> bool {
1244 match crate::config_io::ensure_dir(dir) {
1245 Ok(()) => true,
1246 Err(e) => {
1247 eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
1249 false
1250 }
1251 }
1252}
1253
1254fn is_inside_git_repo(path: &std::path::Path) -> bool {
1255 let mut p = path;
1256 loop {
1257 if p.join(".git").exists() {
1258 return true;
1259 }
1260 match p.parent() {
1261 Some(parent) => p = parent,
1262 None => return false,
1263 }
1264 }
1265}
1266
1267#[cfg(unix)]
1268fn make_executable(path: &PathBuf) {
1269 use std::os::unix::fs::PermissionsExt;
1270 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1271}
1272
1273#[cfg(not(unix))]
1274fn make_executable(_path: &PathBuf) {}
1275
1276pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
1289 let mut pairs = Vec::new();
1290
1291 let cfg = crate::core::config::Config::load();
1292
1293 let project_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
1294 .ok()
1295 .filter(|v| !v.trim().is_empty())
1296 .or_else(|| cfg.project_root.clone().filter(|v| !v.trim().is_empty()));
1297 if let Some(root) = project_root {
1298 pairs.push(("LEAN_CTX_PROJECT_ROOT".to_string(), root));
1299 }
1300
1301 let extra_roots = std::env::var("LEAN_CTX_EXTRA_ROOTS")
1304 .ok()
1305 .filter(|v| !v.trim().is_empty())
1306 .or_else(|| {
1307 let roots: Vec<&str> = cfg
1308 .extra_roots
1309 .iter()
1310 .map(String::as_str)
1311 .filter(|s| !s.trim().is_empty())
1312 .collect();
1313 if roots.is_empty() {
1314 return None;
1315 }
1316 std::env::join_paths(roots)
1317 .ok()
1318 .map(|s| s.to_string_lossy().to_string())
1319 });
1320 if let Some(extra) = extra_roots {
1321 pairs.push(("LEAN_CTX_EXTRA_ROOTS".to_string(), extra));
1322 }
1323
1324 pairs
1325}
1326
1327pub(crate) fn mcp_server_env_json() -> serde_json::Value {
1329 let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
1330 .into_iter()
1331 .map(|(k, v)| (k, serde_json::Value::String(v)))
1332 .collect();
1333 serde_json::Value::Object(map)
1334}
1335
1336fn full_server_entry(binary: &str) -> serde_json::Value {
1337 serde_json::json!({
1343 "command": binary,
1344 "env": mcp_server_env_json()
1345 })
1346}
1347
1348pub(crate) fn install_mcp_json_agent(
1349 name: &str,
1350 display_path: &str,
1351 config_path: &std::path::Path,
1352) {
1353 let binary = resolve_binary_path();
1354 let entry = full_server_entry(&binary);
1355 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
1356}
1357
1358#[cfg(test)]
1359mod tests;