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