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    ]
628}
629
630fn is_skill_agent_detected(agent_key: &str, home: &std::path::Path) -> bool {
631    match agent_key {
632        "claude" => {
633            command_exists("claude")
634                || crate::core::editor_registry::claude_mcp_json_path(home).exists()
635                || crate::core::editor_registry::claude_state_dir(home).exists()
636        }
637        "cursor" => home.join(".cursor").exists(),
638        "codex" => home.join(".codex").exists() || command_exists("codex"),
639        _ => false,
640    }
641}
642
643/// Install SKILL.md for a specific agent. Returns the installed path.
644pub fn install_skill_for_agent(home: &std::path::Path, agent_key: &str) -> Result<PathBuf, String> {
645    let targets = build_skill_targets(home);
646    let target = targets
647        .into_iter()
648        .find(|t| t.agent_key == agent_key)
649        .ok_or_else(|| format!("No skill target for agent '{agent_key}'"))?;
650
651    let skill_path = target.skill_dir.join("SKILL.md");
652    std::fs::create_dir_all(&target.skill_dir).map_err(|e| e.to_string())?;
653
654    if skill_path.exists() {
655        let existing = std::fs::read_to_string(&skill_path).unwrap_or_default();
656        if existing == SKILL_TEMPLATE {
657            return Ok(skill_path);
658        }
659    }
660
661    std::fs::write(&skill_path, SKILL_TEMPLATE).map_err(|e| e.to_string())?;
662    Ok(skill_path)
663}
664
665/// Install SKILL.md for all detected agents.
666/// Returns `Vec<(display_name, was_new_or_updated)>`.
667pub fn install_all_skills(home: &std::path::Path) -> Vec<(String, bool)> {
668    let targets = build_skill_targets(home);
669    let mut results = Vec::new();
670
671    for target in &targets {
672        if !is_skill_agent_detected(target.agent_key, home) {
673            continue;
674        }
675
676        let skill_path = target.skill_dir.join("SKILL.md");
677        let already_current = skill_path.exists()
678            && std::fs::read_to_string(&skill_path).is_ok_and(|c| c == SKILL_TEMPLATE);
679
680        if already_current {
681            results.push((target.display_name.to_string(), false));
682            continue;
683        }
684
685        if let Err(e) = std::fs::create_dir_all(&target.skill_dir) {
686            tracing::warn!(
687                "Failed to create skill dir for {}: {e}",
688                target.display_name
689            );
690            continue;
691        }
692
693        match std::fs::write(&skill_path, SKILL_TEMPLATE) {
694            Ok(()) => results.push((target.display_name.to_string(), true)),
695            Err(e) => {
696                tracing::warn!("Failed to write SKILL.md for {}: {e}", target.display_name);
697            }
698        }
699    }
700
701    results
702}
703
704// ---------------------------------------------------------------------------
705// Tests
706// ---------------------------------------------------------------------------
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711
712    #[test]
713    fn shared_rules_have_markers() {
714        assert!(RULES_SHARED.contains(MARKER));
715        assert!(RULES_SHARED.contains(END_MARKER));
716        assert!(RULES_SHARED.contains(RULES_VERSION));
717    }
718
719    #[test]
720    fn dedicated_rules_have_markers() {
721        assert!(RULES_DEDICATED.contains(MARKER));
722        assert!(RULES_DEDICATED.contains(END_MARKER));
723        assert!(RULES_DEDICATED.contains(RULES_VERSION));
724    }
725
726    #[test]
727    fn cursor_mdc_has_markers_and_frontmatter() {
728        assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
729        assert!(RULES_CURSOR_MDC.contains(END_MARKER));
730        assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
731        assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
732    }
733
734    #[test]
735    fn shared_rules_contain_tool_mapping() {
736        assert!(RULES_SHARED.contains("ctx_read"));
737        assert!(RULES_SHARED.contains("ctx_shell"));
738        assert!(RULES_SHARED.contains("ctx_search"));
739        assert!(RULES_SHARED.contains("ctx_tree"));
740        assert!(RULES_SHARED.contains("Write"));
741    }
742
743    #[test]
744    fn shared_rules_litm_optimized() {
745        let lines: Vec<&str> = RULES_SHARED.lines().collect();
746        let first_5 = lines[..5.min(lines.len())].join("\n");
747        assert!(
748            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
749            "LITM: preference instruction must be near start"
750        );
751        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
752        assert!(
753            last_5.contains("fallback") || last_5.contains("native"),
754            "LITM: fallback note must be near end"
755        );
756    }
757
758    #[test]
759    fn dedicated_rules_contain_modes() {
760        assert!(RULES_DEDICATED.contains("auto"));
761        assert!(RULES_DEDICATED.contains("full"));
762        assert!(RULES_DEDICATED.contains("map"));
763        assert!(RULES_DEDICATED.contains("signatures"));
764        assert!(RULES_DEDICATED.contains("diff"));
765        assert!(RULES_DEDICATED.contains("aggressive"));
766        assert!(RULES_DEDICATED.contains("entropy"));
767        assert!(RULES_DEDICATED.contains("task"));
768        assert!(RULES_DEDICATED.contains("reference"));
769        assert!(RULES_DEDICATED.contains("ctx_read"));
770    }
771
772    #[test]
773    fn dedicated_rules_litm_optimized() {
774        let lines: Vec<&str> = RULES_DEDICATED.lines().collect();
775        let first_5 = lines[..5.min(lines.len())].join("\n");
776        assert!(
777            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
778            "LITM: preference instruction must be near start"
779        );
780        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
781        assert!(
782            last_5.contains("fallback") || last_5.contains("ctx_compress"),
783            "LITM: practical note must be near end"
784        );
785    }
786
787    #[test]
788    fn cursor_mdc_litm_optimized() {
789        let lines: Vec<&str> = RULES_CURSOR_MDC.lines().collect();
790        let first_10 = lines[..10.min(lines.len())].join("\n");
791        assert!(
792            first_10.contains("PREFER") || first_10.contains("lean-ctx"),
793            "LITM: preference instruction must be near start of MDC"
794        );
795        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
796        assert!(
797            last_5.contains("fallback") || last_5.contains("native"),
798            "LITM: fallback note must be near end of MDC"
799        );
800    }
801
802    fn ensure_temp_dir() {
803        let tmp = std::env::temp_dir();
804        if !tmp.exists() {
805            std::fs::create_dir_all(&tmp).ok();
806        }
807    }
808
809    #[test]
810    fn replace_section_with_end_marker() {
811        ensure_temp_dir();
812        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";
813        let path = std::env::temp_dir().join("test_replace_with_end.md");
814        std::fs::write(&path, old).unwrap();
815
816        let result = replace_markdown_section(&path, old).unwrap();
817        assert!(matches!(result, RulesResult::Updated));
818
819        let new_content = std::fs::read_to_string(&path).unwrap();
820        assert!(new_content.contains(RULES_VERSION));
821        assert!(new_content.starts_with("user stuff"));
822        assert!(new_content.contains("more user stuff"));
823        assert!(!new_content.contains("lean-ctx-rules-v2"));
824
825        std::fs::remove_file(&path).ok();
826    }
827
828    #[test]
829    fn replace_section_without_end_marker() {
830        ensure_temp_dir();
831        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
832        let path = std::env::temp_dir().join("test_replace_no_end.md");
833        std::fs::write(&path, old).unwrap();
834
835        let result = replace_markdown_section(&path, old).unwrap();
836        assert!(matches!(result, RulesResult::Updated));
837
838        let new_content = std::fs::read_to_string(&path).unwrap();
839        assert!(new_content.contains(RULES_VERSION));
840        assert!(new_content.starts_with("user stuff"));
841
842        std::fs::remove_file(&path).ok();
843    }
844
845    #[test]
846    fn append_to_shared_preserves_existing() {
847        ensure_temp_dir();
848        let path = std::env::temp_dir().join("test_append_shared.md");
849        std::fs::write(&path, "existing user rules\n").unwrap();
850
851        let result = append_to_shared(&path).unwrap();
852        assert!(matches!(result, RulesResult::Injected));
853
854        let content = std::fs::read_to_string(&path).unwrap();
855        assert!(content.starts_with("existing user rules"));
856        assert!(content.contains(MARKER));
857        assert!(content.contains(END_MARKER));
858
859        std::fs::remove_file(&path).ok();
860    }
861
862    #[test]
863    fn write_dedicated_creates_file() {
864        ensure_temp_dir();
865        let path = std::env::temp_dir().join("test_write_dedicated.md");
866        if path.exists() {
867            std::fs::remove_file(&path).ok();
868        }
869
870        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
871        assert!(matches!(result, RulesResult::Injected));
872
873        let content = std::fs::read_to_string(&path).unwrap();
874        assert!(content.contains(MARKER));
875        assert!(content.contains("ctx_read modes"));
876
877        std::fs::remove_file(&path).ok();
878    }
879
880    #[test]
881    fn write_dedicated_updates_existing() {
882        ensure_temp_dir();
883        let path = std::env::temp_dir().join("test_write_dedicated_update.md");
884        std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
885
886        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
887        assert!(matches!(result, RulesResult::Updated));
888
889        std::fs::remove_file(&path).ok();
890    }
891
892    #[test]
893    fn target_count() {
894        let home = std::path::PathBuf::from("/tmp/fake_home");
895        let targets = build_rules_targets(&home);
896        assert_eq!(targets.len(), 20);
897    }
898
899    #[test]
900    fn skill_template_not_empty() {
901        assert!(!SKILL_TEMPLATE.is_empty());
902        assert!(SKILL_TEMPLATE.contains("lean-ctx"));
903    }
904
905    #[test]
906    fn skill_targets_count() {
907        let home = std::path::PathBuf::from("/tmp/fake_home");
908        let targets = build_skill_targets(&home);
909        assert_eq!(targets.len(), 3);
910    }
911
912    #[test]
913    fn install_skill_creates_file() {
914        ensure_temp_dir();
915        let home = std::env::temp_dir().join("test_skill_install");
916        let _ = std::fs::create_dir_all(&home);
917
918        let fake_cursor = home.join(".cursor");
919        let _ = std::fs::create_dir_all(&fake_cursor);
920
921        let result = install_skill_for_agent(&home, "cursor");
922        assert!(result.is_ok());
923
924        let path = result.unwrap();
925        assert!(path.exists());
926        let content = std::fs::read_to_string(&path).unwrap();
927        assert_eq!(content, SKILL_TEMPLATE);
928
929        let _ = std::fs::remove_dir_all(&home);
930    }
931
932    #[test]
933    fn install_skill_idempotent() {
934        ensure_temp_dir();
935        let home = std::env::temp_dir().join("test_skill_idempotent");
936        let _ = std::fs::create_dir_all(&home);
937
938        let fake_cursor = home.join(".cursor");
939        let _ = std::fs::create_dir_all(&fake_cursor);
940
941        let p1 = install_skill_for_agent(&home, "cursor").unwrap();
942        let p2 = install_skill_for_agent(&home, "cursor").unwrap();
943        assert_eq!(p1, p2);
944
945        let _ = std::fs::remove_dir_all(&home);
946    }
947
948    #[test]
949    fn install_skill_unknown_agent() {
950        let home = std::path::PathBuf::from("/tmp/fake_home");
951        let result = install_skill_for_agent(&home, "unknown_agent");
952        assert!(result.is_err());
953    }
954}