Skip to main content

lean_ctx/
rules_inject.rs

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