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