Skip to main content

lean_ctx/
rules_inject.rs

1use std::path::PathBuf;
2
3const MARKER: &str = "# lean-ctx — Context Engineering Layer";
4const END_MARKER: &str = "<!-- /lean-ctx -->";
5const RULES_VERSION: &str = "lean-ctx-rules-v6";
6
7// ---------------------------------------------------------------------------
8// Rules content for SHARED config files (appended to user's existing config).
9// LITM-optimized: critical instruction at START and END of block.
10// Used for: CLAUDE.md, instructions.md, GEMINI.md, copilot-instructions.md
11// ---------------------------------------------------------------------------
12const RULES_SHARED: &str = r#"# lean-ctx — Context Engineering Layer
13<!-- lean-ctx-rules-v6 -->
14
15PREFER lean-ctx MCP tools over native equivalents for token savings:
16
17| PREFER | OVER | Why |
18|--------|------|-----|
19| `ctx_read(path)` | `Read` / `cat` | Cached, 8 compression modes, re-reads ~13 tokens |
20| `ctx_shell(command)` | `Shell` / `bash` | Pattern compression for git/npm/cargo output |
21| `ctx_search(pattern, path)` | `Grep` / `rg` | Compact, token-efficient results |
22| `ctx_tree(path, depth)` | `ls` / `find` | Compact directory maps |
23
24If your Edit tool requires a prior native Read, use native Read for that file — then edit normally.
25Write, StrReplace, Delete, Glob, Edit → use normally (no replacement).
26Native tools are allowed as fallback — never get stuck.
27<!-- /lean-ctx -->"#;
28
29// ---------------------------------------------------------------------------
30// Rules content for DEDICATED lean-ctx rule files (we control entire file).
31// LITM-optimized with critical mapping at start and end.
32// Used for: Windsurf, Zed, Cline, Roo Code, OpenCode, Continue, Aider
33// ---------------------------------------------------------------------------
34const RULES_DEDICATED: &str = r#"# lean-ctx — Context Engineering Layer
35<!-- lean-ctx-rules-v6 -->
36
37PREFER lean-ctx MCP tools over native equivalents for token savings:
38
39## Tool preference:
40| PREFER | OVER | Why |
41|--------|------|-----|
42| `ctx_read(path)` | `Read` / `cat` | Cached, 8 compression modes, re-reads ~13 tokens |
43| `ctx_shell(command)` | `Shell` / `bash` | Pattern compression for git/npm/cargo output |
44| `ctx_search(pattern, path)` | `Grep` / `rg` | Compact, token-efficient results |
45| `ctx_tree(path, depth)` | `ls` / `find` | Compact directory maps |
46
47## ctx_read modes:
48- `full` — cached read (files you edit)
49- `map` — deps + exports (context-only files)
50- `signatures` — API surface only
51- `diff` — changed lines after edits
52- `lines:N-M` — specific range
53
54## Edit compatibility:
55If your Edit tool requires a prior native Read, use native Read for that file — then edit normally.
56Write, StrReplace, Delete, Glob, Edit → use normally. Native tools are allowed as fallback.
57
58## Proactive (use without being asked):
59- `ctx_overview(task)` at session start
60- `ctx_compress` when context grows large
61<!-- /lean-ctx -->"#;
62
63// ---------------------------------------------------------------------------
64// Rules for Cursor MDC format (dedicated file with frontmatter).
65// alwaysApply: true ensures this is loaded into EVERY conversation.
66// LITM-optimized: critical warning at top and bottom.
67// ---------------------------------------------------------------------------
68const RULES_CURSOR_MDC: &str = r#"---
69description: "lean-ctx: prefer ctx_read/ctx_shell/ctx_search/ctx_tree over Read/Shell/Grep/ls for token savings"
70alwaysApply: true
71---
72
73# lean-ctx — Context Engineering Layer
74<!-- lean-ctx-rules-v6 -->
75
76PREFER lean-ctx MCP tools over native equivalents for token savings:
77
78## Tool Mapping
79
80| PREFER | OVER | Why |
81|--------|------|-----|
82| `ctx_read` | `Read` | Session caching, 8 compression modes, re-reads cost ~13 tokens |
83| `ctx_shell` | `Shell` | Pattern-based compression for git, npm, cargo, docker, tsc |
84| `ctx_search` | `Grep` | Compact context, token-efficient results |
85| `ctx_tree` | `ls`, `find` | Compact directory maps with file counts |
86
87## ctx_read Modes
88
89- `full` — default, cached read (use for files you will edit)
90- `map` — dependency graph + exports + key signatures (use for context-only files)
91- `signatures` — API surface only
92- `diff` — changed lines only (use after edits)
93- `lines:N-M` — specific range
94
95## Edit compatibility
96
97- If your Edit tool requires a prior native Read, use native Read for that file — then edit normally.
98- Write, StrReplace, Delete, Glob, Edit → use normally (no lean-ctx replacement).
99- Native tools are allowed as fallback — never get stuck.
100<!-- /lean-ctx -->"#;
101
102// ---------------------------------------------------------------------------
103
104struct RulesTarget {
105    name: &'static str,
106    path: PathBuf,
107    format: RulesFormat,
108}
109
110enum RulesFormat {
111    SharedMarkdown,
112    DedicatedMarkdown,
113    CursorMdc,
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
123pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
124    let targets = build_rules_targets(home);
125
126    let mut result = InjectResult {
127        injected: Vec::new(),
128        updated: Vec::new(),
129        already: Vec::new(),
130        errors: Vec::new(),
131    };
132
133    for target in &targets {
134        if !is_tool_detected(target, home) {
135            continue;
136        }
137
138        match inject_rules(target) {
139            Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
140            Ok(RulesResult::Updated) => result.updated.push(target.name.to_string()),
141            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
142            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
143        }
144    }
145
146    result
147}
148
149// ---------------------------------------------------------------------------
150// Injection logic
151// ---------------------------------------------------------------------------
152
153enum RulesResult {
154    Injected,
155    Updated,
156    AlreadyPresent,
157}
158
159fn rules_content(format: &RulesFormat) -> &'static str {
160    match format {
161        RulesFormat::SharedMarkdown => RULES_SHARED,
162        RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
163        RulesFormat::CursorMdc => RULES_CURSOR_MDC,
164    }
165}
166
167fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
168    if target.path.exists() {
169        let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
170        if content.contains(MARKER) {
171            if content.contains(RULES_VERSION) {
172                return Ok(RulesResult::AlreadyPresent);
173            }
174            ensure_parent(&target.path)?;
175            return match target.format {
176                RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
177                RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
178                    write_dedicated(&target.path, rules_content(&target.format))
179                }
180            };
181        }
182    }
183
184    ensure_parent(&target.path)?;
185
186    match target.format {
187        RulesFormat::SharedMarkdown => append_to_shared(&target.path),
188        RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
189            write_dedicated(&target.path, rules_content(&target.format))
190        }
191    }
192}
193
194fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
195    if let Some(parent) = path.parent() {
196        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
197    }
198    Ok(())
199}
200
201fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
202    let mut content = if path.exists() {
203        std::fs::read_to_string(path).map_err(|e| e.to_string())?
204    } else {
205        String::new()
206    };
207
208    if !content.is_empty() && !content.ends_with('\n') {
209        content.push('\n');
210    }
211    if !content.is_empty() {
212        content.push('\n');
213    }
214    content.push_str(RULES_SHARED);
215    content.push('\n');
216
217    std::fs::write(path, content).map_err(|e| e.to_string())?;
218    Ok(RulesResult::Injected)
219}
220
221fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
222    let start = content.find(MARKER);
223    let end = content.find(END_MARKER);
224
225    let new_content = match (start, end) {
226        (Some(s), Some(e)) => {
227            let before = &content[..s];
228            let after_end = e + END_MARKER.len();
229            let after = content[after_end..].trim_start_matches('\n');
230            let mut result = before.to_string();
231            result.push_str(RULES_SHARED);
232            if !after.is_empty() {
233                result.push('\n');
234                result.push_str(after);
235            }
236            result
237        }
238        (Some(s), None) => {
239            let before = &content[..s];
240            let mut result = before.to_string();
241            result.push_str(RULES_SHARED);
242            result.push('\n');
243            result
244        }
245        _ => return Ok(RulesResult::AlreadyPresent),
246    };
247
248    std::fs::write(path, new_content).map_err(|e| e.to_string())?;
249    Ok(RulesResult::Updated)
250}
251
252fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
253    let is_update = path.exists() && {
254        let existing = std::fs::read_to_string(path).unwrap_or_default();
255        existing.contains(MARKER)
256    };
257
258    std::fs::write(path, content).map_err(|e| e.to_string())?;
259
260    if is_update {
261        Ok(RulesResult::Updated)
262    } else {
263        Ok(RulesResult::Injected)
264    }
265}
266
267// ---------------------------------------------------------------------------
268// Tool detection
269// ---------------------------------------------------------------------------
270
271fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
272    match target.name {
273        "Claude Code" => {
274            if command_exists("claude") {
275                return true;
276            }
277            home.join(".claude.json").exists() || home.join(".claude").exists()
278        }
279        "Codex CLI" => home.join(".codex").exists() || command_exists("codex"),
280        "Cursor" => home.join(".cursor").exists(),
281        "Windsurf" => home.join(".codeium/windsurf").exists(),
282        "Gemini CLI" => home.join(".gemini").exists(),
283        "VS Code / Copilot" => detect_vscode_installed(home),
284        "Zed" => home.join(".config/zed").exists(),
285        "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
286        "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
287        "OpenCode" => home.join(".config/opencode").exists(),
288        "Continue" => detect_extension_installed(home, "continue.continue"),
289        "Aider" => command_exists("aider") || home.join(".aider.conf.yml").exists(),
290        "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
291        "Qwen Code" => home.join(".qwen").exists(),
292        "Trae" => home.join(".trae").exists(),
293        "Amazon Q Developer" => home.join(".aws/amazonq").exists(),
294        "JetBrains IDEs" => detect_jetbrains_installed(home),
295        "Antigravity" => home.join(".gemini/antigravity").exists(),
296        "Pi Coding Agent" => home.join(".pi").exists() || command_exists("pi"),
297        "AWS Kiro" => home.join(".kiro").exists(),
298        _ => false,
299    }
300}
301
302fn command_exists(name: &str) -> bool {
303    #[cfg(target_os = "windows")]
304    let result = std::process::Command::new("where")
305        .arg(name)
306        .output()
307        .map(|o| o.status.success())
308        .unwrap_or(false);
309
310    #[cfg(not(target_os = "windows"))]
311    let result = std::process::Command::new("which")
312        .arg(name)
313        .output()
314        .map(|o| o.status.success())
315        .unwrap_or(false);
316
317    result
318}
319
320fn detect_vscode_installed(home: &std::path::Path) -> bool {
321    let check_dir = |dir: PathBuf| -> bool {
322        dir.join("settings.json").exists() || dir.join("mcp.json").exists()
323    };
324
325    #[cfg(target_os = "macos")]
326    if check_dir(home.join("Library/Application Support/Code/User")) {
327        return true;
328    }
329    #[cfg(target_os = "linux")]
330    if check_dir(home.join(".config/Code/User")) {
331        return true;
332    }
333    #[cfg(target_os = "windows")]
334    if let Ok(appdata) = std::env::var("APPDATA") {
335        if check_dir(PathBuf::from(&appdata).join("Code/User")) {
336            return true;
337        }
338    }
339    false
340}
341
342fn detect_jetbrains_installed(home: &std::path::Path) -> bool {
343    #[cfg(target_os = "macos")]
344    if home.join("Library/Application Support/JetBrains").exists() {
345        return true;
346    }
347    #[cfg(target_os = "linux")]
348    if home.join(".config/JetBrains").exists() {
349        return true;
350    }
351    home.join(".jb-mcp.json").exists()
352}
353
354fn detect_extension_installed(home: &std::path::Path, extension_id: &str) -> bool {
355    #[cfg(target_os = "macos")]
356    {
357        if home
358            .join(format!(
359                "Library/Application Support/Code/User/globalStorage/{extension_id}"
360            ))
361            .exists()
362        {
363            return true;
364        }
365    }
366    #[cfg(target_os = "linux")]
367    {
368        if home
369            .join(format!(".config/Code/User/globalStorage/{extension_id}"))
370            .exists()
371        {
372            return true;
373        }
374    }
375    #[cfg(target_os = "windows")]
376    {
377        if let Ok(appdata) = std::env::var("APPDATA") {
378            if std::path::PathBuf::from(&appdata)
379                .join(format!("Code/User/globalStorage/{extension_id}"))
380                .exists()
381            {
382                return true;
383            }
384        }
385    }
386    false
387}
388
389// ---------------------------------------------------------------------------
390// Target definitions
391// ---------------------------------------------------------------------------
392
393fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
394    vec![
395        // --- Shared config files (append-only) ---
396        RulesTarget {
397            name: "Claude Code",
398            path: home.join(".claude/CLAUDE.md"),
399            format: RulesFormat::SharedMarkdown,
400        },
401        RulesTarget {
402            name: "Codex CLI",
403            path: home.join(".codex/instructions.md"),
404            format: RulesFormat::SharedMarkdown,
405        },
406        RulesTarget {
407            name: "Gemini CLI",
408            path: home.join(".gemini/GEMINI.md"),
409            format: RulesFormat::SharedMarkdown,
410        },
411        RulesTarget {
412            name: "VS Code / Copilot",
413            path: copilot_instructions_path(home),
414            format: RulesFormat::SharedMarkdown,
415        },
416        // --- Dedicated lean-ctx rule files ---
417        RulesTarget {
418            name: "Cursor",
419            path: home.join(".cursor/rules/lean-ctx.mdc"),
420            format: RulesFormat::CursorMdc,
421        },
422        RulesTarget {
423            name: "Windsurf",
424            path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
425            format: RulesFormat::DedicatedMarkdown,
426        },
427        RulesTarget {
428            name: "Zed",
429            path: home.join(".config/zed/rules/lean-ctx.md"),
430            format: RulesFormat::DedicatedMarkdown,
431        },
432        RulesTarget {
433            name: "Cline",
434            path: home.join(".cline/rules/lean-ctx.md"),
435            format: RulesFormat::DedicatedMarkdown,
436        },
437        RulesTarget {
438            name: "Roo Code",
439            path: home.join(".roo/rules/lean-ctx.md"),
440            format: RulesFormat::DedicatedMarkdown,
441        },
442        RulesTarget {
443            name: "OpenCode",
444            path: home.join(".config/opencode/rules/lean-ctx.md"),
445            format: RulesFormat::DedicatedMarkdown,
446        },
447        RulesTarget {
448            name: "Continue",
449            path: home.join(".continue/rules/lean-ctx.md"),
450            format: RulesFormat::DedicatedMarkdown,
451        },
452        RulesTarget {
453            name: "Aider",
454            path: home.join(".aider/rules/lean-ctx.md"),
455            format: RulesFormat::DedicatedMarkdown,
456        },
457        RulesTarget {
458            name: "Amp",
459            path: home.join(".ampcoder/rules/lean-ctx.md"),
460            format: RulesFormat::DedicatedMarkdown,
461        },
462        RulesTarget {
463            name: "Qwen Code",
464            path: home.join(".qwen/rules/lean-ctx.md"),
465            format: RulesFormat::DedicatedMarkdown,
466        },
467        RulesTarget {
468            name: "Trae",
469            path: home.join(".trae/rules/lean-ctx.md"),
470            format: RulesFormat::DedicatedMarkdown,
471        },
472        RulesTarget {
473            name: "Amazon Q Developer",
474            path: home.join(".aws/amazonq/rules/lean-ctx.md"),
475            format: RulesFormat::DedicatedMarkdown,
476        },
477        RulesTarget {
478            name: "JetBrains IDEs",
479            path: home.join(".jb-rules/lean-ctx.md"),
480            format: RulesFormat::DedicatedMarkdown,
481        },
482        RulesTarget {
483            name: "Antigravity",
484            path: home.join(".gemini/antigravity/rules/lean-ctx.md"),
485            format: RulesFormat::DedicatedMarkdown,
486        },
487        RulesTarget {
488            name: "Pi Coding Agent",
489            path: home.join(".pi/rules/lean-ctx.md"),
490            format: RulesFormat::DedicatedMarkdown,
491        },
492        RulesTarget {
493            name: "AWS Kiro",
494            path: home.join(".kiro/rules/lean-ctx.md"),
495            format: RulesFormat::DedicatedMarkdown,
496        },
497        RulesTarget {
498            name: "Verdent",
499            path: home.join(".verdent/rules/lean-ctx.md"),
500            format: RulesFormat::DedicatedMarkdown,
501        },
502    ]
503}
504
505fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
506    #[cfg(target_os = "macos")]
507    {
508        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
509    }
510    #[cfg(target_os = "linux")]
511    {
512        return home.join(".config/Code/User/github-copilot-instructions.md");
513    }
514    #[cfg(target_os = "windows")]
515    {
516        if let Ok(appdata) = std::env::var("APPDATA") {
517            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
518        }
519    }
520    #[allow(unreachable_code)]
521    home.join(".config/Code/User/github-copilot-instructions.md")
522}
523
524// ---------------------------------------------------------------------------
525// Tests
526// ---------------------------------------------------------------------------
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    #[test]
533    fn shared_rules_have_markers() {
534        assert!(RULES_SHARED.contains(MARKER));
535        assert!(RULES_SHARED.contains(END_MARKER));
536        assert!(RULES_SHARED.contains(RULES_VERSION));
537    }
538
539    #[test]
540    fn dedicated_rules_have_markers() {
541        assert!(RULES_DEDICATED.contains(MARKER));
542        assert!(RULES_DEDICATED.contains(END_MARKER));
543        assert!(RULES_DEDICATED.contains(RULES_VERSION));
544    }
545
546    #[test]
547    fn cursor_mdc_has_markers_and_frontmatter() {
548        assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
549        assert!(RULES_CURSOR_MDC.contains(END_MARKER));
550        assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
551        assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
552    }
553
554    #[test]
555    fn shared_rules_contain_tool_mapping() {
556        assert!(RULES_SHARED.contains("ctx_read"));
557        assert!(RULES_SHARED.contains("ctx_shell"));
558        assert!(RULES_SHARED.contains("ctx_search"));
559        assert!(RULES_SHARED.contains("ctx_tree"));
560        assert!(RULES_SHARED.contains("Write"));
561    }
562
563    #[test]
564    fn shared_rules_litm_optimized() {
565        let lines: Vec<&str> = RULES_SHARED.lines().collect();
566        let first_5 = lines[..5.min(lines.len())].join("\n");
567        assert!(
568            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
569            "LITM: preference instruction must be near start"
570        );
571        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
572        assert!(
573            last_5.contains("fallback") || last_5.contains("native"),
574            "LITM: fallback note must be near end"
575        );
576    }
577
578    #[test]
579    fn dedicated_rules_contain_modes() {
580        assert!(RULES_DEDICATED.contains("full"));
581        assert!(RULES_DEDICATED.contains("map"));
582        assert!(RULES_DEDICATED.contains("signatures"));
583        assert!(RULES_DEDICATED.contains("diff"));
584        assert!(RULES_DEDICATED.contains("ctx_read"));
585    }
586
587    #[test]
588    fn dedicated_rules_litm_optimized() {
589        let lines: Vec<&str> = RULES_DEDICATED.lines().collect();
590        let first_5 = lines[..5.min(lines.len())].join("\n");
591        assert!(
592            first_5.contains("PREFER") || first_5.contains("lean-ctx"),
593            "LITM: preference instruction must be near start"
594        );
595        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
596        assert!(
597            last_5.contains("fallback") || last_5.contains("ctx_compress"),
598            "LITM: practical note must be near end"
599        );
600    }
601
602    #[test]
603    fn cursor_mdc_litm_optimized() {
604        let lines: Vec<&str> = RULES_CURSOR_MDC.lines().collect();
605        let first_10 = lines[..10.min(lines.len())].join("\n");
606        assert!(
607            first_10.contains("PREFER") || first_10.contains("lean-ctx"),
608            "LITM: preference instruction must be near start of MDC"
609        );
610        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
611        assert!(
612            last_5.contains("fallback") || last_5.contains("native"),
613            "LITM: fallback note must be near end of MDC"
614        );
615    }
616
617    fn ensure_temp_dir() {
618        let tmp = std::env::temp_dir();
619        if !tmp.exists() {
620            std::fs::create_dir_all(&tmp).ok();
621        }
622    }
623
624    #[test]
625    fn replace_section_with_end_marker() {
626        ensure_temp_dir();
627        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";
628        let path = std::env::temp_dir().join("test_replace_with_end.md");
629        std::fs::write(&path, old).unwrap();
630
631        let result = replace_markdown_section(&path, old).unwrap();
632        assert!(matches!(result, RulesResult::Updated));
633
634        let new_content = std::fs::read_to_string(&path).unwrap();
635        assert!(new_content.contains(RULES_VERSION));
636        assert!(new_content.starts_with("user stuff"));
637        assert!(new_content.contains("more user stuff"));
638        assert!(!new_content.contains("lean-ctx-rules-v2"));
639
640        std::fs::remove_file(&path).ok();
641    }
642
643    #[test]
644    fn replace_section_without_end_marker() {
645        ensure_temp_dir();
646        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
647        let path = std::env::temp_dir().join("test_replace_no_end.md");
648        std::fs::write(&path, old).unwrap();
649
650        let result = replace_markdown_section(&path, old).unwrap();
651        assert!(matches!(result, RulesResult::Updated));
652
653        let new_content = std::fs::read_to_string(&path).unwrap();
654        assert!(new_content.contains(RULES_VERSION));
655        assert!(new_content.starts_with("user stuff"));
656
657        std::fs::remove_file(&path).ok();
658    }
659
660    #[test]
661    fn append_to_shared_preserves_existing() {
662        ensure_temp_dir();
663        let path = std::env::temp_dir().join("test_append_shared.md");
664        std::fs::write(&path, "existing user rules\n").unwrap();
665
666        let result = append_to_shared(&path).unwrap();
667        assert!(matches!(result, RulesResult::Injected));
668
669        let content = std::fs::read_to_string(&path).unwrap();
670        assert!(content.starts_with("existing user rules"));
671        assert!(content.contains(MARKER));
672        assert!(content.contains(END_MARKER));
673
674        std::fs::remove_file(&path).ok();
675    }
676
677    #[test]
678    fn write_dedicated_creates_file() {
679        ensure_temp_dir();
680        let path = std::env::temp_dir().join("test_write_dedicated.md");
681        if path.exists() {
682            std::fs::remove_file(&path).ok();
683        }
684
685        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
686        assert!(matches!(result, RulesResult::Injected));
687
688        let content = std::fs::read_to_string(&path).unwrap();
689        assert!(content.contains(MARKER));
690        assert!(content.contains("ctx_read modes"));
691
692        std::fs::remove_file(&path).ok();
693    }
694
695    #[test]
696    fn write_dedicated_updates_existing() {
697        ensure_temp_dir();
698        let path = std::env::temp_dir().join("test_write_dedicated_update.md");
699        std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
700
701        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
702        assert!(matches!(result, RulesResult::Updated));
703
704        std::fs::remove_file(&path).ok();
705    }
706
707    #[test]
708    fn target_count() {
709        let home = std::path::PathBuf::from("/tmp/fake_home");
710        let targets = build_rules_targets(&home);
711        assert_eq!(targets.len(), 21);
712    }
713}