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