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