Skip to main content

lean_ctx/
rules_inject.rs

1use std::path::PathBuf;
2
3use serde::{Deserialize, Serialize};
4
5const MARKER: &str = "# lean-ctx — Context Engineering Layer";
6const END_MARKER: &str = "<!-- /lean-ctx -->";
7const RULES_VERSION: &str = "lean-ctx-rules-v9";
8
9pub const RULES_MARKER: &str = MARKER;
10pub const RULES_VERSION_STR: &str = RULES_VERSION;
11
12pub fn rules_dedicated_markdown() -> &'static str {
13    RULES_DEDICATED
14}
15
16// ---------------------------------------------------------------------------
17// Rules content for SHARED config files (appended to user's existing config).
18// LITM-optimized: critical instruction at START and END of block.
19// Used for: CLAUDE.md, instructions.md, GEMINI.md, copilot-instructions.md
20// ---------------------------------------------------------------------------
21const RULES_SHARED: &str = r"# lean-ctx — Context Engineering Layer
22<!-- lean-ctx-rules-v9 -->
23
24CRITICAL: ALWAYS use lean-ctx MCP tools instead of native equivalents. This is NOT optional.
25
26| ALWAYS USE | NEVER USE | Why |
27|------------|-----------|-----|
28| `ctx_read(path, mode)` | `Read` / `cat` / `head` / `tail` | Cached, 10 read modes, re-reads ~13 tokens |
29| `ctx_shell(command)` | `Shell` / `bash` / terminal | Pattern compression for git/npm/cargo output |
30| `ctx_search(pattern, path)` | `Grep` / `rg` | Compact, token-efficient results |
31| `ctx_tree(path, depth)` | `ls` / `find` | Compact directory maps |
32
33Mode selection: editing → `full` then `diff`; context only → `map` or `signatures`; unsure → `auto`.
34Anti-pattern: never use `full` for files you won't edit.
35
36Compatibility: ctx_read replaces READ operations only. Your native Edit/Write/StrReplace tools remain unchanged — keep using them for editing.
37
38If Edit requires native Read and Read is unavailable, use `ctx_edit(path, old_string, new_string)` instead.
39Write, Delete, Glob → use normally. NEVER loop on Edit failures — switch to ctx_edit immediately.
40
41Fallback only if a lean-ctx tool is unavailable: use native equivalents.
42<!-- /lean-ctx -->";
43
44// ---------------------------------------------------------------------------
45// Rules content for DEDICATED lean-ctx rule files (we control entire file).
46// LITM-optimized with critical mapping at start and end.
47// Used for: Windsurf, Zed, Cline, Roo Code, OpenCode, Continue, Aider
48// ---------------------------------------------------------------------------
49const RULES_DEDICATED: &str = r"# lean-ctx — Context Engineering Layer
50<!-- lean-ctx-rules-v9 -->
51
52PREFER lean-ctx MCP tools over native equivalents for token savings:
53
54## Tool preference:
55| PREFER | OVER | Why |
56|--------|------|-----|
57| `ctx_read(path, mode)` | `Read` / `cat` | Cached, 10 read modes, re-reads ~13 tokens |
58| `ctx_shell(command)` | `Shell` / `bash` | Pattern compression for git/npm/cargo output |
59| `ctx_search(pattern, path)` | `Grep` / `rg` | Compact, token-efficient results |
60| `ctx_tree(path, depth)` | `ls` / `find` | Compact directory maps |
61| `ctx_edit(path, old_string, new_string)` | `Edit` (when Read unavailable) | Search-and-replace without native Read |
62
63## ctx_read modes:
64- `auto` — auto-select optimal mode (recommended default)
65- `full` — cached read (files you edit)
66- `map` — deps + exports (context-only files)
67- `signatures` — API surface only
68- `diff` — changed lines after edits
69- `aggressive` — maximum compression (context only)
70- `entropy` — highlight high-entropy fragments
71- `task` — IB-filtered (task relevant)
72- `reference` — quote-friendly minimal excerpts
73- `lines:N-M` — specific range
74
75## Mode selection:
761. Editing the file? → `full` first, then `diff` for re-reads
772. Need API surface only? → `map` or `signatures`
783. Large file, context only? → `entropy` or `aggressive`
794. Specific lines? → `lines:N-M`
805. Active task set? → `task`
816. Unsure? → `auto` (system selects optimal mode)
82
83Anti-pattern: never use `full` for files you won't edit — use `map` or `signatures`.
84
85## File editing:
86Use native Edit/StrReplace if available. If Edit requires Read and Read is unavailable, use ctx_edit.
87Write, Delete, Glob → use normally. NEVER loop on Edit failures — switch to ctx_edit immediately.
88
89## Proactive (use without being asked):
90- `ctx_overview(task)` at session start
91- `ctx_compress` when context grows large
92<!-- /lean-ctx -->";
93
94// ---------------------------------------------------------------------------
95// Rules for Cursor MDC format (dedicated file with frontmatter).
96// ---------------------------------------------------------------------------
97const RULES_CURSOR_MDC: &str = include_str!("templates/lean-ctx.mdc");
98const RULES_CURSOR_MDC_CLI_REDIRECT: &str = include_str!("templates/lean-ctx-cli-redirect.mdc");
99
100// ---------------------------------------------------------------------------
101
102struct RulesTarget {
103    name: &'static str,
104    path: PathBuf,
105    format: RulesFormat,
106}
107
108enum RulesFormat {
109    SharedMarkdown,
110    DedicatedMarkdown,
111    CursorMdc,
112    DedicatedCliRedirect,
113    CursorMdcCliRedirect,
114}
115
116pub struct InjectResult {
117    pub injected: Vec<String>,
118    pub updated: Vec<String>,
119    pub already: Vec<String>,
120    pub errors: Vec<String>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct RulesTargetStatus {
125    pub name: String,
126    pub detected: bool,
127    pub path: String,
128    pub state: String,
129    pub note: Option<String>,
130}
131
132pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
133    if crate::core::config::Config::load().rules_scope_effective()
134        == crate::core::config::RulesScope::Project
135    {
136        return InjectResult {
137            injected: Vec::new(),
138            updated: Vec::new(),
139            already: Vec::new(),
140            errors: Vec::new(),
141        };
142    }
143
144    let targets = build_rules_targets(home);
145
146    let mut result = InjectResult {
147        injected: Vec::new(),
148        updated: Vec::new(),
149        already: Vec::new(),
150        errors: Vec::new(),
151    };
152
153    for target in &targets {
154        if !is_tool_detected(target, home) {
155            continue;
156        }
157
158        match inject_rules(target) {
159            Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
160            Ok(RulesResult::Updated) => result.updated.push(target.name.to_string()),
161            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
162            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
163        }
164    }
165
166    result
167}
168
169/// Check if the rules file for a given MCP client is up-to-date.
170/// Returns `Some(message)` if rules are stale/missing, `None` if current.
171pub fn check_rules_freshness(client_name: &str) -> Option<String> {
172    let home = dirs::home_dir()?;
173    let targets = build_rules_targets(&home);
174
175    let needle = client_name.to_lowercase();
176    let matched: Vec<&RulesTarget> = targets
177        .iter()
178        .filter(|t| {
179            let tn = t.name.to_lowercase();
180            needle.contains(&tn)
181                || tn.contains(&needle)
182                || (needle.contains("cursor") && tn.contains("cursor"))
183                || (needle.contains("claude") && tn.contains("claude"))
184                || (needle.contains("windsurf") && tn.contains("windsurf"))
185                || (needle.contains("codex") && tn.contains("claude"))
186                || (needle.contains("zed") && tn.contains("zed"))
187                || (needle.contains("copilot") && tn.contains("copilot"))
188                || (needle.contains("jetbrains") && tn.contains("jetbrains"))
189                || (needle.contains("kiro") && tn.contains("kiro"))
190                || (needle.contains("gemini") && tn.contains("gemini"))
191        })
192        .collect();
193
194    if matched.is_empty() {
195        return None;
196    }
197
198    for target in &matched {
199        if !target.path.exists() {
200            continue;
201        }
202        let content = std::fs::read_to_string(&target.path).ok()?;
203        if content.contains(MARKER) && !content.contains(RULES_VERSION) {
204            return Some(format!(
205                "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
206                 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
207                 then start a new session for full compatibility.",
208                target.name,
209                target.path.display()
210            ));
211        }
212    }
213
214    None
215}
216
217pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
218    let targets = build_rules_targets(home);
219    let mut out = Vec::new();
220
221    for target in &targets {
222        let detected = is_tool_detected(target, home);
223        let path = target.path.to_string_lossy().to_string();
224
225        let state = if !detected {
226            "not_detected".to_string()
227        } else if !target.path.exists() {
228            "missing".to_string()
229        } else {
230            match std::fs::read_to_string(&target.path) {
231                Ok(content) => {
232                    if content.contains(MARKER) {
233                        if content.contains(RULES_VERSION) {
234                            "up_to_date".to_string()
235                        } else {
236                            "outdated".to_string()
237                        }
238                    } else {
239                        "present_without_marker".to_string()
240                    }
241                }
242                Err(_) => "read_error".to_string(),
243            }
244        };
245
246        out.push(RulesTargetStatus {
247            name: target.name.to_string(),
248            detected,
249            path,
250            state,
251            note: None,
252        });
253    }
254
255    out
256}
257
258// ---------------------------------------------------------------------------
259// Injection logic
260// ---------------------------------------------------------------------------
261
262enum RulesResult {
263    Injected,
264    Updated,
265    AlreadyPresent,
266}
267
268fn rules_content(format: &RulesFormat) -> &'static str {
269    match format {
270        RulesFormat::SharedMarkdown => RULES_SHARED,
271        RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
272        RulesFormat::CursorMdc => RULES_CURSOR_MDC,
273        RulesFormat::DedicatedCliRedirect => crate::hooks::CLI_REDIRECT_RULES,
274        RulesFormat::CursorMdcCliRedirect => RULES_CURSOR_MDC_CLI_REDIRECT,
275    }
276}
277
278fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
279    if target.path.exists() {
280        let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
281        if content.contains(MARKER) {
282            if content.contains(RULES_VERSION) {
283                return Ok(RulesResult::AlreadyPresent);
284            }
285            ensure_parent(&target.path)?;
286            return match target.format {
287                RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
288                RulesFormat::DedicatedMarkdown
289                | RulesFormat::DedicatedCliRedirect
290                | RulesFormat::CursorMdc
291                | RulesFormat::CursorMdcCliRedirect => {
292                    write_dedicated(&target.path, rules_content(&target.format))
293                }
294            };
295        }
296    }
297
298    ensure_parent(&target.path)?;
299
300    match target.format {
301        RulesFormat::SharedMarkdown => append_to_shared(&target.path),
302        RulesFormat::DedicatedMarkdown
303        | RulesFormat::DedicatedCliRedirect
304        | RulesFormat::CursorMdc
305        | RulesFormat::CursorMdcCliRedirect => {
306            write_dedicated(&target.path, rules_content(&target.format))
307        }
308    }
309}
310
311fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
312    if let Some(parent) = path.parent() {
313        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
314    }
315    Ok(())
316}
317
318fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
319    let mut content = if path.exists() {
320        std::fs::read_to_string(path).map_err(|e| e.to_string())?
321    } else {
322        String::new()
323    };
324
325    if !content.is_empty() && !content.ends_with('\n') {
326        content.push('\n');
327    }
328    if !content.is_empty() {
329        content.push('\n');
330    }
331    content.push_str(RULES_SHARED);
332    content.push('\n');
333
334    std::fs::write(path, content).map_err(|e| e.to_string())?;
335    Ok(RulesResult::Injected)
336}
337
338fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
339    let start = content.find(MARKER);
340    let end = content.find(END_MARKER);
341
342    let new_content = match (start, end) {
343        (Some(s), Some(e)) => {
344            let before = &content[..s];
345            let after_end = e + END_MARKER.len();
346            let after = content[after_end..].trim_start_matches('\n');
347            let mut result = before.to_string();
348            result.push_str(RULES_SHARED);
349            if !after.is_empty() {
350                result.push('\n');
351                result.push_str(after);
352            }
353            result
354        }
355        (Some(s), None) => {
356            let before = &content[..s];
357            let mut result = before.to_string();
358            result.push_str(RULES_SHARED);
359            result.push('\n');
360            result
361        }
362        _ => return Ok(RulesResult::AlreadyPresent),
363    };
364
365    std::fs::write(path, new_content).map_err(|e| e.to_string())?;
366    Ok(RulesResult::Updated)
367}
368
369fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
370    let is_update = path.exists() && {
371        let existing = std::fs::read_to_string(path).unwrap_or_default();
372        existing.contains(MARKER)
373    };
374
375    std::fs::write(path, content).map_err(|e| e.to_string())?;
376
377    if is_update {
378        Ok(RulesResult::Updated)
379    } else {
380        Ok(RulesResult::Injected)
381    }
382}
383
384// ---------------------------------------------------------------------------
385// Tool detection
386// ---------------------------------------------------------------------------
387
388fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
389    match target.name {
390        "Claude Code" => {
391            if command_exists("claude") {
392                return true;
393            }
394            let state_dir = crate::core::editor_registry::claude_state_dir(home);
395            crate::core::editor_registry::claude_mcp_json_path(home).exists() || state_dir.exists()
396        }
397        "Codex CLI" => {
398            let codex_dir =
399                crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
400            codex_dir.exists() || command_exists("codex")
401        }
402        "Cursor" => home.join(".cursor").exists(),
403        "Windsurf" => home.join(".codeium/windsurf").exists(),
404        "Gemini CLI" => home.join(".gemini").exists(),
405        "VS Code / Copilot" => detect_vscode_installed(home),
406        "Zed" => home.join(".config/zed").exists(),
407        "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
408        "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
409        "OpenCode" => home.join(".config/opencode").exists(),
410        "Continue" => detect_extension_installed(home, "continue.continue"),
411        "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
412        "Qwen Code" => home.join(".qwen").exists(),
413        "Trae" => home.join(".trae").exists(),
414        "Amazon Q Developer" => home.join(".aws/amazonq").exists(),
415        "JetBrains IDEs" => detect_jetbrains_installed(home),
416        "Antigravity" => home.join(".gemini/antigravity").exists(),
417        "Pi Coding Agent" => home.join(".pi").exists() || command_exists("pi"),
418        "AWS Kiro" => home.join(".kiro").exists(),
419        "Crush" => home.join(".config/crush").exists() || command_exists("crush"),
420        "Verdent" => home.join(".verdent").exists(),
421        _ => false,
422    }
423}
424
425fn command_exists(name: &str) -> bool {
426    #[cfg(target_os = "windows")]
427    let result = std::process::Command::new("where")
428        .arg(name)
429        .output()
430        .is_ok_and(|o| o.status.success());
431
432    #[cfg(not(target_os = "windows"))]
433    let result = std::process::Command::new("which")
434        .arg(name)
435        .output()
436        .is_ok_and(|o| o.status.success());
437
438    result
439}
440
441fn detect_vscode_installed(_home: &std::path::Path) -> bool {
442    let check_dir = |dir: PathBuf| -> bool {
443        dir.join("settings.json").exists() || dir.join("mcp.json").exists()
444    };
445
446    #[cfg(target_os = "macos")]
447    if check_dir(_home.join("Library/Application Support/Code/User")) {
448        return true;
449    }
450    #[cfg(target_os = "linux")]
451    if check_dir(_home.join(".config/Code/User")) {
452        return true;
453    }
454    #[cfg(target_os = "windows")]
455    if let Ok(appdata) = std::env::var("APPDATA") {
456        if check_dir(PathBuf::from(&appdata).join("Code/User")) {
457            return true;
458        }
459    }
460    false
461}
462
463fn detect_jetbrains_installed(home: &std::path::Path) -> bool {
464    #[cfg(target_os = "macos")]
465    if home.join("Library/Application Support/JetBrains").exists() {
466        return true;
467    }
468    #[cfg(target_os = "linux")]
469    if home.join(".config/JetBrains").exists() {
470        return true;
471    }
472    home.join(".jb-mcp.json").exists()
473}
474
475fn detect_extension_installed(_home: &std::path::Path, extension_id: &str) -> bool {
476    #[cfg(target_os = "macos")]
477    {
478        if _home
479            .join(format!(
480                "Library/Application Support/Code/User/globalStorage/{extension_id}"
481            ))
482            .exists()
483        {
484            return true;
485        }
486    }
487    #[cfg(target_os = "linux")]
488    {
489        if _home
490            .join(format!(".config/Code/User/globalStorage/{extension_id}"))
491            .exists()
492        {
493            return true;
494        }
495    }
496    #[cfg(target_os = "windows")]
497    {
498        if let Ok(appdata) = std::env::var("APPDATA") {
499            if std::path::PathBuf::from(&appdata)
500                .join(format!("Code/User/globalStorage/{extension_id}"))
501                .exists()
502            {
503                return true;
504            }
505        }
506    }
507    false
508}
509
510// ---------------------------------------------------------------------------
511// Target definitions
512// ---------------------------------------------------------------------------
513
514fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
515    let cursor_mode = crate::hooks::recommend_hook_mode("cursor");
516    let opencode_mode = crate::hooks::recommend_hook_mode("opencode");
517    let crush_mode = crate::hooks::recommend_hook_mode("crush");
518    let claude_mode = crate::hooks::recommend_hook_mode("claude");
519
520    vec![
521        // --- Shared config files (append-only) ---
522        RulesTarget {
523            name: "Claude Code",
524            path: crate::core::editor_registry::claude_rules_dir(home).join("lean-ctx.md"),
525            format: if matches!(claude_mode, crate::hooks::HookMode::CliRedirect) {
526                RulesFormat::DedicatedCliRedirect
527            } else {
528                RulesFormat::DedicatedMarkdown
529            },
530        },
531        RulesTarget {
532            name: "Gemini CLI",
533            path: home.join(".gemini/GEMINI.md"),
534            format: RulesFormat::SharedMarkdown,
535        },
536        RulesTarget {
537            name: "VS Code / Copilot",
538            path: copilot_instructions_path(home),
539            format: RulesFormat::SharedMarkdown,
540        },
541        // --- Dedicated lean-ctx rule files ---
542        RulesTarget {
543            name: "Cursor",
544            path: home.join(".cursor/rules/lean-ctx.mdc"),
545            format: if matches!(cursor_mode, crate::hooks::HookMode::CliRedirect) {
546                RulesFormat::CursorMdcCliRedirect
547            } else {
548                RulesFormat::CursorMdc
549            },
550        },
551        RulesTarget {
552            name: "Windsurf",
553            path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
554            format: RulesFormat::DedicatedMarkdown,
555        },
556        RulesTarget {
557            name: "Zed",
558            path: home.join(".config/zed/rules/lean-ctx.md"),
559            format: RulesFormat::DedicatedMarkdown,
560        },
561        RulesTarget {
562            name: "Cline",
563            path: home.join(".cline/rules/lean-ctx.md"),
564            format: RulesFormat::DedicatedMarkdown,
565        },
566        RulesTarget {
567            name: "Roo Code",
568            path: home.join(".roo/rules/lean-ctx.md"),
569            format: RulesFormat::DedicatedMarkdown,
570        },
571        RulesTarget {
572            name: "OpenCode",
573            path: home.join(".config/opencode/rules/lean-ctx.md"),
574            format: if matches!(opencode_mode, crate::hooks::HookMode::CliRedirect) {
575                RulesFormat::DedicatedCliRedirect
576            } else {
577                RulesFormat::DedicatedMarkdown
578            },
579        },
580        RulesTarget {
581            name: "Continue",
582            path: home.join(".continue/rules/lean-ctx.md"),
583            format: RulesFormat::DedicatedMarkdown,
584        },
585        RulesTarget {
586            name: "Amp",
587            path: home.join(".ampcoder/rules/lean-ctx.md"),
588            format: RulesFormat::DedicatedMarkdown,
589        },
590        RulesTarget {
591            name: "Qwen Code",
592            path: home.join(".qwen/rules/lean-ctx.md"),
593            format: RulesFormat::DedicatedMarkdown,
594        },
595        RulesTarget {
596            name: "Trae",
597            path: home.join(".trae/rules/lean-ctx.md"),
598            format: RulesFormat::DedicatedMarkdown,
599        },
600        RulesTarget {
601            name: "Amazon Q Developer",
602            path: home.join(".aws/amazonq/rules/lean-ctx.md"),
603            format: RulesFormat::DedicatedMarkdown,
604        },
605        RulesTarget {
606            name: "JetBrains IDEs",
607            path: home.join(".jb-rules/lean-ctx.md"),
608            format: RulesFormat::DedicatedMarkdown,
609        },
610        RulesTarget {
611            name: "Antigravity",
612            path: home.join(".gemini/antigravity/rules/lean-ctx.md"),
613            format: RulesFormat::DedicatedMarkdown,
614        },
615        RulesTarget {
616            name: "Pi Coding Agent",
617            path: home.join(".pi/rules/lean-ctx.md"),
618            format: RulesFormat::DedicatedMarkdown,
619        },
620        RulesTarget {
621            name: "AWS Kiro",
622            path: home.join(".kiro/steering/lean-ctx.md"),
623            format: RulesFormat::DedicatedMarkdown,
624        },
625        RulesTarget {
626            name: "Verdent",
627            path: home.join(".verdent/rules/lean-ctx.md"),
628            format: RulesFormat::DedicatedMarkdown,
629        },
630        RulesTarget {
631            name: "Crush",
632            path: home.join(".config/crush/rules/lean-ctx.md"),
633            format: if matches!(crush_mode, crate::hooks::HookMode::CliRedirect) {
634                RulesFormat::DedicatedCliRedirect
635            } else {
636                RulesFormat::DedicatedMarkdown
637            },
638        },
639    ]
640}
641
642fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
643    #[cfg(target_os = "macos")]
644    {
645        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
646    }
647    #[cfg(target_os = "linux")]
648    {
649        return home.join(".config/Code/User/github-copilot-instructions.md");
650    }
651    #[cfg(target_os = "windows")]
652    {
653        if let Ok(appdata) = std::env::var("APPDATA") {
654            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
655        }
656    }
657    #[allow(unreachable_code)]
658    home.join(".config/Code/User/github-copilot-instructions.md")
659}
660
661// ---------------------------------------------------------------------------
662// SKILL.md installation
663// ---------------------------------------------------------------------------
664
665const SKILL_TEMPLATE: &str = include_str!("templates/SKILL.md");
666
667struct SkillTarget {
668    agent_key: &'static str,
669    display_name: &'static str,
670    skill_dir: PathBuf,
671}
672
673fn build_skill_targets(home: &std::path::Path) -> Vec<SkillTarget> {
674    vec![
675        SkillTarget {
676            agent_key: "claude",
677            display_name: "Claude Code",
678            skill_dir: home.join(".claude/skills/lean-ctx"),
679        },
680        SkillTarget {
681            agent_key: "cursor",
682            display_name: "Cursor",
683            skill_dir: home.join(".cursor/skills/lean-ctx"),
684        },
685        SkillTarget {
686            agent_key: "codex",
687            display_name: "Codex CLI",
688            skill_dir: crate::core::home::resolve_codex_dir()
689                .unwrap_or_else(|| home.join(".codex"))
690                .join("skills/lean-ctx"),
691        },
692        SkillTarget {
693            agent_key: "copilot",
694            display_name: "GitHub Copilot",
695            skill_dir: home.join(".vscode/skills/lean-ctx"),
696        },
697    ]
698}
699
700fn is_skill_agent_detected(agent_key: &str, home: &std::path::Path) -> bool {
701    match agent_key {
702        "claude" => {
703            command_exists("claude")
704                || crate::core::editor_registry::claude_mcp_json_path(home).exists()
705                || crate::core::editor_registry::claude_state_dir(home).exists()
706        }
707        "cursor" => home.join(".cursor").exists(),
708        "codex" => {
709            let codex_dir =
710                crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
711            codex_dir.exists() || command_exists("codex")
712        }
713        "copilot" => {
714            home.join(".vscode").exists()
715                || crate::core::editor_registry::vscode_mcp_path().exists()
716                || command_exists("code")
717        }
718        _ => false,
719    }
720}
721
722/// Install SKILL.md for a specific agent. Returns the installed path.
723pub fn install_skill_for_agent(home: &std::path::Path, agent_key: &str) -> Result<PathBuf, String> {
724    let targets = build_skill_targets(home);
725    let target = targets
726        .into_iter()
727        .find(|t| t.agent_key == agent_key)
728        .ok_or_else(|| format!("No skill target for agent '{agent_key}'"))?;
729
730    let skill_path = target.skill_dir.join("SKILL.md");
731    std::fs::create_dir_all(&target.skill_dir).map_err(|e| e.to_string())?;
732
733    if skill_path.exists() {
734        let existing = std::fs::read_to_string(&skill_path).unwrap_or_default();
735        if existing == SKILL_TEMPLATE {
736            return Ok(skill_path);
737        }
738    }
739
740    std::fs::write(&skill_path, SKILL_TEMPLATE).map_err(|e| e.to_string())?;
741    Ok(skill_path)
742}
743
744/// Install SKILL.md for all detected agents.
745/// Returns `Vec<(display_name, was_new_or_updated)>`.
746pub fn install_all_skills(home: &std::path::Path) -> Vec<(String, bool)> {
747    let targets = build_skill_targets(home);
748    let mut results = Vec::new();
749
750    for target in &targets {
751        if !is_skill_agent_detected(target.agent_key, home) {
752            continue;
753        }
754
755        let skill_path = target.skill_dir.join("SKILL.md");
756        let already_current = skill_path.exists()
757            && std::fs::read_to_string(&skill_path).is_ok_and(|c| c == SKILL_TEMPLATE);
758
759        if already_current {
760            results.push((target.display_name.to_string(), false));
761            continue;
762        }
763
764        if let Err(e) = std::fs::create_dir_all(&target.skill_dir) {
765            tracing::warn!(
766                "Failed to create skill dir for {}: {e}",
767                target.display_name
768            );
769            continue;
770        }
771
772        match std::fs::write(&skill_path, SKILL_TEMPLATE) {
773            Ok(()) => results.push((target.display_name.to_string(), true)),
774            Err(e) => {
775                tracing::warn!("Failed to write SKILL.md for {}: {e}", target.display_name);
776            }
777        }
778    }
779
780    results
781}
782
783// ---------------------------------------------------------------------------
784// Tests
785// ---------------------------------------------------------------------------
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790
791    #[test]
792    fn shared_rules_have_markers() {
793        assert!(RULES_SHARED.contains(MARKER));
794        assert!(RULES_SHARED.contains(END_MARKER));
795        assert!(RULES_SHARED.contains(RULES_VERSION));
796    }
797
798    #[test]
799    fn dedicated_rules_have_markers() {
800        assert!(RULES_DEDICATED.contains(MARKER));
801        assert!(RULES_DEDICATED.contains(END_MARKER));
802        assert!(RULES_DEDICATED.contains(RULES_VERSION));
803    }
804
805    #[test]
806    fn cursor_mdc_has_markers_and_frontmatter() {
807        assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
808        assert!(RULES_CURSOR_MDC.contains(END_MARKER));
809        assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
810        assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
811    }
812
813    #[test]
814    fn shared_rules_contain_tool_mapping() {
815        assert!(RULES_SHARED.contains("ctx_read"));
816        assert!(RULES_SHARED.contains("ctx_shell"));
817        assert!(RULES_SHARED.contains("ctx_search"));
818        assert!(RULES_SHARED.contains("ctx_tree"));
819        assert!(RULES_SHARED.contains("Write"));
820    }
821
822    #[test]
823    fn shared_rules_litm_optimized() {
824        let lines: Vec<&str> = RULES_SHARED.lines().collect();
825        let first_5 = lines[..5.min(lines.len())].join("\n");
826        assert!(
827            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
828            "LITM: preference instruction must be near start"
829        );
830        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
831        assert!(
832            last_5.contains("fallback") || last_5.contains("native"),
833            "LITM: fallback note must be near end"
834        );
835    }
836
837    #[test]
838    fn dedicated_rules_contain_modes() {
839        assert!(RULES_DEDICATED.contains("auto"));
840        assert!(RULES_DEDICATED.contains("full"));
841        assert!(RULES_DEDICATED.contains("map"));
842        assert!(RULES_DEDICATED.contains("signatures"));
843        assert!(RULES_DEDICATED.contains("diff"));
844        assert!(RULES_DEDICATED.contains("aggressive"));
845        assert!(RULES_DEDICATED.contains("entropy"));
846        assert!(RULES_DEDICATED.contains("task"));
847        assert!(RULES_DEDICATED.contains("reference"));
848        assert!(RULES_DEDICATED.contains("ctx_read"));
849    }
850
851    #[test]
852    fn dedicated_rules_litm_optimized() {
853        let lines: Vec<&str> = RULES_DEDICATED.lines().collect();
854        let first_5 = lines[..5.min(lines.len())].join("\n");
855        assert!(
856            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
857            "LITM: preference instruction must be near start"
858        );
859        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
860        assert!(
861            last_5.contains("fallback") || last_5.contains("ctx_compress"),
862            "LITM: practical note must be near end"
863        );
864    }
865
866    #[test]
867    fn cursor_mdc_litm_optimized() {
868        let lines: Vec<&str> = RULES_CURSOR_MDC.lines().collect();
869        let first_10 = lines[..10.min(lines.len())].join("\n");
870        assert!(
871            first_10.contains("PREFER") || first_10.contains("lean-ctx"),
872            "LITM: preference instruction must be near start of MDC"
873        );
874        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
875        assert!(
876            last_5.contains("fallback") || last_5.contains("native"),
877            "LITM: fallback note must be near end of MDC"
878        );
879    }
880
881    fn ensure_temp_dir() {
882        let tmp = std::env::temp_dir();
883        if !tmp.exists() {
884            std::fs::create_dir_all(&tmp).ok();
885        }
886    }
887
888    #[test]
889    fn replace_section_with_end_marker() {
890        ensure_temp_dir();
891        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\n<!-- lean-ctx-rules-v2 -->\nold rules\n<!-- /lean-ctx -->\nmore user stuff\n";
892        let path = std::env::temp_dir().join("test_replace_with_end.md");
893        std::fs::write(&path, old).unwrap();
894
895        let result = replace_markdown_section(&path, old).unwrap();
896        assert!(matches!(result, RulesResult::Updated));
897
898        let new_content = std::fs::read_to_string(&path).unwrap();
899        assert!(new_content.contains(RULES_VERSION));
900        assert!(new_content.starts_with("user stuff"));
901        assert!(new_content.contains("more user stuff"));
902        assert!(!new_content.contains("lean-ctx-rules-v2"));
903
904        std::fs::remove_file(&path).ok();
905    }
906
907    #[test]
908    fn replace_section_without_end_marker() {
909        ensure_temp_dir();
910        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
911        let path = std::env::temp_dir().join("test_replace_no_end.md");
912        std::fs::write(&path, old).unwrap();
913
914        let result = replace_markdown_section(&path, old).unwrap();
915        assert!(matches!(result, RulesResult::Updated));
916
917        let new_content = std::fs::read_to_string(&path).unwrap();
918        assert!(new_content.contains(RULES_VERSION));
919        assert!(new_content.starts_with("user stuff"));
920
921        std::fs::remove_file(&path).ok();
922    }
923
924    #[test]
925    fn append_to_shared_preserves_existing() {
926        ensure_temp_dir();
927        let path = std::env::temp_dir().join("test_append_shared.md");
928        std::fs::write(&path, "existing user rules\n").unwrap();
929
930        let result = append_to_shared(&path).unwrap();
931        assert!(matches!(result, RulesResult::Injected));
932
933        let content = std::fs::read_to_string(&path).unwrap();
934        assert!(content.starts_with("existing user rules"));
935        assert!(content.contains(MARKER));
936        assert!(content.contains(END_MARKER));
937
938        std::fs::remove_file(&path).ok();
939    }
940
941    #[test]
942    fn write_dedicated_creates_file() {
943        ensure_temp_dir();
944        let path = std::env::temp_dir().join("test_write_dedicated.md");
945        if path.exists() {
946            std::fs::remove_file(&path).ok();
947        }
948
949        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
950        assert!(matches!(result, RulesResult::Injected));
951
952        let content = std::fs::read_to_string(&path).unwrap();
953        assert!(content.contains(MARKER));
954        assert!(content.contains("ctx_read modes"));
955
956        std::fs::remove_file(&path).ok();
957    }
958
959    #[test]
960    fn write_dedicated_updates_existing() {
961        ensure_temp_dir();
962        let path = std::env::temp_dir().join("test_write_dedicated_update.md");
963        std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
964
965        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
966        assert!(matches!(result, RulesResult::Updated));
967
968        std::fs::remove_file(&path).ok();
969    }
970
971    #[test]
972    fn target_count() {
973        let home = std::path::PathBuf::from("/tmp/fake_home");
974        let targets = build_rules_targets(&home);
975        assert_eq!(targets.len(), 20);
976    }
977
978    #[test]
979    fn skill_template_not_empty() {
980        assert!(!SKILL_TEMPLATE.is_empty());
981        assert!(SKILL_TEMPLATE.contains("lean-ctx"));
982    }
983
984    #[test]
985    fn skill_targets_count() {
986        let home = std::path::PathBuf::from("/tmp/fake_home");
987        let targets = build_skill_targets(&home);
988        assert_eq!(targets.len(), 4);
989    }
990
991    #[test]
992    fn install_skill_creates_file() {
993        ensure_temp_dir();
994        let home = std::env::temp_dir().join("test_skill_install");
995        let _ = std::fs::create_dir_all(&home);
996
997        let fake_cursor = home.join(".cursor");
998        let _ = std::fs::create_dir_all(&fake_cursor);
999
1000        let result = install_skill_for_agent(&home, "cursor");
1001        assert!(result.is_ok());
1002
1003        let path = result.unwrap();
1004        assert!(path.exists());
1005        let content = std::fs::read_to_string(&path).unwrap();
1006        assert_eq!(content, SKILL_TEMPLATE);
1007
1008        let _ = std::fs::remove_dir_all(&home);
1009    }
1010
1011    #[test]
1012    fn install_skill_idempotent() {
1013        ensure_temp_dir();
1014        let home = std::env::temp_dir().join("test_skill_idempotent");
1015        let _ = std::fs::create_dir_all(&home);
1016
1017        let fake_cursor = home.join(".cursor");
1018        let _ = std::fs::create_dir_all(&fake_cursor);
1019
1020        let p1 = install_skill_for_agent(&home, "cursor").unwrap();
1021        let p2 = install_skill_for_agent(&home, "cursor").unwrap();
1022        assert_eq!(p1, p2);
1023
1024        let _ = std::fs::remove_dir_all(&home);
1025    }
1026
1027    #[test]
1028    fn install_skill_unknown_agent() {
1029        let home = std::path::PathBuf::from("/tmp/fake_home");
1030        let result = install_skill_for_agent(&home, "unknown_agent");
1031        assert!(result.is_err());
1032    }
1033}