Skip to main content

lean_ctx/
rules_inject.rs

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