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 "qoder",
89 "qodercli",
90 "windsurf",
91 "amp",
92 "cline",
93 "roo",
94 "copilot",
95 "kiro",
96 "qwen",
97 "trae",
98 "antigravity",
99 "antigravity-cli",
100 "amazonq",
101 "verdent",
102];
103
104pub fn is_supported_agent(agent: &str) -> bool {
109 let key = agent.to_ascii_lowercase();
110 REPLACE_AGENTS.contains(&key.as_str()) || HYBRID_AGENTS.contains(&key.as_str())
111}
112
113pub fn recommend_hook_mode(agent_key: &str) -> HookMode {
123 let deny_suppressed = is_deny_suppressed();
124 if let Some(override_mode) = crate::core::config::Config::load().hook_mode_override() {
125 return if deny_suppressed {
126 override_mode.cap_at_hybrid()
127 } else {
128 override_mode
129 };
130 }
131 if deny_suppressed {
132 if REPLACE_AGENTS.contains(&agent_key) || HYBRID_AGENTS.contains(&agent_key) {
133 return HookMode::Hybrid;
134 }
135 return HookMode::Mcp;
136 }
137 if REPLACE_AGENTS.contains(&agent_key) {
138 HookMode::Replace
139 } else if HYBRID_AGENTS.contains(&agent_key) {
140 HookMode::Hybrid
141 } else {
142 HookMode::Mcp
143 }
144}
145
146fn is_deny_suppressed() -> bool {
148 if std::env::var("LEAN_CTX_DISABLED").is_ok() {
149 return true;
150 }
151 if matches!(std::env::var("LEAN_CTX_SHADOW_MODE"), Ok(v) if v.trim() == "false" || v.trim() == "0")
152 {
153 return true;
154 }
155 if matches!(std::env::var("LEAN_CTX_HEAL"), Ok(v) if v.trim().eq_ignore_ascii_case("off") || v.trim() == "0")
156 {
157 return true;
158 }
159 let cfg = crate::core::config::Config::load();
160 !cfg.shadow_mode
161}
162use agents::{
163 install_amp_hook, install_antigravity_cli_hook, install_antigravity_hook,
164 install_claude_hook_config, install_claude_hook_scripts, install_claude_hook_with_mode,
165 install_claude_permissions_deny_replace, install_claude_project_hooks, install_cline_rules,
166 install_codebuddy_hook_config, install_codebuddy_hook_scripts,
167 install_codebuddy_hook_with_mode, install_codebuddy_permissions_deny_replace,
168 install_codebuddy_project_hooks, install_codex_hook, install_copilot_hook,
169 install_crush_hook_with_mode, install_cursor_deny_hook, install_cursor_hook_config,
170 install_cursor_hook_scripts, install_cursor_hook_with_mode, install_gemini_deny_hook,
171 install_gemini_hook, install_gemini_hook_config, install_gemini_hook_scripts, install_grok_mcp,
172 install_hermes_hook_with_mode, install_jetbrains_hook, install_kiro_hook,
173 install_openclaw_hook, install_opencode_hook_with_mode, install_pi_hook_with_mode,
174 install_qoder_hook_with_mode, install_vibe_hook, install_windsurf_hooks,
175 install_windsurf_hooks_replace, install_windsurf_rules,
176};
177use support::{
178 ensure_codex_hooks_enabled, install_codex_instruction_docs, install_named_json_server,
179 upsert_lean_ctx_codex_hook_entries,
180};
181
182fn mcp_server_quiet_mode() -> bool {
183 crate::core::runtime_flags::mcp_server_enabled() || crate::core::runtime_flags::quiet_enabled()
184}
185
186const REFRESHABLE_HOOK_AGENTS: &[&str] = &[
194 "claude", "cursor", "gemini", "codex", "windsurf", "copilot", "qoder", "qodercli",
195];
196
197#[cfg(test)]
202const REFRESH_EXEMPT_HYBRID_AGENTS: &[&str] = &[
203 "claude-code",
205 "pi",
207 "cline",
210 "roo",
211 "kiro",
212 "antigravity",
215 "antigravity-cli",
216 "amp",
217 "crush",
218 "hermes",
219 "opencode",
220 "openclaw",
221 "qwen",
222 "trae",
223 "amazonq",
224 "verdent",
225];
226
227pub fn refresh_installed_hooks() {
232 let Some(home) = crate::core::home::resolve_home_dir() else {
233 return;
234 };
235 for agent in REFRESHABLE_HOOK_AGENTS {
236 if hooks_installed_for(agent, &home) {
237 refresh_agent_hooks(agent, &home);
238 }
239 }
240}
241
242fn hooks_installed_for(agent: &str, home: &std::path::Path) -> bool {
244 match agent {
245 "claude" => {
246 let dir = crate::setup::claude_config_dir(home);
247 dir.join("hooks/lean-ctx-rewrite.sh").exists()
248 || file_contains_lean_ctx(&dir.join("settings.json"))
249 }
250 "codebuddy" => {
251 let dir = crate::core::editor_registry::codebuddy_state_dir(home);
252 dir.join("hooks/lean-ctx-rewrite.sh").exists()
253 || file_contains_lean_ctx(&dir.join("settings.json"))
254 }
255 "cursor" => {
256 home.join(".cursor/hooks/lean-ctx-rewrite.sh").exists()
257 || file_contains_lean_ctx(&home.join(".cursor/hooks.json"))
258 }
259 "gemini" => {
260 home.join(".gemini/hooks/lean-ctx-rewrite-gemini.sh")
261 .exists()
262 || home.join(".gemini/hooks/lean-ctx-hook-gemini.sh").exists()
263 }
264 "codex" => {
265 let dir = crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
266 dir.join("hooks/lean-ctx-rewrite-codex.sh").exists()
267 || file_contains_lean_ctx(&dir.join("hooks.json"))
268 }
269 "windsurf" => file_contains_lean_ctx(&home.join(".codeium/windsurf/hooks.json")),
270 "copilot" => {
271 file_contains_lean_ctx(&home.join(".copilot/hooks/hooks.json"))
274 || file_contains_lean_ctx(&home.join(".github/hooks/hooks.json"))
275 }
276 "qoder" | "qodercli" => file_contains_lean_ctx(&home.join(".qoder/settings.json")),
277 _ => false,
278 }
279}
280
281fn refresh_agent_hooks(agent: &str, home: &std::path::Path) {
286 let mode = recommend_hook_mode(agent);
287 match agent {
288 "claude" => {
289 install_claude_hook_scripts(home);
290 install_claude_hook_config(home);
291 if mode == HookMode::Replace {
292 install_claude_permissions_deny_replace(home);
293 }
294 }
295 "codebuddy" => {
296 install_codebuddy_hook_scripts(home);
297 install_codebuddy_hook_config(home);
298 if mode == HookMode::Replace {
299 install_codebuddy_permissions_deny_replace(home);
300 }
301 }
302 "cursor" => {
303 install_cursor_hook_scripts(home);
304 install_cursor_hook_config(home);
305 if mode == HookMode::Replace {
306 install_cursor_deny_hook(true);
307 }
308 }
309 "gemini" => {
310 install_gemini_hook_scripts(home);
311 install_gemini_hook_config(home);
312 if mode == HookMode::Replace {
313 install_gemini_deny_hook(home);
314 }
315 }
316 "codex" => install_codex_hook(),
317 "windsurf" => {
318 if mode == HookMode::Replace {
319 install_windsurf_hooks_replace(home);
320 } else {
321 install_windsurf_hooks(home);
322 }
323 }
324 "copilot" => install_copilot_hook(true),
325 "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
326 _ => {}
327 }
328}
329
330fn file_contains_lean_ctx(path: &std::path::Path) -> bool {
331 std::fs::read_to_string(path).is_ok_and(|c| c.contains("lean-ctx"))
332}
333
334fn resolve_binary_path() -> String {
350 crate::core::portable_binary::resolve_portable_binary()
351}
352
353fn resolve_hook_command_binary() -> String {
364 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
365 return portable;
366 }
367 resolve_binary_path()
368}
369
370fn resolve_binary_path_for_bash() -> String {
371 if let Some(portable) = crate::core::portable_binary::hook_binary_override() {
372 return portable;
373 }
374 to_bash_compatible_path(&resolve_binary_path())
375}
376
377pub(crate) fn shell_quoted_binary(binary: &str) -> String {
384 let escaped = binary.replace('"', "\\\"").replace('`', "\\`");
385 format!("\"{escaped}\"")
386}
387
388fn wrapper_is_portable_and_working(path: &std::path::Path, home: &std::path::Path) -> bool {
397 std::fs::read_to_string(path)
398 .is_ok_and(|content| wrapper_content_is_portable_and_working(&content, home))
399}
400
401pub(crate) fn wrapper_content_is_portable_and_working(
402 content: &str,
403 home: &std::path::Path,
404) -> bool {
405 let Some(token) = wrapper_binary_token(content) else {
406 return false;
407 };
408 if !(token.contains("$HOME") || token.contains("${HOME}") || token.contains("%USERPROFILE%")) {
409 return false;
410 }
411 let home_s = home.to_string_lossy();
412 let expanded = token
413 .replace("${HOME}", &home_s)
414 .replace("$HOME", &home_s)
415 .replace("%USERPROFILE%", &home_s);
416 std::path::Path::new(&from_bash_to_native_path(&expanded)).exists()
417}
418
419pub(crate) fn wrapper_binary_token(content: &str) -> Option<String> {
423 for line in content.lines() {
424 let t = line.trim();
425 if let Some(rest) = t.strip_prefix("LEAN_CTX_BIN=") {
426 let rest = rest.trim();
427 let tok = rest
428 .strip_prefix('"')
429 .map_or(rest, |r| r.split('"').next().unwrap_or_default());
430 if !tok.is_empty() {
431 return Some(tok.to_string());
432 }
433 }
434 if let Some(rest) = t.strip_prefix("exec ") {
435 let rest = rest.trim();
436 let tok = match rest.strip_prefix('"') {
437 Some(r) => r.split('"').next().unwrap_or_default().to_string(),
438 None => rest
439 .split_whitespace()
440 .next()
441 .unwrap_or_default()
442 .to_string(),
443 };
444 if !tok.is_empty() {
445 return Some(tok);
446 }
447 }
448 }
449 None
450}
451
452fn write_wrapper_file(path: &std::path::Path, content: &str, home: &std::path::Path) {
457 if crate::core::portable_binary::hook_binary_override().is_none()
458 && wrapper_is_portable_and_working(path, home)
459 {
460 return;
461 }
462 write_file(path, content);
463}
464
465pub fn to_bash_compatible_path(path: &str) -> String {
466 let path = match crate::core::pathutil::strip_verbatim_str(path) {
467 Some(stripped) => stripped,
468 None => path.replace('\\', "/"),
469 };
470 if path.len() >= 2 && path.as_bytes()[1] == b':' {
471 let drive = (path.as_bytes()[0] as char).to_ascii_lowercase();
472 format!("/{drive}{}", &path[2..])
473 } else {
474 path
475 }
476}
477
478pub fn from_bash_to_native_path(path: &str) -> String {
481 crate::core::pathutil::normalize_tool_path(path)
482}
483
484pub fn normalize_tool_path(path: &str) -> String {
487 crate::core::pathutil::normalize_tool_path(path)
488}
489
490pub fn generate_rewrite_script(binary: &str) -> String {
491 let case_pattern = crate::rewrite_registry::bash_case_pattern();
492 let quoted_binary = shell_quoted_binary(binary);
496 format!(
497 r#"#!/usr/bin/env bash
498# lean-ctx PreToolUse hook — rewrites bash commands to lean-ctx equivalents
499set -euo pipefail
500
501LEAN_CTX_BIN={quoted_binary}
502
503INPUT=$(cat)
504TOOL=$(echo "$INPUT" | grep -oE '"tool_name":"([^"\\]|\\.)*"' | head -1 | sed 's/^"tool_name":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
505
506case "$TOOL" in
507 Bash|bash|PowerShell|powershell) ;;
508 *) exit 0 ;;
509esac
510
511CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g')
512
513if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then
514 exit 0
515fi
516
517# Skip multi-line commands: the grep/sed extraction above does not decode
518# JSON \n into real newlines, so lean-ctx -c would receive fused lines (#787).
519if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
520
521case "$CMD" in
522 {case_pattern})
523 # Shell-escape then JSON-escape (two passes)
524 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
525 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
526 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
527 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD"
528 ;;
529 *) exit 0 ;;
530esac
531"#
532 )
533}
534
535pub fn generate_compact_rewrite_script(binary: &str) -> String {
536 let case_pattern = crate::rewrite_registry::bash_case_pattern();
537 let quoted_binary = shell_quoted_binary(binary);
538 format!(
539 r#"#!/usr/bin/env bash
540# lean-ctx hook — rewrites shell commands
541set -euo pipefail
542LEAN_CTX_BIN={quoted_binary}
543INPUT=$(cat)
544CMD=$(echo "$INPUT" | grep -oE '"command":"([^"\\]|\\.)*"' | head -1 | sed 's/^"command":"//;s/"$//' | sed 's/\\"/"/g;s/\\\\/\\/g' 2>/dev/null || echo "")
545if [ -z "$CMD" ] || echo "$CMD" | grep -qE "^(lean-ctx |\"?$LEAN_CTX_BIN\"? )"; then exit 0; fi
546if printf '%s' "$CMD" | grep -qF '\n'; then exit 0; fi
547case "$CMD" in
548 {case_pattern})
549 SHELL_ESC=$(printf '%s' "$CMD" | sed 's/\\/\\\\/g;s/"/\\"/g')
550 REWRITE="\"$LEAN_CTX_BIN\" -c \"$SHELL_ESC\""
551 JSON_CMD=$(printf '%s' "$REWRITE" | sed 's/\\/\\\\/g;s/"/\\"/g')
552 printf '{{"hookSpecificOutput":{{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{{"command":"%s"}}}}}}' "$JSON_CMD" ;;
553 *) exit 0 ;;
554esac
555"#
556 )
557}
558
559const REDIRECT_SCRIPT_CLAUDE: &str = r"#!/usr/bin/env bash
560# lean-ctx PreToolUse hook — all native tools pass through
561# Read/Grep/ListFiles are allowed so Edit (which requires native Read) works.
562# The MCP instructions guide the AI to prefer ctx_read/ctx_search/ctx_tree.
563exit 0
564";
565
566const REDIRECT_SCRIPT_GENERIC: &str = r"#!/usr/bin/env bash
567# lean-ctx hook — all native tools pass through
568exit 0
569";
570
571pub fn hybrid_rules_content() -> String {
572 use crate::core::rules_canonical;
573 format!(
574 "{start}\n<!-- version: {version} -->\n\n\
575# lean-ctx \u{2014} Hybrid Mode (MCP reads + CLI commands)\n\n\
576{bullets}\n\n\
577{never}\n\n\
578{end}",
579 start = rules_canonical::START_MARK,
580 version = rules_canonical::RULES_VERSION,
581 bullets = rules_canonical::BULLETS,
582 never = rules_canonical::NEVER,
583 end = rules_canonical::END_MARK,
584 )
585}
586
587pub fn replace_rules_content() -> String {
588 use crate::core::rules_canonical;
589 format!(
590 "{start}\n<!-- version: {version} -->\n\n\
591# lean-ctx \u{2014} Replace Mode (native tools denied)\n\n\
592Native Read/Grep/Glob/Bash are denied by policy. Use ONLY ctx_* MCP tools:\n\
593- ctx_read for ALL file reads (cached, 10 modes, unchanged full/auto re-reads ~13 tokens)\n\
594- ctx_shell for ALL shell commands (95+ compression patterns)\n\
595- ctx_search instead of Grep/rg (compact results)\n\
596- ctx_tree instead of ls/find (compact directory maps)\n\
597- ctx_glob instead of Glob (file pattern matching)\n\n\
598Do NOT attempt native Read, Grep, Glob, or Bash \u{2014} they will be denied.\n\n\
599{end}",
600 start = rules_canonical::START_MARK,
601 version = rules_canonical::RULES_VERSION,
602 end = rules_canonical::END_MARK,
603 )
604}
605
606pub fn install_project_rules() {
607 install_project_rules_for_agents(&[]);
608}
609
610pub fn install_project_rules_for_agents(agents: &[&str]) {
613 if crate::core::config::Config::load().rules_scope_effective()
614 == crate::core::config::RulesScope::Global
615 {
616 return;
617 }
618
619 let cwd = std::env::current_dir().unwrap_or_default();
620
621 if !is_inside_git_repo(&cwd) {
622 eprintln!(
623 " Skipping project files: not inside a git repository.\n \
624 Run this command from your project root to create CLAUDE.md / AGENTS.md."
625 );
626 return;
627 }
628
629 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
630 if cwd == home {
631 eprintln!(
632 " Skipping project files: current directory is your home folder.\n \
633 Run this command from a project directory instead."
634 );
635 return;
636 }
637
638 let all = agents.is_empty();
639 let wants = |name: &str| all || agents.iter().any(|a| a.eq_ignore_ascii_case(name));
640
641 ensure_project_agents_integration(&cwd);
642
643 if wants("cursor") || wants("windsurf") {
644 let cursorrules = cwd.join(".cursorrules");
645 if !cursorrules.exists()
646 || !std::fs::read_to_string(&cursorrules)
647 .unwrap_or_default()
648 .contains("lean-ctx")
649 {
650 let content = cursorrules_content();
651 if cursorrules.exists() {
652 let mut existing = std::fs::read_to_string(&cursorrules).unwrap_or_default();
653 if !existing.ends_with('\n') {
654 existing.push('\n');
655 }
656 existing.push('\n');
657 existing.push_str(&content);
658 write_file(&cursorrules, &existing);
659 } else {
660 write_file(&cursorrules, &content);
661 }
662 if !mcp_server_quiet_mode() {
663 eprintln!("Created/updated .cursorrules in project root.");
664 }
665 }
666 }
667
668 if wants("claude") {
669 let claude_rules_file = cwd.join(".claude").join("rules").join("lean-ctx.md");
675 if let Ok(existing) = std::fs::read_to_string(&claude_rules_file)
676 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
677 && std::fs::remove_file(&claude_rules_file).is_ok()
678 && !mcp_server_quiet_mode()
679 {
680 eprintln!(
681 "Removed .claude/rules/lean-ctx.md (always-loaded duplicate; AGENTS.md block + skill replace it)."
682 );
683 }
684
685 install_claude_project_hooks(&cwd);
686 }
687
688 if wants("codebuddy") {
689 let codebuddy_rules_file = cwd.join(".codebuddy").join("rules").join("lean-ctx.md");
690 if let Ok(existing) = std::fs::read_to_string(&codebuddy_rules_file)
691 && existing.contains(crate::core::rules_canonical::RULES_MARKER_PREFIX)
692 && std::fs::remove_file(&codebuddy_rules_file).is_ok()
693 && !mcp_server_quiet_mode()
694 {
695 eprintln!(
696 "Removed .codebuddy/rules/lean-ctx.md (always-loaded duplicate; CODEBUDDY.md block + skill replace it)."
697 );
698 }
699
700 install_codebuddy_project_hooks(&cwd);
701 }
702
703 if wants("kiro") {
704 let kiro_dir = cwd.join(".kiro");
705 if kiro_dir.exists() {
706 let steering_dir = kiro_dir.join("steering");
707 let steering_file = steering_dir.join("lean-ctx.md");
708 if !steering_file.exists()
709 || !std::fs::read_to_string(&steering_file)
710 .unwrap_or_default()
711 .contains("lean-ctx")
712 {
713 let _ = std::fs::create_dir_all(&steering_dir);
714 write_file(&steering_file, &kiro_steering_content());
715 if !mcp_server_quiet_mode() {
716 eprintln!("Created .kiro/steering/lean-ctx.md (Kiro steering).");
717 }
718 }
719 }
720 }
721
722 if wants("copilot") || wants("vscode") {
723 ensure_copilot_instructions(&cwd);
724 ensure_vscode_instruction_files_setting(&cwd);
725 }
726}
727
728const PROJECT_LEAN_CTX_MD_MARKER: &str =
729 crate::core::rules_canonical::PROJECT_LEAN_CTX_OWNED_MARKER;
730const PROJECT_LEAN_CTX_MD: &str = "LEAN-CTX.md";
731const PROJECT_AGENTS_MD: &str = "AGENTS.md";
732const AGENTS_BLOCK_START: &str = crate::core::rules_canonical::AGENTS_BLOCK_START;
736const AGENTS_BLOCK_END: &str = crate::core::rules_canonical::AGENTS_BLOCK_END;
737
738fn ensure_project_agents_integration(cwd: &std::path::Path) {
739 let lean_ctx_md = cwd.join(PROJECT_LEAN_CTX_MD);
740 let desired = format!(
743 "{PROJECT_LEAN_CTX_MD_MARKER}\n{}\n",
744 crate::rules_inject::rules_longform_markdown()
745 );
746
747 if !lean_ctx_md.exists() {
748 write_file(&lean_ctx_md, &desired);
749 } else if std::fs::read_to_string(&lean_ctx_md)
750 .unwrap_or_default()
751 .contains(PROJECT_LEAN_CTX_MD_MARKER)
752 {
753 let current = std::fs::read_to_string(&lean_ctx_md).unwrap_or_default();
754 let version_str = format!(
755 "<!-- version: {} -->",
756 crate::core::rules_canonical::RULES_VERSION
757 );
758 if !current.contains(&version_str) {
759 write_file(&lean_ctx_md, &desired);
760 }
761 }
762
763 let block = format!(
768 "{AGENTS_BLOCK_START}\n\
769## lean-ctx\n\n\
770lean-ctx is active — the MCP tools replace native equivalents.\n\
771Full rules: {PROJECT_LEAN_CTX_MD} (open on demand — do not auto-load).\n\
772{AGENTS_BLOCK_END}\n"
773 );
774
775 let agents_md = cwd.join(PROJECT_AGENTS_MD);
776 if !agents_md.exists() {
777 let content = format!("# Agent Instructions\n\n{block}");
778 write_file(&agents_md, &content);
779 if !mcp_server_quiet_mode() {
780 eprintln!("Created AGENTS.md in project root (lean-ctx reference only).");
781 }
782 return;
783 }
784
785 let existing = std::fs::read_to_string(&agents_md).unwrap_or_default();
786
787 let has_block = crate::marked_block::contains_marker_line(&existing, AGENTS_BLOCK_START);
790
791 if existing.contains("CLI-first Token Optimization for Pi") && !has_block {
792 let content = format!("# Agent Instructions\n\n{block}");
793 write_file(&agents_md, &content);
794 return;
795 }
796
797 if has_block {
798 let updated = crate::marked_block::replace_marked_block(
799 &existing,
800 AGENTS_BLOCK_START,
801 AGENTS_BLOCK_END,
802 &block,
803 );
804 if updated != existing {
805 write_file(&agents_md, &updated);
806 }
807 return;
808 }
809
810 if existing.contains("lean-ctx") && existing.contains(PROJECT_LEAN_CTX_MD) {
811 return;
812 }
813
814 let mut out = existing;
815 if !out.ends_with('\n') {
816 out.push('\n');
817 }
818 out.push('\n');
819 out.push_str(&block);
820 write_file(&agents_md, &out);
821 if !mcp_server_quiet_mode() {
822 eprintln!("Updated AGENTS.md (added lean-ctx reference block).");
823 }
824}
825
826fn ensure_copilot_instructions(cwd: &std::path::Path) {
833 let path = cwd.join(".github").join("copilot-instructions.md");
834 let block = crate::rules_inject::rules_dedicated_markdown();
835 let start = crate::core::rules_canonical::START_MARK;
836 let end = crate::core::rules_canonical::END_MARK;
837 let owned = format!("{}\n", block.trim_end());
838
839 let existing = std::fs::read_to_string(&path).unwrap_or_default();
840 let desired = if existing.trim().is_empty() {
841 owned
842 } else if existing.contains(start) {
843 let user = crate::marked_block::remove_content(&existing, start, end);
845 if user.trim().is_empty() {
846 owned
847 } else {
848 format!("{}\n\n{}\n", user.trim_end(), block.trim_end())
849 }
850 } else {
851 format!("{}\n\n{}\n", existing.trim_end(), block.trim_end())
853 };
854
855 if desired == existing {
856 return;
857 }
858 if let Some(parent) = path.parent()
859 && std::fs::create_dir_all(parent).is_err()
860 {
861 return;
862 }
863 write_file(&path, &desired);
864 if !mcp_server_quiet_mode() {
865 eprintln!("Created/updated .github/copilot-instructions.md (Copilot/VS Code rules).");
866 }
867}
868
869fn ensure_vscode_instruction_files_setting(cwd: &std::path::Path) {
874 const KEY: &str = "github.copilot.chat.codeGeneration.useInstructionFiles";
875 let path = cwd.join(".vscode").join("settings.json");
876
877 let existing = std::fs::read_to_string(&path).unwrap_or_default();
878 let mut json = if existing.trim().is_empty() {
879 serde_json::json!({})
880 } else {
881 match crate::core::jsonc::parse_jsonc(&existing) {
882 Ok(v) if v.is_object() => v,
883 _ => return,
885 }
886 };
887 let Some(obj) = json.as_object_mut() else {
888 return;
889 };
890 if obj.contains_key(KEY) {
891 return;
892 }
893 obj.insert(KEY.to_string(), serde_json::Value::Bool(true));
894
895 if let Some(parent) = path.parent()
896 && std::fs::create_dir_all(parent).is_err()
897 {
898 return;
899 }
900 let Ok(formatted) = serde_json::to_string_pretty(&json) else {
901 return;
902 };
903 if crate::config_io::write_atomic_with_backup(&path, &formatted).is_ok()
904 && !mcp_server_quiet_mode()
905 {
906 eprintln!("Set {KEY} in .vscode/settings.json.");
907 }
908}
909
910pub fn cursorrules_content() -> String {
914 let start = crate::core::rules_canonical::START_MARK;
915 let end = crate::core::rules_canonical::END_MARK;
916 let version = crate::core::rules_canonical::RULES_VERSION;
917 format!(
918 "{start}\n<!-- version: {version} -->\n\n\
919# lean-ctx\n\n\
920{bullets}\n\n\
921{never}\n\
922Full rules: ~/.cursor/rules/lean-ctx.mdc (auto-loaded) \u{2014} do not duplicate here.\n\
923{end}",
924 bullets = crate::core::rules_canonical::BULLETS,
925 never = crate::core::rules_canonical::NEVER,
926 )
927}
928
929pub fn kiro_steering_content() -> String {
930 use crate::core::rules_canonical;
931 format!(
932 "---\n\
933inclusion: always\n\
934---\n\n\
935# Context Engineering Layer\n\n\
936{start}\n\
937<!-- version: {version} -->\n\n\
938The workspace has the `lean-ctx` MCP server installed. \
939You MUST prefer lean-ctx tools over native equivalents for token efficiency and caching.\n\n\
940{bullets}\n\n\
941{never}\n\n\
942## When to use native Kiro tools instead\n\n\
943- `fsWrite` / `fsAppend` \u{2014} always use native (lean-ctx doesn't write files)\n\
944- `strReplace` \u{2014} always use native (precise string replacement)\n\
945- `semanticRename` / `smartRelocate` \u{2014} always use native (IDE integration)\n\
946- `getDiagnostics` \u{2014} always use native (language server diagnostics)\n\
947- `deleteFile` \u{2014} always use native\n\
948- Glob \u{2014} always use native glob\n\n\
949{end}",
950 start = rules_canonical::START_MARK,
951 version = rules_canonical::RULES_VERSION,
952 bullets = rules_canonical::BULLETS,
953 never = rules_canonical::NEVER,
954 end = rules_canonical::END_MARK,
955 )
956}
957pub(crate) fn should_register_mcp() -> bool {
964 crate::core::config::Config::load()
965 .setup
966 .should_update_mcp()
967}
968
969pub fn install_agent_hook(agent: &str, global: bool) {
970 install_agent_hook_with_mode(agent, global, HookMode::Mcp);
971}
972
973pub fn install_agent_hook_with_mode(agent: &str, global: bool, mode: HookMode) {
974 let home = crate::core::home::resolve_home_dir().unwrap_or_default();
975 match agent {
976 "claude" | "claude-code" => install_claude_hook_with_mode(global, mode),
977 "codebuddy" => install_codebuddy_hook_with_mode(global, mode),
978 "cursor" => install_cursor_hook_with_mode(global, mode),
979 "gemini" => {
980 install_gemini_hook();
981 if mode == HookMode::Replace {
982 install_gemini_deny_hook(&home);
983 }
984 install_antigravity_cli_hook();
990 }
991 "grok" | "grok-build" => install_grok_mcp(),
992 "antigravity" => install_antigravity_hook(),
993 "antigravity-cli" => install_antigravity_cli_hook(),
994 "augment" => install_mcp_json_agent(
995 "Augment CLI",
996 "~/.augment/settings.json",
997 &crate::core::editor_registry::augment_cli_settings_path(&home),
998 ),
999 "codex" => {
1000 install_codex_hook();
1001 }
1002 "windsurf" => {
1003 install_windsurf_rules(global);
1004 if mode == HookMode::Replace {
1005 install_windsurf_hooks_replace(&home);
1006 }
1007 }
1008 "cline" | "roo" => install_cline_rules(global),
1009 "copilot" | "vscode" => install_copilot_hook(global),
1010 "vscode-insiders" | "commandcode" => {}
1017 "pi" => install_pi_hook_with_mode(global, mode),
1018 "qoder" | "qodercli" => install_qoder_hook_with_mode(mode),
1019 "qoderwork" => install_mcp_json_agent(
1020 "QoderWork",
1021 "~/.qoderwork/mcp.json",
1022 &home.join(".qoderwork/mcp.json"),
1023 ),
1024 "qwen" => install_mcp_json_agent(
1025 "Qwen Code",
1026 "~/.qwen/settings.json",
1027 &home.join(".qwen/settings.json"),
1028 ),
1029 "trae" => install_mcp_json_agent("Trae", "~/.trae/mcp.json", &home.join(".trae/mcp.json")),
1030 "amazonq" => install_mcp_json_agent(
1031 "Amazon Q Developer",
1032 "~/.aws/amazonq/default.json",
1033 &home.join(".aws/amazonq/default.json"),
1034 ),
1035 "jetbrains" => install_jetbrains_hook(),
1036 "kiro" => install_kiro_hook(),
1037 "verdent" => install_mcp_json_agent(
1038 "Verdent",
1039 "~/.verdent/mcp.json",
1040 &home.join(".verdent/mcp.json"),
1041 ),
1042 "opencode" => install_opencode_hook_with_mode(mode),
1043 "amp" => install_amp_hook(),
1044 "crush" => install_crush_hook_with_mode(mode),
1045 "openclaw" => install_openclaw_hook(),
1046 "hermes" => install_hermes_hook_with_mode(global, mode),
1047 "vibe" => install_vibe_hook(),
1048 "zed" => {
1049 let zed_path = crate::core::editor_registry::zed_settings_path(&home);
1050 let binary = resolve_binary_path();
1051 let entry = full_server_entry(&binary);
1052 install_named_json_server("Zed", "settings.json", &zed_path, "context_servers", entry);
1053 }
1054 "aider" => {
1055 install_mcp_json_agent("Aider", "~/.aider/mcp.json", &home.join(".aider/mcp.json"));
1056 }
1057 "continue" => install_mcp_json_agent(
1058 "Continue",
1059 "~/.continue/mcp.json",
1060 &home.join(".continue/mcp.json"),
1061 ),
1062 "neovim" => install_mcp_json_agent(
1063 "Neovim (mcphub.nvim)",
1064 "~/.config/mcphub/servers.json",
1065 &home.join(".config/mcphub/servers.json"),
1066 ),
1067 "emacs" => install_mcp_json_agent(
1068 "Emacs (mcp.el)",
1069 "~/.emacs.d/mcp.json",
1070 &home.join(".emacs.d/mcp.json"),
1071 ),
1072 "sublime" => install_mcp_json_agent(
1073 "Sublime Text",
1074 "~/.config/sublime-text/mcp.json",
1075 &home.join(".config/sublime-text/mcp.json"),
1076 ),
1077 _ => {
1078 eprintln!("Unknown agent: {agent}");
1079 eprintln!(" Supported: aider, amazonq, amp, antigravity, antigravity-cli, augment,");
1080 eprintln!(
1081 " claude, cline, codebuddy, codex, commandcode, continue, copilot, crush, cursor, emacs, gemini, grok,"
1082 );
1083 eprintln!(
1084 " grok-build, hermes, jetbrains, kiro, neovim, openclaw, opencode, pi, qoder,"
1085 );
1086 eprintln!(
1087 " qodercli, qoderwork, qwen, roo, sublime, trae, verdent, vibe, vscode, windsurf, zed"
1088 );
1089 std::process::exit(1);
1090 }
1091 }
1092}
1093
1094pub fn install_agent_project_hooks(agent: &str, cwd: &std::path::Path) {
1095 match agent {
1096 "claude" | "claude-code" => agents::install_claude_project_hooks(cwd),
1097 "codebuddy" => agents::install_codebuddy_project_hooks(cwd),
1098 _ => {}
1099 }
1100}
1101
1102fn write_file(path: &std::path::Path, content: &str) {
1103 if std::fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1106 return;
1107 }
1108 if let Err(e) = crate::config_io::write_atomic_with_backup(path, content) {
1109 tracing::error!("Error writing {}: {e}", path.display());
1110 }
1111}
1112
1113fn ensure_state_dir(dir: &std::path::Path) -> bool {
1122 match crate::config_io::ensure_dir(dir) {
1123 Ok(()) => true,
1124 Err(e) => {
1125 eprintln!("lean-ctx setup: cannot prepare {}: {e}", dir.display());
1127 false
1128 }
1129 }
1130}
1131
1132fn is_inside_git_repo(path: &std::path::Path) -> bool {
1133 let mut p = path;
1134 loop {
1135 if p.join(".git").exists() {
1136 return true;
1137 }
1138 match p.parent() {
1139 Some(parent) => p = parent,
1140 None => return false,
1141 }
1142 }
1143}
1144
1145#[cfg(unix)]
1146fn make_executable(path: &PathBuf) {
1147 use std::os::unix::fs::PermissionsExt;
1148 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755));
1149}
1150
1151#[cfg(not(unix))]
1152fn make_executable(_path: &PathBuf) {}
1153
1154pub(crate) fn mcp_server_env_pairs() -> Vec<(String, String)> {
1167 let mut pairs = Vec::new();
1168
1169 let cfg = crate::core::config::Config::load();
1170
1171 let project_root = std::env::var("LEAN_CTX_PROJECT_ROOT")
1172 .ok()
1173 .filter(|v| !v.trim().is_empty())
1174 .or_else(|| cfg.project_root.clone().filter(|v| !v.trim().is_empty()));
1175 if let Some(root) = project_root {
1176 pairs.push(("LEAN_CTX_PROJECT_ROOT".to_string(), root));
1177 }
1178
1179 let extra_roots = std::env::var("LEAN_CTX_EXTRA_ROOTS")
1182 .ok()
1183 .filter(|v| !v.trim().is_empty())
1184 .or_else(|| {
1185 let roots: Vec<&str> = cfg
1186 .extra_roots
1187 .iter()
1188 .map(String::as_str)
1189 .filter(|s| !s.trim().is_empty())
1190 .collect();
1191 if roots.is_empty() {
1192 return None;
1193 }
1194 std::env::join_paths(roots)
1195 .ok()
1196 .map(|s| s.to_string_lossy().to_string())
1197 });
1198 if let Some(extra) = extra_roots {
1199 pairs.push(("LEAN_CTX_EXTRA_ROOTS".to_string(), extra));
1200 }
1201
1202 pairs
1203}
1204
1205pub(crate) fn mcp_server_env_json() -> serde_json::Value {
1207 let map: serde_json::Map<String, serde_json::Value> = mcp_server_env_pairs()
1208 .into_iter()
1209 .map(|(k, v)| (k, serde_json::Value::String(v)))
1210 .collect();
1211 serde_json::Value::Object(map)
1212}
1213
1214fn full_server_entry(binary: &str) -> serde_json::Value {
1215 serde_json::json!({
1221 "command": binary,
1222 "env": mcp_server_env_json()
1223 })
1224}
1225
1226pub(crate) fn install_mcp_json_agent(
1227 name: &str,
1228 display_path: &str,
1229 config_path: &std::path::Path,
1230) {
1231 let binary = resolve_binary_path();
1232 let entry = full_server_entry(&binary);
1233 install_named_json_server(name, display_path, config_path, "mcpServers", entry);
1234}
1235
1236#[cfg(test)]
1237mod tests;