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