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-v4";
6
7// ---------------------------------------------------------------------------
8// Rules content for SHARED config files (appended to user's existing config).
9// Concise but forceful — these live alongside user's own rules.
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-v4 -->
14
15lean-ctx MCP tools are connected. Use them instead of native tools:
16- `ctx_read` replaces Read/cat/head/tail (cached, 8 compression modes)
17- `ctx_shell` replaces Shell/bash (pattern compression)
18- `ctx_search` replaces Grep/rg (compact results)
19- `ctx_tree` replaces ls/find (directory maps)
20
21Keep using Write, StrReplace, Delete, Glob normally.
22<!-- /lean-ctx -->"#;
23
24// ---------------------------------------------------------------------------
25// Rules content for DEDICATED lean-ctx rule files (we control entire file).
26// Detailed with examples — these are standalone lean-ctx instruction files.
27// Used for: Windsurf, Zed, Cline, Roo Code, OpenCode, Continue, Aider
28// ---------------------------------------------------------------------------
29const RULES_DEDICATED: &str = r#"# lean-ctx — Context Engineering Layer
30<!-- lean-ctx-rules-v4 -->
31
32lean-ctx MCP tools are connected. Use them instead of native tools:
33
34## Tool replacements:
35| Instead of | Use | Why |
36|------------|-----|-----|
37| `Read` / `cat` / `head` | `ctx_read(path)` | Cached, 8 compression modes, re-reads ~13 tokens |
38| `Shell` / `bash` | `ctx_shell(command)` | Pattern compression for git/npm/cargo output |
39| `Grep` / `rg` | `ctx_search(pattern, path)` | Compact, token-efficient results |
40| `ls` / `find` | `ctx_tree(path, depth)` | Compact directory maps |
41
42## ctx_read modes:
43- `full` — cached read (files you edit)
44- `map` — deps + exports (context-only files)
45- `signatures` — API surface only
46- `diff` — changed lines after edits
47- `lines:N-M` — specific range
48
49## Keep using (no lean-ctx replacement):
50Write, StrReplace, Delete, Glob — use normally.
51
52## Proactive (use without being asked):
53- `ctx_overview(task)` at session start
54- `ctx_compress` when context grows large
55<!-- /lean-ctx -->"#;
56
57// ---------------------------------------------------------------------------
58// Rules for Cursor MDC format (dedicated file with frontmatter).
59// alwaysApply: true ensures this is loaded into EVERY conversation.
60// ---------------------------------------------------------------------------
61const RULES_CURSOR_MDC: &str = r#"---
62description: "lean-ctx: ALWAYS use ctx_read/ctx_shell/ctx_search/ctx_tree instead of Read/Shell/Grep/ls"
63alwaysApply: true
64---
65
66# lean-ctx MCP Tools
67<!-- lean-ctx-rules-v4 -->
68
69Always use lean-ctx MCP tools. Never use the standard equivalents.
70
71## Tool Mapping
72
73| Instead of | Use | Why |
74|---|-----|-----|
75| `Read` | `ctx_read` | Session caching, 8 compression modes, re-reads cost ~13 tokens |
76| `Shell` | `ctx_shell` | Pattern-based compression for git, npm, cargo, docker, tsc |
77| `Grep` | `ctx_search` | Compact context, token-efficient results |
78| `ls`, `find` | `ctx_tree` | Compact directory maps with file counts |
79
80## ctx_read Modes
81
82- `full` — default, cached read (use for files you will edit)
83- `map` — dependency graph + exports + key signatures (use for context-only files)
84- `signatures` — API surface only
85- `diff` — changed lines only (use after edits)
86- `lines:N-M` — specific range
87
88## Rules
89
90- Use `ctx_read(path, mode="full")` for every file read before editing
91- Use `ctx_read(path, mode="map")` for files you only need as context
92- Use `ctx_shell(cmd)` for every shell command
93- Use `ctx_search(pattern, path)` instead of Grep
94- Use `ctx_tree` instead of `ls` or `find` for directory exploration
95- The `Write`, `StrReplace`, `Delete`, `Glob` tools have no lean-ctx equivalent — use them normally
96<!-- /lean-ctx -->"#;
97
98// ---------------------------------------------------------------------------
99
100struct RulesTarget {
101    name: &'static str,
102    path: PathBuf,
103    format: RulesFormat,
104}
105
106enum RulesFormat {
107    SharedMarkdown,
108    DedicatedMarkdown,
109    CursorMdc,
110}
111
112pub struct InjectResult {
113    pub injected: Vec<String>,
114    pub updated: Vec<String>,
115    pub already: Vec<String>,
116    pub errors: Vec<String>,
117}
118
119pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
120    let targets = build_rules_targets(home);
121
122    let mut result = InjectResult {
123        injected: Vec::new(),
124        updated: Vec::new(),
125        already: Vec::new(),
126        errors: Vec::new(),
127    };
128
129    for target in &targets {
130        if !is_tool_detected(target, home) {
131            continue;
132        }
133
134        match inject_rules(target) {
135            Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
136            Ok(RulesResult::Updated) => result.updated.push(target.name.to_string()),
137            Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
138            Err(e) => result.errors.push(format!("{}: {e}", target.name)),
139        }
140    }
141
142    result
143}
144
145// ---------------------------------------------------------------------------
146// Injection logic
147// ---------------------------------------------------------------------------
148
149enum RulesResult {
150    Injected,
151    Updated,
152    AlreadyPresent,
153}
154
155fn rules_content(format: &RulesFormat) -> &'static str {
156    match format {
157        RulesFormat::SharedMarkdown => RULES_SHARED,
158        RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
159        RulesFormat::CursorMdc => RULES_CURSOR_MDC,
160    }
161}
162
163fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
164    if target.path.exists() {
165        let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
166        if content.contains(MARKER) {
167            if content.contains(RULES_VERSION) {
168                return Ok(RulesResult::AlreadyPresent);
169            }
170            ensure_parent(&target.path)?;
171            return match target.format {
172                RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
173                RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
174                    write_dedicated(&target.path, rules_content(&target.format))
175                }
176            };
177        }
178    }
179
180    ensure_parent(&target.path)?;
181
182    match target.format {
183        RulesFormat::SharedMarkdown => append_to_shared(&target.path),
184        RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
185            write_dedicated(&target.path, rules_content(&target.format))
186        }
187    }
188}
189
190fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
191    if let Some(parent) = path.parent() {
192        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
193    }
194    Ok(())
195}
196
197fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
198    let mut content = if path.exists() {
199        std::fs::read_to_string(path).map_err(|e| e.to_string())?
200    } else {
201        String::new()
202    };
203
204    if !content.is_empty() && !content.ends_with('\n') {
205        content.push('\n');
206    }
207    if !content.is_empty() {
208        content.push('\n');
209    }
210    content.push_str(RULES_SHARED);
211    content.push('\n');
212
213    std::fs::write(path, content).map_err(|e| e.to_string())?;
214    Ok(RulesResult::Injected)
215}
216
217fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
218    let start = content.find(MARKER);
219    let end = content.find(END_MARKER);
220
221    let new_content = match (start, end) {
222        (Some(s), Some(e)) => {
223            let before = &content[..s];
224            let after_end = e + END_MARKER.len();
225            let after = content[after_end..].trim_start_matches('\n');
226            let mut result = before.to_string();
227            result.push_str(RULES_SHARED);
228            if !after.is_empty() {
229                result.push('\n');
230                result.push_str(after);
231            }
232            result
233        }
234        (Some(s), None) => {
235            let before = &content[..s];
236            let mut result = before.to_string();
237            result.push_str(RULES_SHARED);
238            result.push('\n');
239            result
240        }
241        _ => return Ok(RulesResult::AlreadyPresent),
242    };
243
244    std::fs::write(path, new_content).map_err(|e| e.to_string())?;
245    Ok(RulesResult::Updated)
246}
247
248fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
249    let is_update = path.exists() && {
250        let existing = std::fs::read_to_string(path).unwrap_or_default();
251        existing.contains(MARKER)
252    };
253
254    std::fs::write(path, content).map_err(|e| e.to_string())?;
255
256    if is_update {
257        Ok(RulesResult::Updated)
258    } else {
259        Ok(RulesResult::Injected)
260    }
261}
262
263// ---------------------------------------------------------------------------
264// Tool detection
265// ---------------------------------------------------------------------------
266
267fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
268    match target.name {
269        "Claude Code" => {
270            if command_exists("claude") {
271                return true;
272            }
273            home.join(".claude.json").exists() || home.join(".claude").exists()
274        }
275        "Codex CLI" => home.join(".codex").exists() || command_exists("codex"),
276        "Cursor" => home.join(".cursor").exists(),
277        "Windsurf" => home.join(".codeium/windsurf").exists(),
278        "Gemini CLI" => home.join(".gemini").exists(),
279        "VS Code / Copilot" => detect_vscode_installed(home),
280        "Zed" => home.join(".config/zed").exists(),
281        "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
282        "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
283        "OpenCode" => home.join(".config/opencode").exists(),
284        "Continue" => detect_extension_installed(home, "continue.continue"),
285        "Aider" => command_exists("aider") || home.join(".aider.conf.yml").exists(),
286        "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
287        _ => false,
288    }
289}
290
291fn command_exists(name: &str) -> bool {
292    #[cfg(target_os = "windows")]
293    let result = std::process::Command::new("where")
294        .arg(name)
295        .output()
296        .map(|o| o.status.success())
297        .unwrap_or(false);
298
299    #[cfg(not(target_os = "windows"))]
300    let result = std::process::Command::new("which")
301        .arg(name)
302        .output()
303        .map(|o| o.status.success())
304        .unwrap_or(false);
305
306    result
307}
308
309fn detect_vscode_installed(home: &std::path::Path) -> bool {
310    let check_dir = |dir: PathBuf| -> bool {
311        dir.join("settings.json").exists() || dir.join("mcp.json").exists()
312    };
313
314    #[cfg(target_os = "macos")]
315    if check_dir(home.join("Library/Application Support/Code/User")) {
316        return true;
317    }
318    #[cfg(target_os = "linux")]
319    if check_dir(home.join(".config/Code/User")) {
320        return true;
321    }
322    #[cfg(target_os = "windows")]
323    if let Ok(appdata) = std::env::var("APPDATA") {
324        if check_dir(PathBuf::from(&appdata).join("Code/User")) {
325            return true;
326        }
327    }
328    false
329}
330
331fn detect_extension_installed(home: &std::path::Path, extension_id: &str) -> bool {
332    #[cfg(target_os = "macos")]
333    {
334        if home
335            .join(format!(
336                "Library/Application Support/Code/User/globalStorage/{extension_id}"
337            ))
338            .exists()
339        {
340            return true;
341        }
342    }
343    #[cfg(target_os = "linux")]
344    {
345        if home
346            .join(format!(".config/Code/User/globalStorage/{extension_id}"))
347            .exists()
348        {
349            return true;
350        }
351    }
352    #[cfg(target_os = "windows")]
353    {
354        if let Ok(appdata) = std::env::var("APPDATA") {
355            if std::path::PathBuf::from(&appdata)
356                .join(format!("Code/User/globalStorage/{extension_id}"))
357                .exists()
358            {
359                return true;
360            }
361        }
362    }
363    false
364}
365
366// ---------------------------------------------------------------------------
367// Target definitions
368// ---------------------------------------------------------------------------
369
370fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
371    vec![
372        // --- Shared config files (append-only) ---
373        RulesTarget {
374            name: "Claude Code",
375            path: home.join(".claude/CLAUDE.md"),
376            format: RulesFormat::SharedMarkdown,
377        },
378        RulesTarget {
379            name: "Codex CLI",
380            path: home.join(".codex/instructions.md"),
381            format: RulesFormat::SharedMarkdown,
382        },
383        RulesTarget {
384            name: "Gemini CLI",
385            path: home.join(".gemini/GEMINI.md"),
386            format: RulesFormat::SharedMarkdown,
387        },
388        RulesTarget {
389            name: "VS Code / Copilot",
390            path: copilot_instructions_path(home),
391            format: RulesFormat::SharedMarkdown,
392        },
393        // --- Dedicated lean-ctx rule files ---
394        RulesTarget {
395            name: "Cursor",
396            path: home.join(".cursor/rules/lean-ctx.mdc"),
397            format: RulesFormat::CursorMdc,
398        },
399        RulesTarget {
400            name: "Windsurf",
401            path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
402            format: RulesFormat::DedicatedMarkdown,
403        },
404        RulesTarget {
405            name: "Zed",
406            path: home.join(".config/zed/rules/lean-ctx.md"),
407            format: RulesFormat::DedicatedMarkdown,
408        },
409        RulesTarget {
410            name: "Cline",
411            path: home.join(".cline/rules/lean-ctx.md"),
412            format: RulesFormat::DedicatedMarkdown,
413        },
414        RulesTarget {
415            name: "Roo Code",
416            path: home.join(".roo/rules/lean-ctx.md"),
417            format: RulesFormat::DedicatedMarkdown,
418        },
419        RulesTarget {
420            name: "OpenCode",
421            path: home.join(".config/opencode/rules/lean-ctx.md"),
422            format: RulesFormat::DedicatedMarkdown,
423        },
424        RulesTarget {
425            name: "Continue",
426            path: home.join(".continue/rules/lean-ctx.md"),
427            format: RulesFormat::DedicatedMarkdown,
428        },
429        RulesTarget {
430            name: "Aider",
431            path: home.join(".aider/rules/lean-ctx.md"),
432            format: RulesFormat::DedicatedMarkdown,
433        },
434        RulesTarget {
435            name: "Amp",
436            path: home.join(".ampcoder/rules/lean-ctx.md"),
437            format: RulesFormat::DedicatedMarkdown,
438        },
439    ]
440}
441
442fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
443    #[cfg(target_os = "macos")]
444    {
445        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
446    }
447    #[cfg(target_os = "linux")]
448    {
449        return home.join(".config/Code/User/github-copilot-instructions.md");
450    }
451    #[cfg(target_os = "windows")]
452    {
453        if let Ok(appdata) = std::env::var("APPDATA") {
454            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
455        }
456    }
457    #[allow(unreachable_code)]
458    home.join(".config/Code/User/github-copilot-instructions.md")
459}
460
461// ---------------------------------------------------------------------------
462// Tests
463// ---------------------------------------------------------------------------
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn shared_rules_have_markers() {
471        assert!(RULES_SHARED.contains(MARKER));
472        assert!(RULES_SHARED.contains(END_MARKER));
473        assert!(RULES_SHARED.contains(RULES_VERSION));
474    }
475
476    #[test]
477    fn dedicated_rules_have_markers() {
478        assert!(RULES_DEDICATED.contains(MARKER));
479        assert!(RULES_DEDICATED.contains(END_MARKER));
480        assert!(RULES_DEDICATED.contains(RULES_VERSION));
481    }
482
483    #[test]
484    fn cursor_mdc_has_markers_and_frontmatter() {
485        assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
486        assert!(RULES_CURSOR_MDC.contains(END_MARKER));
487        assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
488        assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
489    }
490
491    #[test]
492    fn shared_rules_contain_tool_mapping() {
493        assert!(RULES_SHARED.contains("ctx_read"));
494        assert!(RULES_SHARED.contains("ctx_shell"));
495        assert!(RULES_SHARED.contains("ctx_search"));
496        assert!(RULES_SHARED.contains("ctx_tree"));
497        assert!(RULES_SHARED.contains("Write"));
498    }
499
500    #[test]
501    fn dedicated_rules_contain_modes() {
502        assert!(RULES_DEDICATED.contains("full"));
503        assert!(RULES_DEDICATED.contains("map"));
504        assert!(RULES_DEDICATED.contains("signatures"));
505        assert!(RULES_DEDICATED.contains("diff"));
506        assert!(RULES_DEDICATED.contains("ctx_read"));
507    }
508
509    fn ensure_temp_dir() {
510        let tmp = std::env::temp_dir();
511        if !tmp.exists() {
512            std::fs::create_dir_all(&tmp).ok();
513        }
514    }
515
516    #[test]
517    fn replace_section_with_end_marker() {
518        ensure_temp_dir();
519        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";
520        let path = std::env::temp_dir().join("test_replace_with_end.md");
521        std::fs::write(&path, old).unwrap();
522
523        let result = replace_markdown_section(&path, old).unwrap();
524        assert!(matches!(result, RulesResult::Updated));
525
526        let new_content = std::fs::read_to_string(&path).unwrap();
527        assert!(new_content.contains("lean-ctx-rules-v4"));
528        assert!(new_content.starts_with("user stuff"));
529        assert!(new_content.contains("more user stuff"));
530        assert!(!new_content.contains("lean-ctx-rules-v2"));
531
532        std::fs::remove_file(&path).ok();
533    }
534
535    #[test]
536    fn replace_section_without_end_marker() {
537        ensure_temp_dir();
538        let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
539        let path = std::env::temp_dir().join("test_replace_no_end.md");
540        std::fs::write(&path, old).unwrap();
541
542        let result = replace_markdown_section(&path, old).unwrap();
543        assert!(matches!(result, RulesResult::Updated));
544
545        let new_content = std::fs::read_to_string(&path).unwrap();
546        assert!(new_content.contains("lean-ctx-rules-v4"));
547        assert!(new_content.starts_with("user stuff"));
548
549        std::fs::remove_file(&path).ok();
550    }
551
552    #[test]
553    fn append_to_shared_preserves_existing() {
554        ensure_temp_dir();
555        let path = std::env::temp_dir().join("test_append_shared.md");
556        std::fs::write(&path, "existing user rules\n").unwrap();
557
558        let result = append_to_shared(&path).unwrap();
559        assert!(matches!(result, RulesResult::Injected));
560
561        let content = std::fs::read_to_string(&path).unwrap();
562        assert!(content.starts_with("existing user rules"));
563        assert!(content.contains(MARKER));
564        assert!(content.contains(END_MARKER));
565
566        std::fs::remove_file(&path).ok();
567    }
568
569    #[test]
570    fn write_dedicated_creates_file() {
571        ensure_temp_dir();
572        let path = std::env::temp_dir().join("test_write_dedicated.md");
573        if path.exists() {
574            std::fs::remove_file(&path).ok();
575        }
576
577        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
578        assert!(matches!(result, RulesResult::Injected));
579
580        let content = std::fs::read_to_string(&path).unwrap();
581        assert!(content.contains(MARKER));
582        assert!(content.contains("ctx_read modes"));
583
584        std::fs::remove_file(&path).ok();
585    }
586
587    #[test]
588    fn write_dedicated_updates_existing() {
589        ensure_temp_dir();
590        let path = std::env::temp_dir().join("test_write_dedicated_update.md");
591        std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
592
593        let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
594        assert!(matches!(result, RulesResult::Updated));
595
596        std::fs::remove_file(&path).ok();
597    }
598
599    #[test]
600    fn target_count() {
601        let home = std::path::PathBuf::from("/tmp/fake_home");
602        let targets = build_rules_targets(&home);
603        assert_eq!(targets.len(), 13);
604    }
605}