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