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