1use std::path::PathBuf;
2
3pub mod agents;
4pub(crate) mod project_pins;
5mod support;
6pub(crate) use project_pins::strip_project_scoped_env_toml;
7
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum HookMode {
17 #[default]
18 Mcp,
19 Hybrid,
20 Replace,
21}
22
23impl std::fmt::Display for HookMode {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 match self {
26 Self::Mcp => write!(f, "MCP"),
27 Self::Hybrid => write!(f, "Hybrid"),
28 Self::Replace => write!(f, "Replace"),
29 }
30 }
31}
32
33impl HookMode {
34 pub fn from_str_loose(s: &str) -> Option<Self> {
35 match s.to_lowercase().replace('-', "").as_str() {
36 "mcp" => Some(Self::Mcp),
37 "hybrid" => Some(Self::Hybrid),
38 "replace" => Some(Self::Replace),
39 _ => None,
40 }
41 }
42
43 pub fn cap_at_hybrid(self) -> Self {
45 if matches!(self, Self::Replace) {
46 Self::Hybrid
47 } else {
48 self
49 }
50 }
51
52 pub fn description(&self) -> &'static str {
53 match self {
54 Self::Mcp => "MCP server only (extension/plugin-based agents without reliable shell)",
55 Self::Hybrid => "MCP server + shell hooks for command compression (best of both)",
56 Self::Replace => {
57 "Native tools denied — lean-ctx MCP is the only path (zero tool drift)"
58 }
59 }
60 }
61}
62
63pub const REPLACE_AGENTS: &[&str] = &[
71 "cursor",
72 "claude",
73 "claude-code",
74 "codebuddy",
75 "codex",
76 "windsurf",
77 "opencode",
78 "gemini",
79];
80
81pub const HYBRID_AGENTS: &[&str] = &[
84 "cursor",
85 "gemini",
86 "codex",
87 "claude",
88 "claude-code",
89 "crush",
90 "hermes",
91 "opencode",
92 "openclaw",
93 "pi",
94 "omp",
95 "qoder",
96 "qodercli",
97 "windsurf",
98 "amp",
99 "cline",
100 "roo",
101 "copilot",
102 "kiro",
103 "qwen",
104 "trae",
105 "antigravity",
106 "antigravity-cli",
107 "amazonq",
108 "verdent",
109];
110
111pub const MCP_ONLY_AGENTS: &[&str] = &["codewhale"];
121
122pub fn is_supported_agent(agent: &str) -> bool {
127 let key = agent.to_ascii_lowercase();
128 REPLACE_AGENTS.contains(&key.as_str())
129 || HYBRID_AGENTS.contains(&key.as_str())
130 || MCP_ONLY_AGENTS.contains(&key.as_str())
131}
132
133pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
145 if let Some(override_mode) = crate::core::config::Config::load().hook_mode_override() {
146 return if is_deny_suppressed() {
147 override_mode.cap_at_hybrid()
148 } else {
149 override_mode
150 };
151 }
152 if REPLACE_AGENTS.contains(&agent_key) || HYBRID_AGENTS.contains(&agent_key) {
153 HookMode::Hybrid
154 } else {
155 HookMode::Mcp
156 }
157}
158
159#[must_use]
164pub fn replace_mode_chosen() -> bool {
165 crate::core::config::Config::load().hook_mode_override() == Some(HookMode::Replace)
166 && !is_deny_suppressed()
167}
168
169#[must_use]
181pub fn claude_hides_native_search(mode: HookMode) -> bool {
182 match mode {
183 HookMode::Replace => true,
184 HookMode::Hybrid => {
185 crate::core::config::Config::load()
186 .hook_mode_override()
187 .is_none()
188 && !is_deny_suppressed()
189 }
190 HookMode::Mcp => false,
191 }
192}
193
194fn is_deny_suppressed() -> bool {
196 if std::env::var("LEAN_CTX_DISABLED").is_ok() {
197 return true;
198 }
199 if matches!(std::env::var("LEAN_CTX_SHADOW_MODE"), Ok(v) if v.trim() == "false" || v.trim() == "0")
200 {
201 return true;
202 }
203 if matches!(std::env::var("LEAN_CTX_HEAL"), Ok(v) if v.trim().eq_ignore_ascii_case("off") || v.trim() == "0")
204 {
205 return true;
206 }
207 let cfg = crate::core::config::Config::load();
208 !cfg.shadow_mode
209}
210use agents::{
211 install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
212 install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
213 install_claude_permissions_allow_mcp, install_claude_permissions_deny_replace,
214 install_claude_project_hooks, install_claude_statusline, install_cline_rules,
215 install_codebuddy_hook_config, install_codebuddy_hook_scripts,
216 install_codebuddy_hook_with_mode, install_codebuddy_permissions_deny_replace,
217 install_codebuddy_project_hooks, install_codex_hook, install_codex_runtime_hook,
218 install_copilot_hook, install_copilot_runtime_hook, install_crush_hook_with_mode,
219 install_cursor_deny_hook, install_cursor_hook_config, install_cursor_hook_scripts,
220 install_cursor_hook_with_mode, install_gemini_deny_hook, install_gemini_hook,
221 install_gemini_hook_config, install_gemini_hook_scripts, install_grok_mcp,
222 install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
223 install_openclaw_hook, install_opencode_hook_with_mode, install_pi_hook_with_mode,
224 install_qoder_hook_with_mode, install_qoder_runtime_hook_with_mode, install_vibe_hook,
225 install_windsurf_hooks, install_windsurf_hooks_replace, install_windsurf_rules,
226};
227use support::{
228 ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
229 upsert_lean_ctx_codex_hook_entries,
230};
231
232fn mcp_server_quiet_mode() -> bool {
233 crate::core::runtime_flags::mcp_server_enabled() || crate::core::runtime_flags::quiet_enabled()
234}
235
236const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
244 "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder", "qodercli",
245];
246
247#[cfg(test)]
252const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
253 "claude-code",
255 "pi",
257 "omp",
259 "cline",
262 "roo",
263 "kiro",
264 "antigravity",
267 "antigravity-cli",
268 "amp",
269 "crush",
270 "hermes",
271 "opencode",
272 "openclaw",
273 "qwen",
274 "trae",
275 "amazonq",
276 "verdent",
277];
278
279pub fn refresh_installed_hooks() {
288 if !crate::core::config::Config::load().setup.manage_hooks {
289 tracing::debug!("hook refresh skipped: [setup] manage_hooks = false");
290 return;
291 }
292 let Some(home) = crate::core::home::resolve_home_dir() else {
293 return;
294 };
295 agents::release_opencode_native_tool_gates(&home);
299 for agent in REFRESHABLE_HOOK_AGENTS {
300 if hooks_installed_for(agent, &home) {
301 refresh_agent_hooks(agent, &home);
302 }
303 }
304}
305
306pub(crate) fn installed_hook_mode(agent: &str, home: &std::path::Path) -> Option<HookMode> {
309 hooks_installed_for(agent, home).then(|| recommend_hook_mode(agent))
310}
311
312fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
314 match agent {
315 "claude" => {
316 let dir = crate::setup::claude_config_dir(home);
317 dir.join("hooks/lean-ctx-rewrite.sh").exists()
318 || file_contains_lean_ctx(&dir.join("settings.json"))
319 }
320 "codebuddy" => {
321 let dir = crate::core::editor_registry::codebuddy_state_dir(home);
322 dir.join("hooks/lean-ctx-rewrite.sh").exists()
323 || file_contains_lean_ctx(&dir.join("settings.json"))
324 }
325 "cursor" => {
326 home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
327 || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
328 }
329 "gemini" => {
330 home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
331 .exists()
332 || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
333 }
334 "codex" => {
335 let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
336 dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
337 || file_contains_lean_ctx(&dir.join("hooks.json"))
338 }
339 "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
340 "copilot" => {
341 file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
344 || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
345 }
346 "qoder" | "qodercli" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
347 _ => false,
348 }
349}
350
351fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
356 let mode = recommend_hook_mode(agent);
357 match agent {
358 "claude" => {
359 install_claude_hook_scripts(home);
360 install_claude_hook_config(home);
361 install_claude_statusline(home);
364 if claude_hides_native_search(mode) {
365 install_claude_permissions_deny_replace(home);
366 }
367 }
368 "codebuddy" => {
369 install_codebuddy_hook_scripts(home);
370 install_codebuddy_hook_config(home);
371 if claude_hides_native_search(mode) {
372 install_codebuddy_permissions_deny_replace(home, mode);
373 }
374 }
375 "cursor" => {
376 install_cursor_hook_scripts(home);
377 install_cursor_hook_config(home);
378 if mode == HookMode::Replace {
379 install_cursor_deny_hook(true);
380 }
381 }
382 "gemini" => {
383 install_gemini_hook_scripts(home);
384 install_gemini_hook_config(home);
385 if mode == HookMode::Replace {
386 install_gemini_deny_hook(home);
387 }
388 }
389 "codex" => install_codex_runtime_hook(),
390 "windsurf" => {
391 if mode == HookMode::Replace {
392 install_windsurf_hooks_replace(home);
393 } else {
394 install_windsurf_hooks(home);
395 }
396 }
397 "copilot" => install_copilot_runtime_hook(true),
398 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
399 _ => {}
400 }
401}
402
403fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
404 std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
405}
406
407fn resolve_binary_path() -> String {
423 crate::core::portable_binary::resolve_agent_binary()
424}
425
426fn resolve_hook_command_binary() -> String {
437 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
438 return portable;
439 }
440 resolve_binary_path()
441}
442
443fn resolve_binary_path_for_bash() -> String {
444 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
445 return portable;
446 }
447 to_bash_compatible_path(&resolve_binary_path())
448}
449
450pub(crate) fn shell_quoted_binary(binary: &str) -> String {
457 let escaped = binary.replace('"', "\\\"").replace('`', "\\`");
458 format!("\"{escaped}\"")
459}
460
461fn wrapper_is_portable_and_working(path: &std::path::Path, home: &std::path::Path) -> bool {
470 std::fs::read_to_string(path)
471 .is_ok_and(|content| wrapper_content_is_portable_and_working(&content, home))
472}
473
474pub(crate) fn wrapper_content_is_portable_and_working(
475 content: &str,
476 home: &std::path::Path,
477) -> bool {
478 let Some(token) = wrapper_binary_token(content) else {
479 return false;
480 };
481 if !(token.contains("$HOME") || token.contains("${HOME}") || token.contains("%USERPROFILE%")) {
482 return false;
483 }
484 let home_s = home.to_string_lossy();
485 let expanded = token
486 .replace("${HOME}", &home_s)
487 .replace("$HOME", &home_s)
488 .replace("%USERPROFILE%", &home_s);
489 std::path::Path::new(&from_bash_to_native_path(&expanded)).exists()
490}
491
492pub(crate) fn wrapper_binary_token(content: &str) -> Option<String> {
496 for line in content.lines() {
497 let t = line.trim();
498 if let Some(rest) = t.strip_prefix("LEAN_CTX_BIN=") {
499 let rest = rest.trim();
500 let tok = rest
501 .strip_prefix('"')
502 .map_or(rest, |r| r.split('"').next().unwrap_or_default());
503 if !tok.is_empty() {
504 return Some(tok.to_string());
505 }
506 }
507 if let Some(rest) = t.strip_prefix("exec ") {
508 let rest = rest.trim();
509 let tok = match rest.strip_prefix('"') {
510 Some(r) => r.split('"').next().unwrap_or_default().to_string(),
511 None => rest
512 .split_whitespace()
513 .next()
514 .unwrap_or_default()
515 .to_string(),
516 };
517 if !tok.is_empty() {
518 return Some(tok);
519 }
520 }
521 }
522 None
523}
524
525fn write_wrapper_file(path: &std::path::Path, content: &str, home: &std::path::Path) {
530 if crate::core::portable_binary::hook_binary_override().is_none()
531 && wrapper_is_portable_and_working(path, home)
532 {
533 return;
534 }
535 write_file(path, content);
536}
537
538pub fn to_bash_compatible_path(path: &str) -> String {
539 let path = match crate::core::pathutil::strip_verbatim_str(path) {
540 Some(stripped) => stripped,
541 None => path.replace('\\', "/"),
542 };
543 if path.len() >= 2 && path.as_bytes()[1] == b':' {
544 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
545 format!("/{drive}{}", &path[2..])
546 } else {
547 path
548 }
549}
550
551pub fn from_bash_to_native_path(path: &str) -> String {
554 crate::core::pathutil::normalize_tool_path(path)
555}
556
557pub fn normalize_tool_path(path: &str) -> String {
560 crate::core::pathutil::normalize_tool_path(path)
561}
562
563pub fn generate_rewrite_script(binary: &str) -> String {
564 let case_pattern = crate::rewrite_registry::bash_case_pattern();
565 let quoted_binary = shell_quoted_binary(binary);
569 format!(
570 r#"#!/usr/bin/env bash
571# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
572set -euo pipefail
573
574LEAN_CTX_BIN={quoted_binary}
575
576INPUT=$(cat)
577TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
578
579case "$TOOL" in
580 Bash|bash|PowerShell|powershell) ;;
581 *) exit 0 ;;
582esac
583
584CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
585
586if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then
587 exit 0
588fi
589
590# Skip multi-line commands: the grep/sed extraction above does not decode
591# JSON \n into real newlines, so lean-ctx -c would receive fused lines (#787).
592if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
593
594case "$CMD" in
595 {case_pattern})
596 # Shell-escape then JSON-escape (two passes)
597 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
598 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
599 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
600 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
601 ;;
602 *) exit 0 ;;
603esac
604"#
605 )
606}
607
608pub fn generate_compact_rewrite_script(binary: &str) -> String {
609 let case_pattern = crate::rewrite_registry::bash_case_pattern();
610 let quoted_binary = shell_quoted_binary(binary);
611 format!(
612 r#"#!/usr/bin/env bash
613# lean-ctx hook — rewrites shell commands
614set -euo pipefail
615LEAN_CTX_BIN={quoted_binary}
616INPUT=$(cat)
617CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
618if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then exit 0; fi
619if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
620case "$CMD" in
621 {case_pattern})
622 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
623 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
624 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
625 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
626 *) exit 0 ;;
627esac
628"#
629 )
630}
631
632const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
633# lean-ctx PreToolUse hook — all native tools pass through
634# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
635# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
636exit 0
637";
638
639const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
640# lean-ctx hook — all native tools pass through
641exit 0
642";
643
644pub fn hybrid_rules_content() -> String {
645 use crate::core::rules_canonical;
646 format!(
647 "{start}\n<!-- version: {version} -->\n\n\
648# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
649{bullets}\n\n\
650{never}\n\n\
651{end}",
652 start = rules_canonical::START_MARK,
653 version = rules_canonical::RULES_VERSION,
654 bullets = rules_canonical::BULLETS,
655 never = rules_canonical::NEVER,
656 end = rules_canonical::END_MARK,
657 )
658}
659
660pub fn replace_rules_content() -> String {
661 use crate::core::rules_canonical;
662 format!(
663 "{start}\n<!-- version: {version} -->\n\n\
664# lean-ctx \u{2014} Replace Mode (native tools denied)\n\n\
665Native Read/Grep/Glob/Bash are denied by policy. Use ONLY ctx_* MCP tools:\n\
666- ctx_read for ALL file reads (cached, 10 modes, unchanged full/auto re-reads ~13 tokens)\n\
667- ctx_shell for ALL shell commands (95+ compression patterns)\n\
668- ctx_search instead of Grep/rg (compact results)\n\
669- ctx_tree instead of ls/find (compact directory maps)\n\
670- ctx_glob instead of Glob (file pattern matching)\n\n\
671Do NOT attempt native Read, Grep, Glob, or Bash \u{2014} they will be denied.\n\n\
672{end}",
673 start = rules_canonical::START_MARK,
674 version = rules_canonical::RULES_VERSION,
675 end = rules_canonical::END_MARK,
676 )
677}
678
679pub fn install_project_rules() {
680 install_project_rules_for_agents(&[]);
681}
682
683pub fn install_project_rules_for_agents(agents: &[&str]) {
686 if crate::core::config::Config::load().rules_scope_effective()
687 == crate::core::config::RulesScope::Global
688 {
689 return;
690 }
691
692 let cwd = std::env::current_dir().unwrap_or_default();
693
694 if !is_inside_git_repo(&cwd) {
695 eprintln!(
696 " Skipping project files: not inside a git repository.\n \
697 Run this command from your project root to create CLAUDE.md / AGENTS.md."
698 );
699 return;
700 }
701
702 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
703 if cwd == home {
704 eprintln!(
705 " Skipping project files: current directory is your home folder.\n \
706 Run this command from a project directory instead."
707 );
708 return;
709 }
710
711 let all = agents.is_empty();
712 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
713
714 ensure_project_agents_integration(&cwd);
715
716 if wants("cursor") || wants("windsurf") {
717 let cursorrules = cwd.join(".cursorrules");
718 if !cursorrules.exists()
719 || !std::fs::read_to_string(&cursorrules)
720 .unwrap_or_default()
721 .contains("lean-ctx")
722 {
723 let content = cursorrules_content();
724 if cursorrules.exists() {
725 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
726 if !existing.ends_with('\n') {
727 existing.push('\n');
728 }
729 existing.push('\n');
730 existing.push_str(&content);
731 write_file(&cursorrules, &existing);
732 } else {
733 write_file(&cursorrules, &content);
734 }
735 if !mcp_server_quiet_mode() {
736 eprintln!("Created/updated .cursorrules in project root.");
737 }
738 }
739 }
740
741 if wants("claude") {
742 let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
748 if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
749 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
750 && std::fs::remove_file(&claude_rules_file).is_ok()
751 && !mcp_server_quiet_mode()
752 {
753 eprintln!(
754 "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
755 );
756 }
757
758 install_claude_project_hooks(&cwd);
759 }
760
761 if wants("codebuddy") {
762 let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
763 if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
764 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
765 && std::fs::remove_file(&codebuddy_rules_file).is_ok()
766 && !mcp_server_quiet_mode()
767 {
768 eprintln!(
769 "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
770 );
771 }
772
773 install_codebuddy_project_hooks(&cwd);
774 }
775
776 if wants("kiro") {
777 let kiro_dir = cwd.join(".kiro");
778 if kiro_dir.exists() {
779 let steering_dir = kiro_dir.join("steering");
780 let steering_file = steering_dir.join("lean-ctx.md");
781 if !steering_file.exists()
782 || !std::fs::read_to_string(&steering_file)
783 .unwrap_or_default()
784 .contains("lean-ctx")
785 {
786 let _ = std::fs::create_dir_all(&steering_dir);
787 write_file(&steering_file, &kiro_steering_content());
788 if !mcp_server_quiet_mode() {
789 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
790 }
791 }
792 }
793 }
794
795 if wants("copilot") || wants("vscode") {
796 ensure_copilot_instructions(&cwd);
797 ensure_vscode_instruction_files_setting(&cwd);
798 }
799}
800
801const PROJECT_LEAN_CTX_MD_MARKER: &str =
802 crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
803const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
804const PROJECT_AGENTS_MD: &str = "AGENTS.md";
805const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
809const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
810
811fn ensure_project_agents_integration(cwd: &std::path::Path) {
812 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
813 let desired = format!(
816 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
817 crate::rules_inject::rules_longform_markdown()
818 );
819
820 if !lean_ctx_md.exists() {
821 write_file(&lean_ctx_md, &desired);
822 } else if std::fs::read_to_string(&lean_ctx_md)
823 .unwrap_or_default()
824 .contains(PROJECT_LEAN_CTX_MD_MARKER)
825 {
826 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
827 let version_str = format!(
828 "<!-- version: {} -->",
829 crate::core::rules_canonical::RULES_VERSION
830 );
831 if !current.contains(&version_str) {
832 write_file(&lean_ctx_md, &desired);
833 }
834 }
835
836 let block = format!(
841 "{AGENTS_BLOCK_START}\n\
842## lean-ctx\n\n\
843lean-ctx is active — the MCP tools replace native equivalents.\n\
844Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
845{AGENTS_BLOCK_END}\n"
846 );
847
848 let agents_md = cwd.join(PROJECT_AGENTS_MD);
849 if !agents_md.exists() {
850 let content = format!("# Agent Instructions\n\n{block}");
851 write_file(&agents_md, &content);
852 if !mcp_server_quiet_mode() {
853 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
854 }
855 return;
856 }
857
858 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
859
860 let has_block = crate::marked_block::contains_marker_line(&existing, AGENTS_BLOCK_START);
863
864 if existing.contains("CLI-first Token Optimization for Pi") && !has_block {
865 let content = format!("# Agent Instructions\n\n{block}");
866 write_file(&agents_md, &content);
867 return;
868 }
869
870 if has_block {
871 let updated = crate::marked_block::replace_marked_block(
872 &existing,
873 AGENTS_BLOCK_START,
874 AGENTS_BLOCK_END,
875 &block,
876 );
877 if updated != existing {
878 write_file(&agents_md, &updated);
879 }
880 return;
881 }
882
883 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
884 return;
885 }
886
887 let mut out = existing;
888 if !out.ends_with('\n') {
889 out.push('\n');
890 }
891 out.push('\n');
892 out.push_str(&block);
893 write_file(&agents_md, &out);
894 if !mcp_server_quiet_mode() {
895 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
896 }
897}
898
899fn ensure_copilot_instructions(cwd: &std::path::Path) {
906 let path = cwd.join(".github").join("copilot-instructions.md");
907 let block = crate::rules_inject::rules_dedicated_markdown();
908 let start = crate::core::rules_canonical::START_MARK;
909 let end = crate::core::rules_canonical::END_MARK;
910 let owned = format!("{}\n", block.trim_end());
911
912 let existing = std::fs::read_to_string(&path).unwrap_or_default();
913 let desired = if existing.trim().is_empty() {
914 owned
915 } else if existing.contains(start) {
916 let user = crate::marked_block::remove_content(&existing, start, end);
918 if user.trim().is_empty() {
919 owned
920 } else {
921 format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
922 }
923 } else {
924 format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
926 };
927
928 if desired == existing {
929 return;
930 }
931 if let Some(parent) = path.parent()
932 && std::fs::create_dir_all(parent).is_err()
933 {
934 return;
935 }
936 write_file(&path, &desired);
937 if !mcp_server_quiet_mode() {
938 eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
939 }
940}
941
942fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
947 const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
948 let path = cwd.join(".vscode").join("settings.json");
949
950 let existing = std::fs::read_to_string(&path).unwrap_or_default();
951 let mut json = if existing.trim().is_empty() {
952 serde_json::json!({})
953 } else {
954 match crate::core::jsonc::parse_jsonc(&existing) {
955 Ok(v) if v.is_object() => v,
956 _ => return,
958 }
959 };
960 let Some(obj) = json.as_object_mut() else {
961 return;
962 };
963 if obj.contains_key(KEY) {
964 return;
965 }
966 obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
967
968 if let Some(parent) = path.parent()
969 && std::fs::create_dir_all(parent).is_err()
970 {
971 return;
972 }
973 let Ok(formatted) = serde_json::to_string_pretty(&json) else {
974 return;
975 };
976 if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
977 && !mcp_server_quiet_mode()
978 {
979 eprintln!("Set {KEY} in .vscode/settings.json.");
980 }
981}
982
983pub fn cursorrules_content() -> String {
987 let start = crate::core::rules_canonical::START_MARK;
988 let end = crate::core::rules_canonical::END_MARK;
989 let version = crate::core::rules_canonical::RULES_VERSION;
990 format!(
991 "{start}\n<!-- version: {version} -->\n\n\
992# lean-ctx\n\n\
993{bullets}\n\n\
994{never}\n\
995Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
996{end}",
997 bullets = crate::core::rules_canonical::BULLETS,
998 never = crate::core::rules_canonical::NEVER,
999 )
1000}
1001
1002pub fn kiro_steering_content() -> String {
1003 use crate::core::rules_canonical;
1004 format!(
1005 "---\n\
1006inclusion: always\n\
1007---\n\n\
1008# LeanCTX — Context Gateway for AI Systems\n\n\
1009{start}\n\
1010<!-- version: {version} -->\n\n\
1011The workspace has the `lean-ctx` MCP server installed. \
1012You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
1013{bullets}\n\n\
1014{never}\n\n\
1015## When to use native Kiro tools instead\n\n\
1016- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
1017- `strReplace` \u{2014} always use native (precise string replacement)\n\
1018- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
1019- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
1020- `deleteFile` \u{2014} always use native\n\
1021- Glob \u{2014} always use native glob\n\n\
1022{end}",
1023 start = rules_canonical::START_MARK,
1024 version = rules_canonical::RULES_VERSION,
1025 bullets = rules_canonical::BULLETS,
1026 never = rules_canonical::NEVER,
1027 end = rules_canonical::END_MARK,
1028 )
1029}
1030pub(crate) fn should_register_mcp() -> bool {
1037 crate::core::config::Config::load()
1038 .setup
1039 .should_update_mcp()
1040}
1041
1042pub fn install_agent_hook(agent: &str, global: bool) {
1043 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
1044}
1045
1046pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1047 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1048 match agent {
1049 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
1050 "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
1051 "cursor" => install_cursor_hook_with_mode(global, mode),
1052 "gemini" => {
1053 install_gemini_hook();
1054 if mode == HookMode::Replace {
1055 install_gemini_deny_hook(&home);
1056 }
1057 install_antigravity_cli_hook();
1063 }
1064 "grok" | "grok-build" => install_grok_mcp(),
1065 "antigravity" => install_antigravity_hook(),
1066 "antigravity-cli" => install_antigravity_cli_hook(),
1067 "augment" => install_mcp_json_agent(
1068 "Augment CLI",
1069 "~/.augment/settings.json",
1070 &crate::core::editor_registry::augment_cli_settings_path(&home),
1071 ),
1072 "codex" => {
1073 install_codex_hook();
1074 }
1075 "windsurf" => {
1076 install_windsurf_rules(global);
1077 if mode == HookMode::Replace {
1078 install_windsurf_hooks_replace(&home);
1079 }
1080 }
1081 "cline" | "roo" => install_cline_rules(global),
1082 "copilot" | "vscode" => install_copilot_hook(global),
1083 "vscode-insiders" | "commandcode" | "codewhale" | "omp" => {}
1097 "pi" => install_pi_hook_with_mode(global, mode),
1098 "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
1099 "qoderwork" => install_mcp_json_agent(
1100 "QoderWork",
1101 "~/.qoderwork/mcp.json",
1102 &home.join(".qoderwork/mcp.json"),
1103 ),
1104 "qwen" => install_mcp_json_agent(
1105 "Qwen Code",
1106 "~/.qwen/settings.json",
1107 &home.join(".qwen/settings.json"),
1108 ),
1109 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
1110 "amazonq" => install_mcp_json_agent(
1111 "Amazon Q Developer",
1112 "~/.aws/amazonq/default.json",
1113 &home.join(".aws/amazonq/default.json"),
1114 ),
1115 "jetbrains" => install_jetbrains_hook(),
1116 "kiro" => install_kiro_hook(),
1117 "verdent" => install_mcp_json_agent(
1118 "Verdent",
1119 "~/.verdent/mcp.json",
1120 &home.join(".verdent/mcp.json"),
1121 ),
1122 "opencode" => install_opencode_hook_with_mode(mode),
1123 "amp" => install_amp_hook(),
1124 "crush" => install_crush_hook_with_mode(mode),
1125 "openclaw" => install_openclaw_hook(),
1126 "hermes" => install_hermes_hook_with_mode(global, mode),
1127 "vibe" => install_vibe_hook(),
1128 "zed" => {
1129 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
1130 let binary = resolve_binary_path();
1131 let entry = full_server_entry(&binary);
1132 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
1133 }
1134 "aider" => {
1135 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
1136 }
1137 "continue" => install_mcp_json_agent(
1138 "Continue",
1139 "~/.continue/mcp.json",
1140 &home.join(".continue/mcp.json"),
1141 ),
1142 "neovim" => install_mcp_json_agent(
1143 "Neovim (mcphub.nvim)",
1144 "~/.config/mcphub/servers.json",
1145 &home.join(".config/mcphub/servers.json"),
1146 ),
1147 "emacs" => install_mcp_json_agent(
1148 "Emacs (mcp.el)",
1149 "~/.emacs.d/mcp.json",
1150 &home.join(".emacs.d/mcp.json"),
1151 ),
1152 "sublime" => install_mcp_json_agent(
1153 "Sublime Text",
1154 "~/.config/sublime-text/mcp.json",
1155 &home.join(".config/sublime-text/mcp.json"),
1156 ),
1157 _ => {
1158 eprintln!("Unknown agent: {agent}");
1159 eprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
1160 eprintln!(
1161 " claude, cline, codebuddy, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, grok,"
1162 );
1163 eprintln!(
1164 " grok-build, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi, qoder,"
1165 );
1166 eprintln!(
1167 " qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vibe, vscode, windsurf, zed"
1168 );
1169 std::process::exit(1);
1170 }
1171 }
1172}
1173
1174pub(crate) fn install_agent_hook_respecting_rules_off(agent: &str, global: bool, mode: HookMode) {
1181 if crate::core::config::Config::load().rules_injection_effective()
1182 == crate::core::config::RulesInjection::Off
1183 {
1184 install_agent_runtime_hook_with_mode(agent, global, mode);
1185 } else {
1186 install_agent_hook_with_mode(agent, global, mode);
1187 }
1188}
1189
1190pub(crate) fn install_agent_runtime_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1198 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1199
1200 match agent {
1201 "claude" | "claude-code" => {
1202 install_claude_hook_scripts(&home);
1203 install_claude_hook_config(&home);
1204 install_claude_statusline(&home);
1205
1206 if claude_hides_native_search(mode) {
1207 install_claude_permissions_deny_replace(&home);
1208 }
1209
1210 install_claude_permissions_allow_mcp(&home);
1211 }
1212 "codebuddy" => {
1213 install_codebuddy_hook_scripts(&home);
1214 install_codebuddy_hook_config(&home);
1215
1216 if claude_hides_native_search(mode) {
1217 install_codebuddy_permissions_deny_replace(&home, mode);
1218 }
1219 }
1220 "cursor" => {
1221 install_cursor_hook_scripts(&home);
1222 install_cursor_hook_config(&home);
1223
1224 if mode == HookMode::Replace {
1225 install_cursor_deny_hook(global);
1226 }
1227 }
1228 "gemini" => {
1229 install_gemini_hook_scripts(&home);
1230 install_gemini_hook_config(&home);
1231
1232 if mode == HookMode::Replace {
1233 install_gemini_deny_hook(&home);
1234 }
1235
1236 install_antigravity_cli_hook();
1240 }
1241 "codex" => install_codex_runtime_hook(),
1242 "windsurf" => {
1243 if mode == HookMode::Replace {
1244 install_windsurf_hooks_replace(&home);
1245 } else {
1246 install_windsurf_hooks(&home);
1247 }
1248 }
1249 "copilot" | "vscode" => install_copilot_runtime_hook(global),
1250 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
1251
1252 "pi" => install_pi_hook_with_mode(global, mode),
1255
1256 "antigravity" => install_antigravity_hook(),
1259 "antigravity-cli" => install_antigravity_cli_hook(),
1260 "amp" => install_amp_hook(),
1261 "jetbrains" => install_jetbrains_hook(),
1262 "openclaw" => install_openclaw_hook(),
1263 "vibe" => install_vibe_hook(),
1264 _ => {}
1269 }
1270}
1271
1272pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
1273 match agent {
1274 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
1275 "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
1276 _ => {}
1277 }
1278}
1279
1280fn write_file(path: &std::path::Path, content: &str) {
1281 if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1284 return;
1285 }
1286 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
1287 tracing::error!("Error writing {}: {e}", path.display());
1288 }
1289}
1290
1291fn ensure_state_dir(dir: &std::path::Path) -> bool {
1300 match crate::config_io::ensure_dir(dir) {
1301 Ok(()) => true,
1302 Err(e) => {
1303 eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
1305 false
1306 }
1307 }
1308}
1309
1310fn is_inside_git_repo(path: &std::path::Path) -> bool {
1311 let mut p = path;
1312 loop {
1313 if p.join(".git").exists() {
1314 return true;
1315 }
1316 match p.parent() {
1317 Some(parent) => p = parent,
1318 None => return false,
1319 }
1320 }
1321}
1322
1323#[cfg(unix)]
1324fn make_executable(path: &PathBuf) {
1325 use std::os::unix::fs::PermissionsExt;
1326 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1327}
1328
1329#[cfg(not(unix))]
1330fn make_executable(_path: &PathBuf) {}
1331
1332pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
1354 Vec::new()
1355}
1356
1357pub(crate) fn mcp_server_env_json() -> serde_json::Value {
1359 let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
1360 .into_iter()
1361 .map(|(k, v)| (k, serde_json::Value::String(v)))
1362 .collect();
1363 serde_json::Value::Object(map)
1364}
1365
1366fn full_server_entry(binary: &str) -> serde_json::Value {
1367 serde_json::json!({
1373 "command": binary,
1374 "env": mcp_server_env_json()
1375 })
1376}
1377
1378pub(crate) fn install_mcp_json_agent(
1379 name: &str,
1380 display_path: &str,
1381 config_path: &std::path::Path,
1382) {
1383 let binary = resolve_binary_path();
1384 let entry = full_server_entry(&binary);
1385 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
1386}
1387
1388#[cfg(test)]
1389mod tests;