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