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// alwaysApply: true ensures this is loaded into EVERY conversation.
86// LITM-optimized: critical warning at top and bottom.
87// ---------------------------------------------------------------------------
88const RULES_CURSOR_MDC: &str = r#"---
89description: "lean-ctx: prefer ctx_read/ctx_shell/ctx_search/ctx_tree over Read/Shell/Grep/ls for token savings"
90alwaysApply: true
91---
92
93# lean-ctx — Context Engineering Layer
94<!-- lean-ctx-rules-v9 -->
95
96PREFER lean-ctx MCP tools over native equivalents for token savings:
97
98## Tool Mapping
99
100| PREFER | OVER | Why |
101|--------|------|-----|
102| `ctx_read` | `Read` | Session caching, 10 read modes, re-reads cost ~13 tokens |
103| `ctx_shell` | `Shell` | Pattern-based compression for git, npm, cargo, docker, tsc |
104| `ctx_search` | `Grep` | Compact context, token-efficient results |
105| `ctx_tree` | `ls`, `find` | Compact directory maps with file counts |
106| `ctx_edit` | `Edit` (when Read unavailable) | Search-and-replace without native Read dependency |
107
108## ctx_read Modes
109
110- `auto` — auto-select optimal mode (recommended default)
111- `full` — cached read (use for files you will edit)
112- `map` — dependency graph + exports + key signatures (use for context-only files)
113- `signatures` — API surface only
114- `diff` — changed lines only (use after edits)
115- `aggressive` — maximum compression (context only)
116- `entropy` — highlight high-entropy fragments
117- `task` — IB-filtered (task relevant)
118- `reference` — quote-friendly minimal excerpts
119- `lines:N-M` — specific range
120
121## File editing
122
123- Use native Edit/StrReplace when available.
124- If Edit requires native Read and Read is unavailable: use `ctx_edit(path, old_string, new_string)` instead.
125- NEVER loop trying to make Edit work. If it fails, switch to ctx_edit immediately.
126- Write, Delete, Glob → use normally.
127- Fallback only if a lean-ctx tool is unavailable: use native equivalents.
128<!-- /lean-ctx -->"#;
129
130// ---------------------------------------------------------------------------
131
132struct RulesTarget {
133    name: &'static str,
134    path: PathBuf,
135    format: RulesFormat,
136}
137
138enum RulesFormat {
139    SharedMarkdown,
140    DedicatedMarkdown,
141    CursorMdc,
142}
143
144pub struct InjectResult {
145    pub injected: Vec<String>,
146    pub updated: Vec<String>,
147    pub already: Vec<String>,
148    pub errors: Vec<String>,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct RulesTargetStatus {
153    pub name: String,
154    pub detected: bool,
155    pub path: String,
156    pub state: String,
157    pub note: Option<String>,
158}
159
160pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
161    let targets = build_rules_targets(home);
162
163    let mut result = InjectResult {
164        injected: Vec::new(),
165        updated: Vec::new(),
166        already: Vec::new(),
167        errors: Vec::new(),
168    };
169
170    for target in &targets {
171        if !is_tool_detected(target, home) {
172            continue;
173        }
174
175        match inject_rules(target) {
176            Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
177            Ok(RulesResult::Updated) => result.updated.push(target.name.to_string()),
178            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
179            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
180        }
181    }
182
183    result
184}
185
186pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
187    let targets = build_rules_targets(home);
188    let mut out = Vec::new();
189
190    for target in &targets {
191        let detected = is_tool_detected(target, home);
192        let path = target.path.to_string_lossy().to_string();
193
194        let state = if !detected {
195            "not_detected".to_string()
196        } else if !target.path.exists() {
197            "missing".to_string()
198        } else {
199            match std::fs::read_to_string(&target.path) {
200                Ok(content) => {
201                    if content.contains(MARKER) {
202                        if content.contains(RULES_VERSION) {
203                            "up_to_date".to_string()
204                        } else {
205                            "outdated".to_string()
206                        }
207                    } else {
208                        "present_without_marker".to_string()
209                    }
210                }
211                Err(_) => "read_error".to_string(),
212            }
213        };
214
215        out.push(RulesTargetStatus {
216            name: target.name.to_string(),
217            detected,
218            path,
219            state,
220            note: None,
221        });
222    }
223
224    out
225}
226
227// ---------------------------------------------------------------------------
228// Injection logic
229// ---------------------------------------------------------------------------
230
231enum RulesResult {
232    Injected,
233    Updated,
234    AlreadyPresent,
235}
236
237fn rules_content(format: &RulesFormat) -> &'static str {
238    match format {
239        RulesFormat::SharedMarkdown => RULES_SHARED,
240        RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
241        RulesFormat::CursorMdc => RULES_CURSOR_MDC,
242    }
243}
244
245fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
246    if target.path.exists() {
247        let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
248        if content.contains(MARKER) {
249            if content.contains(RULES_VERSION) {
250                return Ok(RulesResult::AlreadyPresent);
251            }
252            ensure_parent(&target.path)?;
253            return match target.format {
254                RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
255                RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
256                    write_dedicated(&target.path, rules_content(&target.format))
257                }
258            };
259        }
260    }
261
262    ensure_parent(&target.path)?;
263
264    match target.format {
265        RulesFormat::SharedMarkdown => append_to_shared(&target.path),
266        RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
267            write_dedicated(&target.path, rules_content(&target.format))
268        }
269    }
270}
271
272fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
273    if let Some(parent) = path.parent() {
274        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
275    }
276    Ok(())
277}
278
279fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
280    let mut content = if path.exists() {
281        std::fs::read_to_string(path).map_err(|e| e.to_string())?
282    } else {
283        String::new()
284    };
285
286    if !content.is_empty() && !content.ends_with('\n') {
287        content.push('\n');
288    }
289    if !content.is_empty() {
290        content.push('\n');
291    }
292    content.push_str(RULES_SHARED);
293    content.push('\n');
294
295    std::fs::write(path, content).map_err(|e| e.to_string())?;
296    Ok(RulesResult::Injected)
297}
298
299fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
300    let start = content.find(MARKER);
301    let end = content.find(END_MARKER);
302
303    let new_content = match (start, end) {
304        (Some(s), Some(e)) => {
305            let before = &content[..s];
306            let after_end = e + END_MARKER.len();
307            let after = content[after_end..].trim_start_matches('\n');
308            let mut result = before.to_string();
309            result.push_str(RULES_SHARED);
310            if !after.is_empty() {
311                result.push('\n');
312                result.push_str(after);
313            }
314            result
315        }
316        (Some(s), None) => {
317            let before = &content[..s];
318            let mut result = before.to_string();
319            result.push_str(RULES_SHARED);
320            result.push('\n');
321            result
322        }
323        _ => return Ok(RulesResult::AlreadyPresent),
324    };
325
326    std::fs::write(path, new_content).map_err(|e| e.to_string())?;
327    Ok(RulesResult::Updated)
328}
329
330fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
331    let is_update = path.exists() && {
332        let existing = std::fs::read_to_string(path).unwrap_or_default();
333        existing.contains(MARKER)
334    };
335
336    std::fs::write(path, content).map_err(|e| e.to_string())?;
337
338    if is_update {
339        Ok(RulesResult::Updated)
340    } else {
341        Ok(RulesResult::Injected)
342    }
343}
344
345// ---------------------------------------------------------------------------
346// Tool detection
347// ---------------------------------------------------------------------------
348
349fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
350    match target.name {
351        "Claude Code" => {
352            if command_exists("claude") {
353                return true;
354            }
355            let state_dir = crate::core::editor_registry::claude_state_dir(home);
356            crate::core::editor_registry::claude_mcp_json_path(home).exists() || state_dir.exists()
357        }
358        "Codex CLI" => home.join(".codex").exists() || command_exists("codex"),
359        "Cursor" => home.join(".cursor").exists(),
360        "Windsurf" => home.join(".codeium/windsurf").exists(),
361        "Gemini CLI" => home.join(".gemini").exists(),
362        "VS Code / Copilot" => detect_vscode_installed(home),
363        "Zed" => home.join(".config/zed").exists(),
364        "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
365        "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
366        "OpenCode" => home.join(".config/opencode").exists(),
367        "Continue" => detect_extension_installed(home, "continue.continue"),
368        "Aider" => command_exists("aider") || home.join(".aider.conf.yml").exists(),
369        "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
370        "Qwen Code" => home.join(".qwen").exists(),
371        "Trae" => home.join(".trae").exists(),
372        "Amazon Q Developer" => home.join(".aws/amazonq").exists(),
373        "JetBrains IDEs" => detect_jetbrains_installed(home),
374        "Antigravity" => home.join(".gemini/antigravity").exists(),
375        "Pi Coding Agent" => home.join(".pi").exists() || command_exists("pi"),
376        "AWS Kiro" => home.join(".kiro").exists(),
377        "Crush" => home.join(".config/crush").exists() || command_exists("crush"),
378        _ => false,
379    }
380}
381
382fn command_exists(name: &str) -> bool {
383    #[cfg(target_os = "windows")]
384    let result = std::process::Command::new("where")
385        .arg(name)
386        .output()
387        .map(|o| o.status.success())
388        .unwrap_or(false);
389
390    #[cfg(not(target_os = "windows"))]
391    let result = std::process::Command::new("which")
392        .arg(name)
393        .output()
394        .map(|o| o.status.success())
395        .unwrap_or(false);
396
397    result
398}
399
400fn detect_vscode_installed(_home: &std::path::Path) -> bool {
401    let check_dir = |dir: PathBuf| -> bool {
402        dir.join("settings.json").exists() || dir.join("mcp.json").exists()
403    };
404
405    #[cfg(target_os = "macos")]
406    if check_dir(_home.join("Library/Application Support/Code/User")) {
407        return true;
408    }
409    #[cfg(target_os = "linux")]
410    if check_dir(_home.join(".config/Code/User")) {
411        return true;
412    }
413    #[cfg(target_os = "windows")]
414    if let Ok(appdata) = std::env::var("APPDATA") {
415        if check_dir(PathBuf::from(&appdata).join("Code/User")) {
416            return true;
417        }
418    }
419    false
420}
421
422fn detect_jetbrains_installed(home: &std::path::Path) -> bool {
423    #[cfg(target_os = "macos")]
424    if home.join("Library/Application Support/JetBrains").exists() {
425        return true;
426    }
427    #[cfg(target_os = "linux")]
428    if home.join(".config/JetBrains").exists() {
429        return true;
430    }
431    home.join(".jb-mcp.json").exists()
432}
433
434fn detect_extension_installed(_home: &std::path::Path, extension_id: &str) -> bool {
435    #[cfg(target_os = "macos")]
436    {
437        if _home
438            .join(format!(
439                "Library/Application Support/Code/User/globalStorage/{extension_id}"
440            ))
441            .exists()
442        {
443            return true;
444        }
445    }
446    #[cfg(target_os = "linux")]
447    {
448        if _home
449            .join(format!(".config/Code/User/globalStorage/{extension_id}"))
450            .exists()
451        {
452            return true;
453        }
454    }
455    #[cfg(target_os = "windows")]
456    {
457        if let Ok(appdata) = std::env::var("APPDATA") {
458            if std::path::PathBuf::from(&appdata)
459                .join(format!("Code/User/globalStorage/{extension_id}"))
460                .exists()
461            {
462                return true;
463            }
464        }
465    }
466    false
467}
468
469// ---------------------------------------------------------------------------
470// Target definitions
471// ---------------------------------------------------------------------------
472
473fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
474    vec![
475        // --- Shared config files (append-only) ---
476        RulesTarget {
477            name: "Claude Code",
478            path: crate::core::editor_registry::claude_rules_dir(home).join("lean-ctx.md"),
479            format: RulesFormat::DedicatedMarkdown,
480        },
481        RulesTarget {
482            name: "Codex CLI",
483            path: home.join(".codex/instructions.md"),
484            format: RulesFormat::SharedMarkdown,
485        },
486        RulesTarget {
487            name: "Gemini CLI",
488            path: home.join(".gemini/GEMINI.md"),
489            format: RulesFormat::SharedMarkdown,
490        },
491        RulesTarget {
492            name: "VS Code / Copilot",
493            path: copilot_instructions_path(home),
494            format: RulesFormat::SharedMarkdown,
495        },
496        // --- Dedicated lean-ctx rule files ---
497        RulesTarget {
498            name: "Cursor",
499            path: home.join(".cursor/rules/lean-ctx.mdc"),
500            format: RulesFormat::CursorMdc,
501        },
502        RulesTarget {
503            name: "Windsurf",
504            path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
505            format: RulesFormat::DedicatedMarkdown,
506        },
507        RulesTarget {
508            name: "Zed",
509            path: home.join(".config/zed/rules/lean-ctx.md"),
510            format: RulesFormat::DedicatedMarkdown,
511        },
512        RulesTarget {
513            name: "Cline",
514            path: home.join(".cline/rules/lean-ctx.md"),
515            format: RulesFormat::DedicatedMarkdown,
516        },
517        RulesTarget {
518            name: "Roo Code",
519            path: home.join(".roo/rules/lean-ctx.md"),
520            format: RulesFormat::DedicatedMarkdown,
521        },
522        RulesTarget {
523            name: "OpenCode",
524            path: home.join(".config/opencode/rules/lean-ctx.md"),
525            format: RulesFormat::DedicatedMarkdown,
526        },
527        RulesTarget {
528            name: "Continue",
529            path: home.join(".continue/rules/lean-ctx.md"),
530            format: RulesFormat::DedicatedMarkdown,
531        },
532        RulesTarget {
533            name: "Aider",
534            path: home.join(".aider/rules/lean-ctx.md"),
535            format: RulesFormat::DedicatedMarkdown,
536        },
537        RulesTarget {
538            name: "Amp",
539            path: home.join(".ampcoder/rules/lean-ctx.md"),
540            format: RulesFormat::DedicatedMarkdown,
541        },
542        RulesTarget {
543            name: "Qwen Code",
544            path: home.join(".qwen/rules/lean-ctx.md"),
545            format: RulesFormat::DedicatedMarkdown,
546        },
547        RulesTarget {
548            name: "Trae",
549            path: home.join(".trae/rules/lean-ctx.md"),
550            format: RulesFormat::DedicatedMarkdown,
551        },
552        RulesTarget {
553            name: "Amazon Q Developer",
554            path: home.join(".aws/amazonq/rules/lean-ctx.md"),
555            format: RulesFormat::DedicatedMarkdown,
556        },
557        RulesTarget {
558            name: "JetBrains IDEs",
559            path: home.join(".jb-rules/lean-ctx.md"),
560            format: RulesFormat::DedicatedMarkdown,
561        },
562        RulesTarget {
563            name: "Antigravity",
564            path: home.join(".gemini/antigravity/rules/lean-ctx.md"),
565            format: RulesFormat::DedicatedMarkdown,
566        },
567        RulesTarget {
568            name: "Pi Coding Agent",
569            path: home.join(".pi/rules/lean-ctx.md"),
570            format: RulesFormat::DedicatedMarkdown,
571        },
572        RulesTarget {
573            name: "AWS Kiro",
574            path: home.join(".kiro/rules/lean-ctx.md"),
575            format: RulesFormat::DedicatedMarkdown,
576        },
577        RulesTarget {
578            name: "Verdent",
579            path: home.join(".verdent/rules/lean-ctx.md"),
580            format: RulesFormat::DedicatedMarkdown,
581        },
582        RulesTarget {
583            name: "Crush",
584            path: home.join(".config/crush/rules/lean-ctx.md"),
585            format: RulesFormat::DedicatedMarkdown,
586        },
587    ]
588}
589
590fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
591    #[cfg(target_os = "macos")]
592    {
593        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
594    }
595    #[cfg(target_os = "linux")]
596    {
597        return home.join(".config/Code/User/github-copilot-instructions.md");
598    }
599    #[cfg(target_os = "windows")]
600    {
601        if let Ok(appdata) = std::env::var("APPDATA") {
602            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
603        }
604    }
605    #[allow(unreachable_code)]
606    home.join(".config/Code/User/github-copilot-instructions.md")
607}
608
609// ---------------------------------------------------------------------------
610// Tests
611// ---------------------------------------------------------------------------
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn shared_rules_have_markers() {
619        assert!(RULES_SHARED.contains(MARKER));
620        assert!(RULES_SHARED.contains(END_MARKER));
621        assert!(RULES_SHARED.contains(RULES_VERSION));
622    }
623
624    #[test]
625    fn dedicated_rules_have_markers() {
626        assert!(RULES_DEDICATED.contains(MARKER));
627        assert!(RULES_DEDICATED.contains(END_MARKER));
628        assert!(RULES_DEDICATED.contains(RULES_VERSION));
629    }
630
631    #[test]
632    fn cursor_mdc_has_markers_and_frontmatter() {
633        assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
634        assert!(RULES_CURSOR_MDC.contains(END_MARKER));
635        assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
636        assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
637    }
638
639    #[test]
640    fn shared_rules_contain_tool_mapping() {
641        assert!(RULES_SHARED.contains("ctx_read"));
642        assert!(RULES_SHARED.contains("ctx_shell"));
643        assert!(RULES_SHARED.contains("ctx_search"));
644        assert!(RULES_SHARED.contains("ctx_tree"));
645        assert!(RULES_SHARED.contains("Write"));
646    }
647
648    #[test]
649    fn shared_rules_litm_optimized() {
650        let lines: Vec<&str> = RULES_SHARED.lines().collect();
651        let first_5 = lines[..5.min(lines.len())].join("\n");
652        assert!(
653            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
654            "LITM: preference instruction must be near start"
655        );
656        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
657        assert!(
658            last_5.contains("fallback") || last_5.contains("native"),
659            "LITM: fallback note must be near end"
660        );
661    }
662
663    #[test]
664    fn dedicated_rules_contain_modes() {
665        assert!(RULES_DEDICATED.contains("auto"));
666        assert!(RULES_DEDICATED.contains("full"));
667        assert!(RULES_DEDICATED.contains("map"));
668        assert!(RULES_DEDICATED.contains("signatures"));
669        assert!(RULES_DEDICATED.contains("diff"));
670        assert!(RULES_DEDICATED.contains("aggressive"));
671        assert!(RULES_DEDICATED.contains("entropy"));
672        assert!(RULES_DEDICATED.contains("task"));
673        assert!(RULES_DEDICATED.contains("reference"));
674        assert!(RULES_DEDICATED.contains("ctx_read"));
675    }
676
677    #[test]
678    fn dedicated_rules_litm_optimized() {
679        let lines: Vec<&str> = RULES_DEDICATED.lines().collect();
680        let first_5 = lines[..5.min(lines.len())].join("\n");
681        assert!(
682            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
683            "LITM: preference instruction must be near start"
684        );
685        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
686        assert!(
687            last_5.contains("fallback") || last_5.contains("ctx_compress"),
688            "LITM: practical note must be near end"
689        );
690    }
691
692    #[test]
693    fn cursor_mdc_litm_optimized() {
694        let lines: Vec<&str> = RULES_CURSOR_MDC.lines().collect();
695        let first_10 = lines[..10.min(lines.len())].join("\n");
696        assert!(
697            first_10.contains("PREFER") || first_10.contains("lean-ctx"),
698            "LITM: preference instruction must be near start of MDC"
699        );
700        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
701        assert!(
702            last_5.contains("fallback") || last_5.contains("native"),
703            "LITM: fallback note must be near end of MDC"
704        );
705    }
706
707    fn ensure_temp_dir() {
708        let tmp = std::env::temp_dir();
709        if !tmp.exists() {
710            std::fs::create_dir_all(&tmp).ok();
711        }
712    }
713
714    #[test]
715    fn replace_section_with_end_marker() {
716        ensure_temp_dir();
717        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";
718        let path = std::env::temp_dir().join("test_replace_with_end.md");
719        std::fs::write(&path, old).unwrap();
720
721        let result = replace_markdown_section(&path, old).unwrap();
722        assert!(matches!(result, RulesResult::Updated));
723
724        let new_content = std::fs::read_to_string(&path).unwrap();
725        assert!(new_content.contains(RULES_VERSION));
726        assert!(new_content.starts_with("user stuff"));
727        assert!(new_content.contains("more user stuff"));
728        assert!(!new_content.contains("lean-ctx-rules-v2"));
729
730        std::fs::remove_file(&path).ok();
731    }
732
733    #[test]
734    fn replace_section_without_end_marker() {
735        ensure_temp_dir();
736        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
737        let path = std::env::temp_dir().join("test_replace_no_end.md");
738        std::fs::write(&path, old).unwrap();
739
740        let result = replace_markdown_section(&path, old).unwrap();
741        assert!(matches!(result, RulesResult::Updated));
742
743        let new_content = std::fs::read_to_string(&path).unwrap();
744        assert!(new_content.contains(RULES_VERSION));
745        assert!(new_content.starts_with("user stuff"));
746
747        std::fs::remove_file(&path).ok();
748    }
749
750    #[test]
751    fn append_to_shared_preserves_existing() {
752        ensure_temp_dir();
753        let path = std::env::temp_dir().join("test_append_shared.md");
754        std::fs::write(&path, "existing user rules\n").unwrap();
755
756        let result = append_to_shared(&path).unwrap();
757        assert!(matches!(result, RulesResult::Injected));
758
759        let content = std::fs::read_to_string(&path).unwrap();
760        assert!(content.starts_with("existing user rules"));
761        assert!(content.contains(MARKER));
762        assert!(content.contains(END_MARKER));
763
764        std::fs::remove_file(&path).ok();
765    }
766
767    #[test]
768    fn write_dedicated_creates_file() {
769        ensure_temp_dir();
770        let path = std::env::temp_dir().join("test_write_dedicated.md");
771        if path.exists() {
772            std::fs::remove_file(&path).ok();
773        }
774
775        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
776        assert!(matches!(result, RulesResult::Injected));
777
778        let content = std::fs::read_to_string(&path).unwrap();
779        assert!(content.contains(MARKER));
780        assert!(content.contains("ctx_read modes"));
781
782        std::fs::remove_file(&path).ok();
783    }
784
785    #[test]
786    fn write_dedicated_updates_existing() {
787        ensure_temp_dir();
788        let path = std::env::temp_dir().join("test_write_dedicated_update.md");
789        std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
790
791        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
792        assert!(matches!(result, RulesResult::Updated));
793
794        std::fs::remove_file(&path).ok();
795    }
796
797    #[test]
798    fn target_count() {
799        let home = std::path::PathBuf::from("/tmp/fake_home");
800        let targets = build_rules_targets(&home);
801        assert_eq!(targets.len(), 22);
802    }
803}