Skip to main content

lean_ctx/
rules_inject.rs

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