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        RulesTarget {
504            name: "Verdent",
505            path: home.join(".verdent/rules/lean-ctx.md"),
506            format: RulesFormat::DedicatedMarkdown,
507        },
508    ]
509}
510
511fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
512    #[cfg(target_os = "macos")]
513    {
514        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
515    }
516    #[cfg(target_os = "linux")]
517    {
518        return home.join(".config/Code/User/github-copilot-instructions.md");
519    }
520    #[cfg(target_os = "windows")]
521    {
522        if let Ok(appdata) = std::env::var("APPDATA") {
523            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
524        }
525    }
526    #[allow(unreachable_code)]
527    home.join(".config/Code/User/github-copilot-instructions.md")
528}
529
530// ---------------------------------------------------------------------------
531// Tests
532// ---------------------------------------------------------------------------
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    #[test]
539    fn shared_rules_have_markers() {
540        assert!(RULES_SHARED.contains(MARKER));
541        assert!(RULES_SHARED.contains(END_MARKER));
542        assert!(RULES_SHARED.contains(RULES_VERSION));
543    }
544
545    #[test]
546    fn dedicated_rules_have_markers() {
547        assert!(RULES_DEDICATED.contains(MARKER));
548        assert!(RULES_DEDICATED.contains(END_MARKER));
549        assert!(RULES_DEDICATED.contains(RULES_VERSION));
550    }
551
552    #[test]
553    fn cursor_mdc_has_markers_and_frontmatter() {
554        assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
555        assert!(RULES_CURSOR_MDC.contains(END_MARKER));
556        assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
557        assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
558    }
559
560    #[test]
561    fn shared_rules_contain_tool_mapping() {
562        assert!(RULES_SHARED.contains("ctx_read"));
563        assert!(RULES_SHARED.contains("ctx_shell"));
564        assert!(RULES_SHARED.contains("ctx_search"));
565        assert!(RULES_SHARED.contains("ctx_tree"));
566        assert!(RULES_SHARED.contains("Write"));
567    }
568
569    #[test]
570    fn shared_rules_litm_optimized() {
571        let lines: Vec<&str> = RULES_SHARED.lines().collect();
572        let first_5 = lines[..5.min(lines.len())].join("\n");
573        assert!(
574            first_5.contains("MANDATORY") || first_5.contains("FORBIDDEN"),
575            "LITM: critical instruction must be near start"
576        );
577        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
578        assert!(
579            last_5.contains("REMINDER") || last_5.contains("NEVER"),
580            "LITM: reminder must be near end"
581        );
582    }
583
584    #[test]
585    fn dedicated_rules_contain_modes() {
586        assert!(RULES_DEDICATED.contains("full"));
587        assert!(RULES_DEDICATED.contains("map"));
588        assert!(RULES_DEDICATED.contains("signatures"));
589        assert!(RULES_DEDICATED.contains("diff"));
590        assert!(RULES_DEDICATED.contains("ctx_read"));
591    }
592
593    #[test]
594    fn dedicated_rules_litm_optimized() {
595        let lines: Vec<&str> = RULES_DEDICATED.lines().collect();
596        let first_5 = lines[..5.min(lines.len())].join("\n");
597        assert!(
598            first_5.contains("MANDATORY") || first_5.contains("FORBIDDEN"),
599            "LITM: critical instruction must be near start"
600        );
601        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
602        assert!(
603            last_5.contains("REMINDER") || last_5.contains("NEVER"),
604            "LITM: reminder must be near end"
605        );
606    }
607
608    #[test]
609    fn cursor_mdc_litm_optimized() {
610        let lines: Vec<&str> = RULES_CURSOR_MDC.lines().collect();
611        let first_10 = lines[..10.min(lines.len())].join("\n");
612        assert!(
613            first_10.contains("CRITICAL") || first_10.contains("NEVER"),
614            "LITM: critical instruction must be near start of MDC"
615        );
616        let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
617        assert!(
618            last_5.contains("REMINDER") || last_5.contains("NEVER"),
619            "LITM: reminder must be near end of MDC"
620        );
621    }
622
623    fn ensure_temp_dir() {
624        let tmp = std::env::temp_dir();
625        if !tmp.exists() {
626            std::fs::create_dir_all(&tmp).ok();
627        }
628    }
629
630    #[test]
631    fn replace_section_with_end_marker() {
632        ensure_temp_dir();
633        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";
634        let path = std::env::temp_dir().join("test_replace_with_end.md");
635        std::fs::write(&path, old).unwrap();
636
637        let result = replace_markdown_section(&path, old).unwrap();
638        assert!(matches!(result, RulesResult::Updated));
639
640        let new_content = std::fs::read_to_string(&path).unwrap();
641        assert!(new_content.contains(RULES_VERSION));
642        assert!(new_content.starts_with("user stuff"));
643        assert!(new_content.contains("more user stuff"));
644        assert!(!new_content.contains("lean-ctx-rules-v2"));
645
646        std::fs::remove_file(&path).ok();
647    }
648
649    #[test]
650    fn replace_section_without_end_marker() {
651        ensure_temp_dir();
652        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
653        let path = std::env::temp_dir().join("test_replace_no_end.md");
654        std::fs::write(&path, old).unwrap();
655
656        let result = replace_markdown_section(&path, old).unwrap();
657        assert!(matches!(result, RulesResult::Updated));
658
659        let new_content = std::fs::read_to_string(&path).unwrap();
660        assert!(new_content.contains(RULES_VERSION));
661        assert!(new_content.starts_with("user stuff"));
662
663        std::fs::remove_file(&path).ok();
664    }
665
666    #[test]
667    fn append_to_shared_preserves_existing() {
668        ensure_temp_dir();
669        let path = std::env::temp_dir().join("test_append_shared.md");
670        std::fs::write(&path, "existing user rules\n").unwrap();
671
672        let result = append_to_shared(&path).unwrap();
673        assert!(matches!(result, RulesResult::Injected));
674
675        let content = std::fs::read_to_string(&path).unwrap();
676        assert!(content.starts_with("existing user rules"));
677        assert!(content.contains(MARKER));
678        assert!(content.contains(END_MARKER));
679
680        std::fs::remove_file(&path).ok();
681    }
682
683    #[test]
684    fn write_dedicated_creates_file() {
685        ensure_temp_dir();
686        let path = std::env::temp_dir().join("test_write_dedicated.md");
687        if path.exists() {
688            std::fs::remove_file(&path).ok();
689        }
690
691        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
692        assert!(matches!(result, RulesResult::Injected));
693
694        let content = std::fs::read_to_string(&path).unwrap();
695        assert!(content.contains(MARKER));
696        assert!(content.contains("ctx_read modes"));
697
698        std::fs::remove_file(&path).ok();
699    }
700
701    #[test]
702    fn write_dedicated_updates_existing() {
703        ensure_temp_dir();
704        let path = std::env::temp_dir().join("test_write_dedicated_update.md");
705        std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
706
707        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
708        assert!(matches!(result, RulesResult::Updated));
709
710        std::fs::remove_file(&path).ok();
711    }
712
713    #[test]
714    fn target_count() {
715        let home = std::path::PathBuf::from("/tmp/fake_home");
716        let targets = build_rules_targets(&home);
717        assert_eq!(targets.len(), 21);
718    }
719}