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] = &[
67 "cursor",
68 "claude",
69 "claude-code",
70 "codebuddy",
71 "codex",
72 "windsurf",
73 "opencode",
74 "gemini",
75];
76
77pub const HYBRID_AGENTS: &[&str] = &[
80 "cursor",
81 "gemini",
82 "codex",
83 "claude",
84 "claude-code",
85 "crush",
86 "hermes",
87 "opencode",
88 "openclaw",
89 "pi",
90 "omp",
91 "qoder",
92 "qodercli",
93 "windsurf",
94 "amp",
95 "cline",
96 "roo",
97 "copilot",
98 "kiro",
99 "qwen",
100 "trae",
101 "antigravity",
102 "antigravity-cli",
103 "amazonq",
104 "verdent",
105];
106
107pub const MCP_ONLY_AGENTS: &[&str] = &["codewhale"];
117
118pub fn is_supported_agent(agent: &str) -> bool {
123 let key = agent.to_ascii_lowercase();
124 REPLACE_AGENTS.contains(&key.as_str())
125 || HYBRID_AGENTS.contains(&key.as_str())
126 || MCP_ONLY_AGENTS.contains(&key.as_str())
127}
128
129pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
139 let deny_suppressed = is_deny_suppressed();
140 if let Some(override_mode) = crate::core::config::Config::load().hook_mode_override() {
141 return if deny_suppressed {
142 override_mode.cap_at_hybrid()
143 } else {
144 override_mode
145 };
146 }
147 if deny_suppressed {
148 if REPLACE_AGENTS.contains(&agent_key) || HYBRID_AGENTS.contains(&agent_key) {
149 return HookMode::Hybrid;
150 }
151 return HookMode::Mcp;
152 }
153 if REPLACE_AGENTS.contains(&agent_key) {
154 HookMode::Replace
155 } else if HYBRID_AGENTS.contains(&agent_key) {
156 HookMode::Hybrid
157 } else {
158 HookMode::Mcp
159 }
160}
161
162fn is_deny_suppressed() -> bool {
164 if std::env::var("LEAN_CTX_DISABLED").is_ok() {
165 return true;
166 }
167 if matches!(std::env::var("LEAN_CTX_SHADOW_MODE"), Ok(v) if v.trim() == "false" || v.trim() == "0")
168 {
169 return true;
170 }
171 if matches!(std::env::var("LEAN_CTX_HEAL"), Ok(v) if v.trim().eq_ignore_ascii_case("off") || v.trim() == "0")
172 {
173 return true;
174 }
175 let cfg = crate::core::config::Config::load();
176 !cfg.shadow_mode
177}
178use agents::{
179 install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
180 install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
181 install_claude_permissions_allow_mcp, install_claude_permissions_deny_replace,
182 install_claude_project_hooks, install_claude_statusline, install_cline_rules,
183 install_codebuddy_hook_config, install_codebuddy_hook_scripts,
184 install_codebuddy_hook_with_mode, install_codebuddy_permissions_deny_replace,
185 install_codebuddy_project_hooks, install_codex_hook, install_codex_runtime_hook,
186 install_copilot_hook, install_copilot_runtime_hook, install_crush_hook_with_mode,
187 install_cursor_deny_hook, install_cursor_hook_config, install_cursor_hook_scripts,
188 install_cursor_hook_with_mode, install_gemini_deny_hook, install_gemini_hook,
189 install_gemini_hook_config, install_gemini_hook_scripts, install_grok_mcp,
190 install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
191 install_openclaw_hook, install_opencode_hook_with_mode, install_pi_hook_with_mode,
192 install_qoder_hook_with_mode, install_qoder_runtime_hook_with_mode, install_vibe_hook,
193 install_windsurf_hooks, install_windsurf_hooks_replace, install_windsurf_rules,
194};
195use support::{
196 ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
197 upsert_lean_ctx_codex_hook_entries,
198};
199
200fn mcp_server_quiet_mode() -> bool {
201 crate::core::runtime_flags::mcp_server_enabled() || crate::core::runtime_flags::quiet_enabled()
202}
203
204const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
212 "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder", "qodercli",
213];
214
215#[cfg(test)]
220const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
221 "claude-code",
223 "pi",
225 "omp",
227 "cline",
230 "roo",
231 "kiro",
232 "antigravity",
235 "antigravity-cli",
236 "amp",
237 "crush",
238 "hermes",
239 "opencode",
240 "openclaw",
241 "qwen",
242 "trae",
243 "amazonq",
244 "verdent",
245];
246
247pub fn refresh_installed_hooks() {
256 if !crate::core::config::Config::load().setup.manage_hooks {
257 tracing::debug!("hook refresh skipped: [setup] manage_hooks = false");
258 return;
259 }
260 let Some(home) = crate::core::home::resolve_home_dir() else {
261 return;
262 };
263 for agent in REFRESHABLE_HOOK_AGENTS {
264 if hooks_installed_for(agent, &home) {
265 refresh_agent_hooks(agent, &home);
266 }
267 }
268}
269
270pub(crate) fn installed_hook_mode(agent: &str, home: &std::path::Path) -> Option<HookMode> {
273 hooks_installed_for(agent, home).then(|| recommend_hook_mode(agent))
274}
275
276fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
278 match agent {
279 "claude" => {
280 let dir = crate::setup::claude_config_dir(home);
281 dir.join("hooks/lean-ctx-rewrite.sh").exists()
282 || file_contains_lean_ctx(&dir.join("settings.json"))
283 }
284 "codebuddy" => {
285 let dir = crate::core::editor_registry::codebuddy_state_dir(home);
286 dir.join("hooks/lean-ctx-rewrite.sh").exists()
287 || file_contains_lean_ctx(&dir.join("settings.json"))
288 }
289 "cursor" => {
290 home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
291 || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
292 }
293 "gemini" => {
294 home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
295 .exists()
296 || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
297 }
298 "codex" => {
299 let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
300 dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
301 || file_contains_lean_ctx(&dir.join("hooks.json"))
302 }
303 "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
304 "copilot" => {
305 file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
308 || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
309 }
310 "qoder" | "qodercli" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
311 _ => false,
312 }
313}
314
315fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
320 let mode = recommend_hook_mode(agent);
321 match agent {
322 "claude" => {
323 install_claude_hook_scripts(home);
324 install_claude_hook_config(home);
325 install_claude_statusline(home);
328 if mode == HookMode::Replace {
329 install_claude_permissions_deny_replace(home);
330 }
331 }
332 "codebuddy" => {
333 install_codebuddy_hook_scripts(home);
334 install_codebuddy_hook_config(home);
335 if mode == HookMode::Replace {
336 install_codebuddy_permissions_deny_replace(home);
337 }
338 }
339 "cursor" => {
340 install_cursor_hook_scripts(home);
341 install_cursor_hook_config(home);
342 if mode == HookMode::Replace {
343 install_cursor_deny_hook(true);
344 }
345 }
346 "gemini" => {
347 install_gemini_hook_scripts(home);
348 install_gemini_hook_config(home);
349 if mode == HookMode::Replace {
350 install_gemini_deny_hook(home);
351 }
352 }
353 "codex" => install_codex_runtime_hook(),
354 "windsurf" => {
355 if mode == HookMode::Replace {
356 install_windsurf_hooks_replace(home);
357 } else {
358 install_windsurf_hooks(home);
359 }
360 }
361 "copilot" => install_copilot_runtime_hook(true),
362 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
363 _ => {}
364 }
365}
366
367fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
368 std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
369}
370
371fn resolve_binary_path() -> String {
387 crate::core::portable_binary::resolve_agent_binary()
388}
389
390fn resolve_hook_command_binary() -> String {
401 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
402 return portable;
403 }
404 resolve_binary_path()
405}
406
407fn resolve_binary_path_for_bash() -> String {
408 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
409 return portable;
410 }
411 to_bash_compatible_path(&resolve_binary_path())
412}
413
414pub(crate) fn shell_quoted_binary(binary: &str) -> String {
421 let escaped = binary.replace('"', "\\\"").replace('`', "\\`");
422 format!("\"{escaped}\"")
423}
424
425fn wrapper_is_portable_and_working(path: &std::path::Path, home: &std::path::Path) -> bool {
434 std::fs::read_to_string(path)
435 .is_ok_and(|content| wrapper_content_is_portable_and_working(&content, home))
436}
437
438pub(crate) fn wrapper_content_is_portable_and_working(
439 content: &str,
440 home: &std::path::Path,
441) -> bool {
442 let Some(token) = wrapper_binary_token(content) else {
443 return false;
444 };
445 if !(token.contains("$HOME") || token.contains("${HOME}") || token.contains("%USERPROFILE%")) {
446 return false;
447 }
448 let home_s = home.to_string_lossy();
449 let expanded = token
450 .replace("${HOME}", &home_s)
451 .replace("$HOME", &home_s)
452 .replace("%USERPROFILE%", &home_s);
453 std::path::Path::new(&from_bash_to_native_path(&expanded)).exists()
454}
455
456pub(crate) fn wrapper_binary_token(content: &str) -> Option<String> {
460 for line in content.lines() {
461 let t = line.trim();
462 if let Some(rest) = t.strip_prefix("LEAN_CTX_BIN=") {
463 let rest = rest.trim();
464 let tok = rest
465 .strip_prefix('"')
466 .map_or(rest, |r| r.split('"').next().unwrap_or_default());
467 if !tok.is_empty() {
468 return Some(tok.to_string());
469 }
470 }
471 if let Some(rest) = t.strip_prefix("exec ") {
472 let rest = rest.trim();
473 let tok = match rest.strip_prefix('"') {
474 Some(r) => r.split('"').next().unwrap_or_default().to_string(),
475 None => rest
476 .split_whitespace()
477 .next()
478 .unwrap_or_default()
479 .to_string(),
480 };
481 if !tok.is_empty() {
482 return Some(tok);
483 }
484 }
485 }
486 None
487}
488
489fn write_wrapper_file(path: &std::path::Path, content: &str, home: &std::path::Path) {
494 if crate::core::portable_binary::hook_binary_override().is_none()
495 && wrapper_is_portable_and_working(path, home)
496 {
497 return;
498 }
499 write_file(path, content);
500}
501
502pub fn to_bash_compatible_path(path: &str) -> String {
503 let path = match crate::core::pathutil::strip_verbatim_str(path) {
504 Some(stripped) => stripped,
505 None => path.replace('\\', "/"),
506 };
507 if path.len() >= 2 && path.as_bytes()[1] == b':' {
508 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
509 format!("/{drive}{}", &path[2..])
510 } else {
511 path
512 }
513}
514
515pub fn from_bash_to_native_path(path: &str) -> String {
518 crate::core::pathutil::normalize_tool_path(path)
519}
520
521pub fn normalize_tool_path(path: &str) -> String {
524 crate::core::pathutil::normalize_tool_path(path)
525}
526
527pub fn generate_rewrite_script(binary: &str) -> String {
528 let case_pattern = crate::rewrite_registry::bash_case_pattern();
529 let quoted_binary = shell_quoted_binary(binary);
533 format!(
534 r#"#!/usr/bin/env bash
535# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
536set -euo pipefail
537
538LEAN_CTX_BIN={quoted_binary}
539
540INPUT=$(cat)
541TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
542
543case "$TOOL" in
544 Bash|bash|PowerShell|powershell) ;;
545 *) exit 0 ;;
546esac
547
548CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
549
550if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then
551 exit 0
552fi
553
554# Skip multi-line commands: the grep/sed extraction above does not decode
555# JSON \n into real newlines, so lean-ctx -c would receive fused lines (#787).
556if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
557
558case "$CMD" in
559 {case_pattern})
560 # Shell-escape then JSON-escape (two passes)
561 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
562 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
563 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
564 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
565 ;;
566 *) exit 0 ;;
567esac
568"#
569 )
570}
571
572pub fn generate_compact_rewrite_script(binary: &str) -> String {
573 let case_pattern = crate::rewrite_registry::bash_case_pattern();
574 let quoted_binary = shell_quoted_binary(binary);
575 format!(
576 r#"#!/usr/bin/env bash
577# lean-ctx hook — rewrites shell commands
578set -euo pipefail
579LEAN_CTX_BIN={quoted_binary}
580INPUT=$(cat)
581CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
582if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then exit 0; fi
583if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
584case "$CMD" in
585 {case_pattern})
586 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
587 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
588 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
589 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
590 *) exit 0 ;;
591esac
592"#
593 )
594}
595
596const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
597# lean-ctx PreToolUse hook — all native tools pass through
598# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
599# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
600exit 0
601";
602
603const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
604# lean-ctx hook — all native tools pass through
605exit 0
606";
607
608pub fn hybrid_rules_content() -> String {
609 use crate::core::rules_canonical;
610 format!(
611 "{start}\n<!-- version: {version} -->\n\n\
612# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
613{bullets}\n\n\
614{never}\n\n\
615{end}",
616 start = rules_canonical::START_MARK,
617 version = rules_canonical::RULES_VERSION,
618 bullets = rules_canonical::BULLETS,
619 never = rules_canonical::NEVER,
620 end = rules_canonical::END_MARK,
621 )
622}
623
624pub fn replace_rules_content() -> String {
625 use crate::core::rules_canonical;
626 format!(
627 "{start}\n<!-- version: {version} -->\n\n\
628# lean-ctx \u{2014} Replace Mode (native tools denied)\n\n\
629Native Read/Grep/Glob/Bash are denied by policy. Use ONLY ctx_* MCP tools:\n\
630- ctx_read for ALL file reads (cached, 10 modes, unchanged full/auto re-reads ~13 tokens)\n\
631- ctx_shell for ALL shell commands (95+ compression patterns)\n\
632- ctx_search instead of Grep/rg (compact results)\n\
633- ctx_tree instead of ls/find (compact directory maps)\n\
634- ctx_glob instead of Glob (file pattern matching)\n\n\
635Do NOT attempt native Read, Grep, Glob, or Bash \u{2014} they will be denied.\n\n\
636{end}",
637 start = rules_canonical::START_MARK,
638 version = rules_canonical::RULES_VERSION,
639 end = rules_canonical::END_MARK,
640 )
641}
642
643pub fn install_project_rules() {
644 install_project_rules_for_agents(&[]);
645}
646
647pub fn install_project_rules_for_agents(agents: &[&str]) {
650 if crate::core::config::Config::load().rules_scope_effective()
651 == crate::core::config::RulesScope::Global
652 {
653 return;
654 }
655
656 let cwd = std::env::current_dir().unwrap_or_default();
657
658 if !is_inside_git_repo(&cwd) {
659 eprintln!(
660 " Skipping project files: not inside a git repository.\n \
661 Run this command from your project root to create CLAUDE.md / AGENTS.md."
662 );
663 return;
664 }
665
666 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
667 if cwd == home {
668 eprintln!(
669 " Skipping project files: current directory is your home folder.\n \
670 Run this command from a project directory instead."
671 );
672 return;
673 }
674
675 let all = agents.is_empty();
676 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
677
678 ensure_project_agents_integration(&cwd);
679
680 if wants("cursor") || wants("windsurf") {
681 let cursorrules = cwd.join(".cursorrules");
682 if !cursorrules.exists()
683 || !std::fs::read_to_string(&cursorrules)
684 .unwrap_or_default()
685 .contains("lean-ctx")
686 {
687 let content = cursorrules_content();
688 if cursorrules.exists() {
689 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
690 if !existing.ends_with('\n') {
691 existing.push('\n');
692 }
693 existing.push('\n');
694 existing.push_str(&content);
695 write_file(&cursorrules, &existing);
696 } else {
697 write_file(&cursorrules, &content);
698 }
699 if !mcp_server_quiet_mode() {
700 eprintln!("Created/updated .cursorrules in project root.");
701 }
702 }
703 }
704
705 if wants("claude") {
706 let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
712 if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
713 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
714 && std::fs::remove_file(&claude_rules_file).is_ok()
715 && !mcp_server_quiet_mode()
716 {
717 eprintln!(
718 "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
719 );
720 }
721
722 install_claude_project_hooks(&cwd);
723 }
724
725 if wants("codebuddy") {
726 let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
727 if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
728 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
729 && std::fs::remove_file(&codebuddy_rules_file).is_ok()
730 && !mcp_server_quiet_mode()
731 {
732 eprintln!(
733 "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
734 );
735 }
736
737 install_codebuddy_project_hooks(&cwd);
738 }
739
740 if wants("kiro") {
741 let kiro_dir = cwd.join(".kiro");
742 if kiro_dir.exists() {
743 let steering_dir = kiro_dir.join("steering");
744 let steering_file = steering_dir.join("lean-ctx.md");
745 if !steering_file.exists()
746 || !std::fs::read_to_string(&steering_file)
747 .unwrap_or_default()
748 .contains("lean-ctx")
749 {
750 let _ = std::fs::create_dir_all(&steering_dir);
751 write_file(&steering_file, &kiro_steering_content());
752 if !mcp_server_quiet_mode() {
753 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
754 }
755 }
756 }
757 }
758
759 if wants("copilot") || wants("vscode") {
760 ensure_copilot_instructions(&cwd);
761 ensure_vscode_instruction_files_setting(&cwd);
762 }
763}
764
765const PROJECT_LEAN_CTX_MD_MARKER: &str =
766 crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
767const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
768const PROJECT_AGENTS_MD: &str = "AGENTS.md";
769const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
773const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
774
775fn ensure_project_agents_integration(cwd: &std::path::Path) {
776 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
777 let desired = format!(
780 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
781 crate::rules_inject::rules_longform_markdown()
782 );
783
784 if !lean_ctx_md.exists() {
785 write_file(&lean_ctx_md, &desired);
786 } else if std::fs::read_to_string(&lean_ctx_md)
787 .unwrap_or_default()
788 .contains(PROJECT_LEAN_CTX_MD_MARKER)
789 {
790 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
791 let version_str = format!(
792 "<!-- version: {} -->",
793 crate::core::rules_canonical::RULES_VERSION
794 );
795 if !current.contains(&version_str) {
796 write_file(&lean_ctx_md, &desired);
797 }
798 }
799
800 let block = format!(
805 "{AGENTS_BLOCK_START}\n\
806## lean-ctx\n\n\
807lean-ctx is active — the MCP tools replace native equivalents.\n\
808Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
809{AGENTS_BLOCK_END}\n"
810 );
811
812 let agents_md = cwd.join(PROJECT_AGENTS_MD);
813 if !agents_md.exists() {
814 let content = format!("# Agent Instructions\n\n{block}");
815 write_file(&agents_md, &content);
816 if !mcp_server_quiet_mode() {
817 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
818 }
819 return;
820 }
821
822 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
823
824 let has_block = crate::marked_block::contains_marker_line(&existing, AGENTS_BLOCK_START);
827
828 if existing.contains("CLI-first Token Optimization for Pi") && !has_block {
829 let content = format!("# Agent Instructions\n\n{block}");
830 write_file(&agents_md, &content);
831 return;
832 }
833
834 if has_block {
835 let updated = crate::marked_block::replace_marked_block(
836 &existing,
837 AGENTS_BLOCK_START,
838 AGENTS_BLOCK_END,
839 &block,
840 );
841 if updated != existing {
842 write_file(&agents_md, &updated);
843 }
844 return;
845 }
846
847 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
848 return;
849 }
850
851 let mut out = existing;
852 if !out.ends_with('\n') {
853 out.push('\n');
854 }
855 out.push('\n');
856 out.push_str(&block);
857 write_file(&agents_md, &out);
858 if !mcp_server_quiet_mode() {
859 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
860 }
861}
862
863fn ensure_copilot_instructions(cwd: &std::path::Path) {
870 let path = cwd.join(".github").join("copilot-instructions.md");
871 let block = crate::rules_inject::rules_dedicated_markdown();
872 let start = crate::core::rules_canonical::START_MARK;
873 let end = crate::core::rules_canonical::END_MARK;
874 let owned = format!("{}\n", block.trim_end());
875
876 let existing = std::fs::read_to_string(&path).unwrap_or_default();
877 let desired = if existing.trim().is_empty() {
878 owned
879 } else if existing.contains(start) {
880 let user = crate::marked_block::remove_content(&existing, start, end);
882 if user.trim().is_empty() {
883 owned
884 } else {
885 format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
886 }
887 } else {
888 format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
890 };
891
892 if desired == existing {
893 return;
894 }
895 if let Some(parent) = path.parent()
896 && std::fs::create_dir_all(parent).is_err()
897 {
898 return;
899 }
900 write_file(&path, &desired);
901 if !mcp_server_quiet_mode() {
902 eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
903 }
904}
905
906fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
911 const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
912 let path = cwd.join(".vscode").join("settings.json");
913
914 let existing = std::fs::read_to_string(&path).unwrap_or_default();
915 let mut json = if existing.trim().is_empty() {
916 serde_json::json!({})
917 } else {
918 match crate::core::jsonc::parse_jsonc(&existing) {
919 Ok(v) if v.is_object() => v,
920 _ => return,
922 }
923 };
924 let Some(obj) = json.as_object_mut() else {
925 return;
926 };
927 if obj.contains_key(KEY) {
928 return;
929 }
930 obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
931
932 if let Some(parent) = path.parent()
933 && std::fs::create_dir_all(parent).is_err()
934 {
935 return;
936 }
937 let Ok(formatted) = serde_json::to_string_pretty(&json) else {
938 return;
939 };
940 if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
941 && !mcp_server_quiet_mode()
942 {
943 eprintln!("Set {KEY} in .vscode/settings.json.");
944 }
945}
946
947pub fn cursorrules_content() -> String {
951 let start = crate::core::rules_canonical::START_MARK;
952 let end = crate::core::rules_canonical::END_MARK;
953 let version = crate::core::rules_canonical::RULES_VERSION;
954 format!(
955 "{start}\n<!-- version: {version} -->\n\n\
956# lean-ctx\n\n\
957{bullets}\n\n\
958{never}\n\
959Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
960{end}",
961 bullets = crate::core::rules_canonical::BULLETS,
962 never = crate::core::rules_canonical::NEVER,
963 )
964}
965
966pub fn kiro_steering_content() -> String {
967 use crate::core::rules_canonical;
968 format!(
969 "---\n\
970inclusion: always\n\
971---\n\n\
972# LeanCTX — Context Gateway for AI Systems\n\n\
973{start}\n\
974<!-- version: {version} -->\n\n\
975The workspace has the `lean-ctx` MCP server installed. \
976You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
977{bullets}\n\n\
978{never}\n\n\
979## When to use native Kiro tools instead\n\n\
980- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
981- `strReplace` \u{2014} always use native (precise string replacement)\n\
982- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
983- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
984- `deleteFile` \u{2014} always use native\n\
985- Glob \u{2014} always use native glob\n\n\
986{end}",
987 start = rules_canonical::START_MARK,
988 version = rules_canonical::RULES_VERSION,
989 bullets = rules_canonical::BULLETS,
990 never = rules_canonical::NEVER,
991 end = rules_canonical::END_MARK,
992 )
993}
994pub(crate) fn should_register_mcp() -> bool {
1001 crate::core::config::Config::load()
1002 .setup
1003 .should_update_mcp()
1004}
1005
1006pub fn install_agent_hook(agent: &str, global: bool) {
1007 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
1008}
1009
1010pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1011 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1012 match agent {
1013 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
1014 "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
1015 "cursor" => install_cursor_hook_with_mode(global, mode),
1016 "gemini" => {
1017 install_gemini_hook();
1018 if mode == HookMode::Replace {
1019 install_gemini_deny_hook(&home);
1020 }
1021 install_antigravity_cli_hook();
1027 }
1028 "grok" | "grok-build" => install_grok_mcp(),
1029 "antigravity" => install_antigravity_hook(),
1030 "antigravity-cli" => install_antigravity_cli_hook(),
1031 "augment" => install_mcp_json_agent(
1032 "Augment CLI",
1033 "~/.augment/settings.json",
1034 &crate::core::editor_registry::augment_cli_settings_path(&home),
1035 ),
1036 "codex" => {
1037 install_codex_hook();
1038 }
1039 "windsurf" => {
1040 install_windsurf_rules(global);
1041 if mode == HookMode::Replace {
1042 install_windsurf_hooks_replace(&home);
1043 }
1044 }
1045 "cline" | "roo" => install_cline_rules(global),
1046 "copilot" | "vscode" => install_copilot_hook(global),
1047 "vscode-insiders" | "commandcode" | "codewhale" | "omp" => {}
1061 "pi" => install_pi_hook_with_mode(global, mode),
1062 "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
1063 "qoderwork" => install_mcp_json_agent(
1064 "QoderWork",
1065 "~/.qoderwork/mcp.json",
1066 &home.join(".qoderwork/mcp.json"),
1067 ),
1068 "qwen" => install_mcp_json_agent(
1069 "Qwen Code",
1070 "~/.qwen/settings.json",
1071 &home.join(".qwen/settings.json"),
1072 ),
1073 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
1074 "amazonq" => install_mcp_json_agent(
1075 "Amazon Q Developer",
1076 "~/.aws/amazonq/default.json",
1077 &home.join(".aws/amazonq/default.json"),
1078 ),
1079 "jetbrains" => install_jetbrains_hook(),
1080 "kiro" => install_kiro_hook(),
1081 "verdent" => install_mcp_json_agent(
1082 "Verdent",
1083 "~/.verdent/mcp.json",
1084 &home.join(".verdent/mcp.json"),
1085 ),
1086 "opencode" => install_opencode_hook_with_mode(mode),
1087 "amp" => install_amp_hook(),
1088 "crush" => install_crush_hook_with_mode(mode),
1089 "openclaw" => install_openclaw_hook(),
1090 "hermes" => install_hermes_hook_with_mode(global, mode),
1091 "vibe" => install_vibe_hook(),
1092 "zed" => {
1093 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
1094 let binary = resolve_binary_path();
1095 let entry = full_server_entry(&binary);
1096 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
1097 }
1098 "aider" => {
1099 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
1100 }
1101 "continue" => install_mcp_json_agent(
1102 "Continue",
1103 "~/.continue/mcp.json",
1104 &home.join(".continue/mcp.json"),
1105 ),
1106 "neovim" => install_mcp_json_agent(
1107 "Neovim (mcphub.nvim)",
1108 "~/.config/mcphub/servers.json",
1109 &home.join(".config/mcphub/servers.json"),
1110 ),
1111 "emacs" => install_mcp_json_agent(
1112 "Emacs (mcp.el)",
1113 "~/.emacs.d/mcp.json",
1114 &home.join(".emacs.d/mcp.json"),
1115 ),
1116 "sublime" => install_mcp_json_agent(
1117 "Sublime Text",
1118 "~/.config/sublime-text/mcp.json",
1119 &home.join(".config/sublime-text/mcp.json"),
1120 ),
1121 _ => {
1122 eprintln!("Unknown agent: {agent}");
1123 eprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
1124 eprintln!(
1125 " claude, cline, codebuddy, codewhale, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, grok,"
1126 );
1127 eprintln!(
1128 " grok-build, hermes, jetbrains, kiro, neovim, omp, openclaw, opencode, pi, qoder,"
1129 );
1130 eprintln!(
1131 " qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vibe, vscode, windsurf, zed"
1132 );
1133 std::process::exit(1);
1134 }
1135 }
1136}
1137
1138pub(crate) fn install_agent_hook_respecting_rules_off(agent: &str, global: bool, mode: HookMode) {
1145 if crate::core::config::Config::load().rules_injection_effective()
1146 == crate::core::config::RulesInjection::Off
1147 {
1148 install_agent_runtime_hook_with_mode(agent, global, mode);
1149 } else {
1150 install_agent_hook_with_mode(agent, global, mode);
1151 }
1152}
1153
1154pub(crate) fn install_agent_runtime_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
1162 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
1163
1164 match agent {
1165 "claude" | "claude-code" => {
1166 install_claude_hook_scripts(&home);
1167 install_claude_hook_config(&home);
1168 install_claude_statusline(&home);
1169
1170 if mode == HookMode::Replace {
1171 install_claude_permissions_deny_replace(&home);
1172 }
1173
1174 install_claude_permissions_allow_mcp(&home);
1175 }
1176 "codebuddy" => {
1177 install_codebuddy_hook_scripts(&home);
1178 install_codebuddy_hook_config(&home);
1179
1180 if mode == HookMode::Replace {
1181 install_codebuddy_permissions_deny_replace(&home);
1182 }
1183 }
1184 "cursor" => {
1185 install_cursor_hook_scripts(&home);
1186 install_cursor_hook_config(&home);
1187
1188 if mode == HookMode::Replace {
1189 install_cursor_deny_hook(global);
1190 }
1191 }
1192 "gemini" => {
1193 install_gemini_hook_scripts(&home);
1194 install_gemini_hook_config(&home);
1195
1196 if mode == HookMode::Replace {
1197 install_gemini_deny_hook(&home);
1198 }
1199
1200 install_antigravity_cli_hook();
1204 }
1205 "codex" => install_codex_runtime_hook(),
1206 "windsurf" => {
1207 if mode == HookMode::Replace {
1208 install_windsurf_hooks_replace(&home);
1209 } else {
1210 install_windsurf_hooks(&home);
1211 }
1212 }
1213 "copilot" | "vscode" => install_copilot_runtime_hook(global),
1214 "qoder" | "qodercli" => install_qoder_runtime_hook_with_mode(mode),
1215
1216 "pi" => install_pi_hook_with_mode(global, mode),
1219
1220 "antigravity" => install_antigravity_hook(),
1223 "antigravity-cli" => install_antigravity_cli_hook(),
1224 "amp" => install_amp_hook(),
1225 "jetbrains" => install_jetbrains_hook(),
1226 "openclaw" => install_openclaw_hook(),
1227 "vibe" => install_vibe_hook(),
1228 _ => {}
1233 }
1234}
1235
1236pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
1237 match agent {
1238 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
1239 "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
1240 _ => {}
1241 }
1242}
1243
1244fn write_file(path: &std::path::Path, content: &str) {
1245 if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1248 return;
1249 }
1250 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
1251 tracing::error!("Error writing {}: {e}", path.display());
1252 }
1253}
1254
1255fn ensure_state_dir(dir: &std::path::Path) -> bool {
1264 match crate::config_io::ensure_dir(dir) {
1265 Ok(()) => true,
1266 Err(e) => {
1267 eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
1269 false
1270 }
1271 }
1272}
1273
1274fn is_inside_git_repo(path: &std::path::Path) -> bool {
1275 let mut p = path;
1276 loop {
1277 if p.join(".git").exists() {
1278 return true;
1279 }
1280 match p.parent() {
1281 Some(parent) => p = parent,
1282 None => return false,
1283 }
1284 }
1285}
1286
1287#[cfg(unix)]
1288fn make_executable(path: &PathBuf) {
1289 use std::os::unix::fs::PermissionsExt;
1290 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1291}
1292
1293#[cfg(not(unix))]
1294fn make_executable(_path: &PathBuf) {}
1295
1296pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
1318 Vec::new()
1319}
1320
1321pub(crate) fn mcp_server_env_json() -> serde_json::Value {
1323 let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
1324 .into_iter()
1325 .map(|(k, v)| (k, serde_json::Value::String(v)))
1326 .collect();
1327 serde_json::Value::Object(map)
1328}
1329
1330fn full_server_entry(binary: &str) -> serde_json::Value {
1331 serde_json::json!({
1337 "command": binary,
1338 "env": mcp_server_env_json()
1339 })
1340}
1341
1342pub(crate) fn install_mcp_json_agent(
1343 name: &str,
1344 display_path: &str,
1345 config_path: &std::path::Path,
1346) {
1347 let binary = resolve_binary_path();
1348 let entry = full_server_entry(&binary);
1349 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
1350}
1351
1352#[cfg(test)]
1353mod tests;