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
7const RULES_SHARED: &str = r#"# lean-ctx — Context Engineering Layer
13<!-- lean-ctx-rules-v4 -->
14
15CRITICAL RULE: You have lean-ctx MCP tools connected. You MUST use them for ALL file reads,
16shell commands, and code searches. Using native tools instead wastes tokens and is FORBIDDEN.
17
18## Tool replacements (MANDATORY — no exceptions):
19| FORBIDDEN | USE INSTEAD | Saves |
20|-----------|-------------|-------|
21| Read, cat, head, tail | ctx_read | 40-90% via caching + compression |
22| Shell, bash, terminal | ctx_shell | 30-70% via pattern compression |
23| Grep, rg, search | ctx_search | 50-80% via compact results |
24| ls, find, tree | ctx_tree | 60-85% via directory maps |
25
26## How to call (use your MCP tool syntax):
27- Claude Code: `mcp__lean-ctx__ctx_read(path="/src/main.rs", mode="full")`
28- Codex CLI: `mcp__lean-ctx__ctx_shell(command="cargo test")`
29- Gemini CLI: Use the lean-ctx MCP tools directly: `ctx_read`, `ctx_shell`, `ctx_search`, `ctx_tree`
30
31## Native tools to keep using (no lean-ctx replacement):
32Write, StrReplace, Delete, Glob — use these normally.
33
34## If you catch yourself about to use Read, Shell, Grep, or ls:
35STOP. Use ctx_read, ctx_shell, ctx_search, or ctx_tree instead. Every time.
36<!-- /lean-ctx -->"#;
37
38const RULES_DEDICATED: &str = r#"# lean-ctx — Context Engineering Layer
44<!-- lean-ctx-rules-v4 -->
45
46You are connected to the lean-ctx MCP server, which provides optimized replacements for
47built-in file, shell, and search tools. Using the lean-ctx tools is MANDATORY — not optional.
48
49## MANDATORY tool replacements:
50
51| FORBIDDEN tool | REQUIRED replacement | Why |
52|----------------|---------------------|-----|
53| `Read` / `cat` / `head` / `tail` | `ctx_read(path)` | Cached reads, 6 compression modes, re-reads cost ~13 tokens |
54| `Shell` / `bash` / terminal | `ctx_shell(command)` | Pattern-based output compression for git, npm, cargo, docker |
55| `Grep` / `rg` / `search` | `ctx_search(pattern, path)` | Compact context-aware results, token-efficient |
56| `ls` / `find` / `tree` | `ctx_tree(path, depth)` | Compact directory maps with file counts |
57
58## How to call (MCP tool syntax):
59```
60ctx_read(path="/src/main.rs", mode="full")
61ctx_shell(command="cargo test")
62ctx_search(pattern="fn main", path="src/")
63ctx_tree(path=".", depth=3)
64```
65
66## ctx_read modes (use the right mode for the job):
67- `full` — default, cached read. Use for files you will edit.
68- `map` — dependency graph + exports + key signatures. Use for context-only files.
69- `signatures` — API surface only. Use for large files you just need the structure of.
70- `diff` — changed lines only. Use after your own edits to verify.
71- `aggressive` — syntax stripped. Use for very large files.
72- `entropy` — Shannon + Jaccard filtering. Use for noisy files.
73- `lines:N-M` — specific line range. Use when you know exactly what you need.
74
75## Tools you KEEP using (no lean-ctx replacement):
76- `Write` — create/overwrite files
77- `StrReplace` — edit files in place
78- `Delete` — delete files
79- `Glob` — find files by glob pattern
80
81## ABSOLUTE RULES — violations waste user tokens:
821. NEVER use `Read` to read a file — always use `ctx_read`
832. NEVER use `Shell` to run a command — always use `ctx_shell`
843. NEVER use `Grep` or `rg` to search — always use `ctx_search`
854. NEVER use `ls`, `find`, `cat`, `head`, `tail` — always use `ctx_tree` or `ctx_read`
865. You do NOT need to `ctx_read` a file before creating it with `Write`
876. If `ctx_read` returns "cached" and you need fresh content, set `fresh=true`
88
89## Proactive tools (use without being asked):
90- `ctx_overview(task)` — at session start, get task-relevant project map
91- `ctx_compress` — when context grows large, create checkpoint
92- `ctx_metrics` — periodically verify token savings
93<!-- /lean-ctx -->"#;
94
95const RULES_CURSOR_MDC: &str = r#"---
100description: "lean-ctx: ALWAYS use ctx_read/ctx_shell/ctx_search/ctx_tree instead of Read/Shell/Grep/ls"
101alwaysApply: true
102---
103
104# lean-ctx — Context Engineering Layer
105<!-- lean-ctx-rules-v4 -->
106
107You are connected to the lean-ctx MCP server. You MUST use lean-ctx tools for ALL file reads,
108shell commands, and code searches. Using native tools instead is FORBIDDEN — it wastes tokens.
109
110## MANDATORY tool replacements:
111
112| FORBIDDEN | USE INSTEAD | Why |
113|-----------|-------------|-----|
114| `Read` / `cat` / `head` / `tail` | `ctx_read(path)` | Cached, 6 compression modes, re-reads ~13 tokens |
115| `Shell` / `bash` / terminal | `ctx_shell(command)` | Pattern compression for git/npm/cargo/docker output |
116| `Grep` / `rg` / `search` | `ctx_search(pattern, path)` | Compact, token-efficient results |
117| `ls` / `find` / `tree` | `ctx_tree(path, depth)` | Compact directory maps with file counts |
118
119## How to call in Cursor (exact syntax):
120```
121CallMcpTool(server="user-lean-ctx", toolName="ctx_read", arguments={"path": "/src/main.rs", "mode": "full"})
122CallMcpTool(server="user-lean-ctx", toolName="ctx_shell", arguments={"command": "cargo test"})
123CallMcpTool(server="user-lean-ctx", toolName="ctx_search", arguments={"pattern": "fn main", "path": "src/"})
124CallMcpTool(server="user-lean-ctx", toolName="ctx_tree", arguments={"path": ".", "depth": 3})
125```
126
127## ctx_read modes:
128- `full` — cached read (for files you edit)
129- `map` — deps + API (context-only files)
130- `signatures` — API surface only
131- `diff` — changed lines after edits
132- `aggressive` — syntax stripped
133- `entropy` — Shannon + Jaccard filtering
134- `lines:N-M` — specific range
135
136## Keep using (no lean-ctx replacement):
137`Write`, `StrReplace`, `Delete`, `Glob` — use normally.
138
139## NEVER do this:
140- NEVER use `Read` to read files — use `ctx_read`
141- NEVER use `Shell` to run commands — use `ctx_shell`
142- NEVER use `Grep` to search code — use `ctx_search`
143- NEVER use `ls`, `find`, `cat`, `head`, `tail` — use `ctx_tree` or `ctx_read`
144- If `ctx_read` returns "cached", use `fresh=true` to re-read
145
146## Proactive (use without being asked):
147- `ctx_overview(task)` at session start
148- `ctx_compress` when context grows large
149- `ctx_metrics` to verify savings
150<!-- /lean-ctx -->"#;
151
152struct RulesTarget {
155 name: &'static str,
156 path: PathBuf,
157 format: RulesFormat,
158}
159
160enum RulesFormat {
161 SharedMarkdown,
162 DedicatedMarkdown,
163 CursorMdc,
164}
165
166pub struct InjectResult {
167 pub injected: Vec<String>,
168 pub updated: Vec<String>,
169 pub already: Vec<String>,
170 pub errors: Vec<String>,
171}
172
173pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
174 let targets = build_rules_targets(home);
175
176 let mut result = InjectResult {
177 injected: Vec::new(),
178 updated: Vec::new(),
179 already: Vec::new(),
180 errors: Vec::new(),
181 };
182
183 for target in &targets {
184 if !is_tool_detected(target, home) {
185 continue;
186 }
187
188 match inject_rules(target) {
189 Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
190 Ok(RulesResult::Updated) => result.updated.push(target.name.to_string()),
191 Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
192 Err(e) => result.errors.push(format!("{}: {e}", target.name)),
193 }
194 }
195
196 result
197}
198
199enum RulesResult {
204 Injected,
205 Updated,
206 AlreadyPresent,
207}
208
209fn rules_content(format: &RulesFormat) -> &'static str {
210 match format {
211 RulesFormat::SharedMarkdown => RULES_SHARED,
212 RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
213 RulesFormat::CursorMdc => RULES_CURSOR_MDC,
214 }
215}
216
217fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
218 if target.path.exists() {
219 let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
220 if content.contains(MARKER) {
221 if content.contains(RULES_VERSION) {
222 return Ok(RulesResult::AlreadyPresent);
223 }
224 ensure_parent(&target.path)?;
225 return match target.format {
226 RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
227 RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
228 write_dedicated(&target.path, rules_content(&target.format))
229 }
230 };
231 }
232 }
233
234 ensure_parent(&target.path)?;
235
236 match target.format {
237 RulesFormat::SharedMarkdown => append_to_shared(&target.path),
238 RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
239 write_dedicated(&target.path, rules_content(&target.format))
240 }
241 }
242}
243
244fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
247 }
248 Ok(())
249}
250
251fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
252 let mut content = if path.exists() {
253 std::fs::read_to_string(path).map_err(|e| e.to_string())?
254 } else {
255 String::new()
256 };
257
258 if !content.is_empty() && !content.ends_with('\n') {
259 content.push('\n');
260 }
261 if !content.is_empty() {
262 content.push('\n');
263 }
264 content.push_str(RULES_SHARED);
265 content.push('\n');
266
267 std::fs::write(path, content).map_err(|e| e.to_string())?;
268 Ok(RulesResult::Injected)
269}
270
271fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
272 let start = content.find(MARKER);
273 let end = content.find(END_MARKER);
274
275 let new_content = match (start, end) {
276 (Some(s), Some(e)) => {
277 let before = &content[..s];
278 let after_end = e + END_MARKER.len();
279 let after = content[after_end..].trim_start_matches('\n');
280 let mut result = before.to_string();
281 result.push_str(RULES_SHARED);
282 if !after.is_empty() {
283 result.push('\n');
284 result.push_str(after);
285 }
286 result
287 }
288 (Some(s), None) => {
289 let before = &content[..s];
290 let mut result = before.to_string();
291 result.push_str(RULES_SHARED);
292 result.push('\n');
293 result
294 }
295 _ => return Ok(RulesResult::AlreadyPresent),
296 };
297
298 std::fs::write(path, new_content).map_err(|e| e.to_string())?;
299 Ok(RulesResult::Updated)
300}
301
302fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
303 let is_update = path.exists() && {
304 let existing = std::fs::read_to_string(path).unwrap_or_default();
305 existing.contains(MARKER)
306 };
307
308 std::fs::write(path, content).map_err(|e| e.to_string())?;
309
310 if is_update {
311 Ok(RulesResult::Updated)
312 } else {
313 Ok(RulesResult::Injected)
314 }
315}
316
317fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
322 match target.name {
323 "Claude Code" => {
324 if command_exists("claude") {
325 return true;
326 }
327 home.join(".claude.json").exists() || home.join(".claude").exists()
328 }
329 "Codex CLI" => home.join(".codex").exists() || command_exists("codex"),
330 "Cursor" => home.join(".cursor").exists(),
331 "Windsurf" => home.join(".codeium/windsurf").exists(),
332 "Gemini CLI" => home.join(".gemini").exists(),
333 "VS Code / Copilot" => detect_vscode_installed(home),
334 "Zed" => home.join(".config/zed").exists(),
335 "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
336 "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
337 "OpenCode" => home.join(".config/opencode").exists(),
338 "Continue" => detect_extension_installed(home, "continue.continue"),
339 "Aider" => command_exists("aider") || home.join(".aider.conf.yml").exists(),
340 "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
341 _ => false,
342 }
343}
344
345fn command_exists(name: &str) -> bool {
346 #[cfg(target_os = "windows")]
347 let result = std::process::Command::new("where")
348 .arg(name)
349 .output()
350 .map(|o| o.status.success())
351 .unwrap_or(false);
352
353 #[cfg(not(target_os = "windows"))]
354 let result = std::process::Command::new("which")
355 .arg(name)
356 .output()
357 .map(|o| o.status.success())
358 .unwrap_or(false);
359
360 result
361}
362
363fn detect_vscode_installed(home: &std::path::Path) -> bool {
364 let check_dir = |dir: PathBuf| -> bool {
365 dir.join("settings.json").exists() || dir.join("mcp.json").exists()
366 };
367
368 #[cfg(target_os = "macos")]
369 if check_dir(home.join("Library/Application Support/Code/User")) {
370 return true;
371 }
372 #[cfg(target_os = "linux")]
373 if check_dir(home.join(".config/Code/User")) {
374 return true;
375 }
376 #[cfg(target_os = "windows")]
377 if let Ok(appdata) = std::env::var("APPDATA") {
378 if check_dir(PathBuf::from(&appdata).join("Code/User")) {
379 return true;
380 }
381 }
382 false
383}
384
385fn detect_extension_installed(home: &std::path::Path, extension_id: &str) -> bool {
386 #[cfg(target_os = "macos")]
387 {
388 if home
389 .join(format!(
390 "Library/Application Support/Code/User/globalStorage/{extension_id}"
391 ))
392 .exists()
393 {
394 return true;
395 }
396 }
397 #[cfg(target_os = "linux")]
398 {
399 if home
400 .join(format!(".config/Code/User/globalStorage/{extension_id}"))
401 .exists()
402 {
403 return true;
404 }
405 }
406 #[cfg(target_os = "windows")]
407 {
408 if let Ok(appdata) = std::env::var("APPDATA") {
409 if std::path::PathBuf::from(&appdata)
410 .join(format!("Code/User/globalStorage/{extension_id}"))
411 .exists()
412 {
413 return true;
414 }
415 }
416 }
417 false
418}
419
420fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
425 vec![
426 RulesTarget {
428 name: "Claude Code",
429 path: home.join(".claude/CLAUDE.md"),
430 format: RulesFormat::SharedMarkdown,
431 },
432 RulesTarget {
433 name: "Codex CLI",
434 path: home.join(".codex/instructions.md"),
435 format: RulesFormat::SharedMarkdown,
436 },
437 RulesTarget {
438 name: "Gemini CLI",
439 path: home.join(".gemini/GEMINI.md"),
440 format: RulesFormat::SharedMarkdown,
441 },
442 RulesTarget {
443 name: "VS Code / Copilot",
444 path: copilot_instructions_path(home),
445 format: RulesFormat::SharedMarkdown,
446 },
447 RulesTarget {
449 name: "Cursor",
450 path: home.join(".cursor/rules/lean-ctx.mdc"),
451 format: RulesFormat::CursorMdc,
452 },
453 RulesTarget {
454 name: "Windsurf",
455 path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
456 format: RulesFormat::DedicatedMarkdown,
457 },
458 RulesTarget {
459 name: "Zed",
460 path: home.join(".config/zed/rules/lean-ctx.md"),
461 format: RulesFormat::DedicatedMarkdown,
462 },
463 RulesTarget {
464 name: "Cline",
465 path: home.join(".cline/rules/lean-ctx.md"),
466 format: RulesFormat::DedicatedMarkdown,
467 },
468 RulesTarget {
469 name: "Roo Code",
470 path: home.join(".roo/rules/lean-ctx.md"),
471 format: RulesFormat::DedicatedMarkdown,
472 },
473 RulesTarget {
474 name: "OpenCode",
475 path: home.join(".config/opencode/rules/lean-ctx.md"),
476 format: RulesFormat::DedicatedMarkdown,
477 },
478 RulesTarget {
479 name: "Continue",
480 path: home.join(".continue/rules/lean-ctx.md"),
481 format: RulesFormat::DedicatedMarkdown,
482 },
483 RulesTarget {
484 name: "Aider",
485 path: home.join(".aider/rules/lean-ctx.md"),
486 format: RulesFormat::DedicatedMarkdown,
487 },
488 RulesTarget {
489 name: "Amp",
490 path: home.join(".ampcoder/rules/lean-ctx.md"),
491 format: RulesFormat::DedicatedMarkdown,
492 },
493 ]
494}
495
496fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
497 #[cfg(target_os = "macos")]
498 {
499 return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
500 }
501 #[cfg(target_os = "linux")]
502 {
503 return home.join(".config/Code/User/github-copilot-instructions.md");
504 }
505 #[cfg(target_os = "windows")]
506 {
507 if let Ok(appdata) = std::env::var("APPDATA") {
508 return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
509 }
510 }
511 #[allow(unreachable_code)]
512 home.join(".config/Code/User/github-copilot-instructions.md")
513}
514
515#[cfg(test)]
520mod tests {
521 use super::*;
522
523 #[test]
524 fn shared_rules_have_markers() {
525 assert!(RULES_SHARED.contains(MARKER));
526 assert!(RULES_SHARED.contains(END_MARKER));
527 assert!(RULES_SHARED.contains(RULES_VERSION));
528 }
529
530 #[test]
531 fn dedicated_rules_have_markers() {
532 assert!(RULES_DEDICATED.contains(MARKER));
533 assert!(RULES_DEDICATED.contains(END_MARKER));
534 assert!(RULES_DEDICATED.contains(RULES_VERSION));
535 }
536
537 #[test]
538 fn cursor_mdc_has_markers_and_frontmatter() {
539 assert!(RULES_CURSOR_MDC.contains(MARKER));
540 assert!(RULES_CURSOR_MDC.contains(END_MARKER));
541 assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
542 assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
543 }
544
545 #[test]
546 fn shared_rules_contain_forbidden_table() {
547 assert!(RULES_SHARED.contains("FORBIDDEN"));
548 assert!(RULES_SHARED.contains("ctx_read"));
549 assert!(RULES_SHARED.contains("ctx_shell"));
550 assert!(RULES_SHARED.contains("ctx_search"));
551 assert!(RULES_SHARED.contains("ctx_tree"));
552 }
553
554 #[test]
555 fn dedicated_rules_contain_modes() {
556 assert!(RULES_DEDICATED.contains("full"));
557 assert!(RULES_DEDICATED.contains("map"));
558 assert!(RULES_DEDICATED.contains("signatures"));
559 assert!(RULES_DEDICATED.contains("diff"));
560 assert!(RULES_DEDICATED.contains("aggressive"));
561 assert!(RULES_DEDICATED.contains("entropy"));
562 }
563
564 #[test]
565 fn replace_section_with_end_marker() {
566 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";
567 let path = std::env::temp_dir().join("test_replace_with_end.md");
568 std::fs::write(&path, old).unwrap();
569
570 let result = replace_markdown_section(&path, old).unwrap();
571 assert!(matches!(result, RulesResult::Updated));
572
573 let new_content = std::fs::read_to_string(&path).unwrap();
574 assert!(new_content.contains("lean-ctx-rules-v4"));
575 assert!(new_content.starts_with("user stuff"));
576 assert!(new_content.contains("more user stuff"));
577 assert!(!new_content.contains("lean-ctx-rules-v2"));
578
579 std::fs::remove_file(&path).ok();
580 }
581
582 #[test]
583 fn replace_section_without_end_marker() {
584 let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
585 let path = std::env::temp_dir().join("test_replace_no_end.md");
586 std::fs::write(&path, old).unwrap();
587
588 let result = replace_markdown_section(&path, old).unwrap();
589 assert!(matches!(result, RulesResult::Updated));
590
591 let new_content = std::fs::read_to_string(&path).unwrap();
592 assert!(new_content.contains("lean-ctx-rules-v4"));
593 assert!(new_content.starts_with("user stuff"));
594
595 std::fs::remove_file(&path).ok();
596 }
597
598 #[test]
599 fn append_to_shared_preserves_existing() {
600 let path = std::env::temp_dir().join("test_append_shared.md");
601 std::fs::write(&path, "existing user rules\n").unwrap();
602
603 let result = append_to_shared(&path).unwrap();
604 assert!(matches!(result, RulesResult::Injected));
605
606 let content = std::fs::read_to_string(&path).unwrap();
607 assert!(content.starts_with("existing user rules"));
608 assert!(content.contains(MARKER));
609 assert!(content.contains(END_MARKER));
610
611 std::fs::remove_file(&path).ok();
612 }
613
614 #[test]
615 fn write_dedicated_creates_file() {
616 let path = std::env::temp_dir().join("test_write_dedicated.md");
617 if path.exists() {
618 std::fs::remove_file(&path).ok();
619 }
620
621 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
622 assert!(matches!(result, RulesResult::Injected));
623
624 let content = std::fs::read_to_string(&path).unwrap();
625 assert!(content.contains(MARKER));
626 assert!(content.contains("ctx_read modes"));
627
628 std::fs::remove_file(&path).ok();
629 }
630
631 #[test]
632 fn write_dedicated_updates_existing() {
633 let path = std::env::temp_dir().join("test_write_dedicated_update.md");
634 std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
635
636 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
637 assert!(matches!(result, RulesResult::Updated));
638
639 std::fs::remove_file(&path).ok();
640 }
641
642 #[test]
643 fn target_count() {
644 let home = std::path::PathBuf::from("/tmp/fake_home");
645 let targets = build_rules_targets(&home);
646 assert_eq!(targets.len(), 13);
647 }
648}