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
16const 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
43const 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
83const 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
130struct 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 let targets = build_rules_targets(home);
162
163 let mut result = InjectResult {
164 injected: Vec::new(),
165 updated: Vec::new(),
166 already: Vec::new(),
167 errors: Vec::new(),
168 };
169
170 for target in &targets {
171 if !is_tool_detected(target, home) {
172 continue;
173 }
174
175 match inject_rules(target) {
176 Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
177 Ok(RulesResult::Updated) => result.updated.push(target.name.to_string()),
178 Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
179 Err(e) => result.errors.push(format!("{}: {e}", target.name)),
180 }
181 }
182
183 result
184}
185
186pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
187 let targets = build_rules_targets(home);
188 let mut out = Vec::new();
189
190 for target in &targets {
191 let detected = is_tool_detected(target, home);
192 let path = target.path.to_string_lossy().to_string();
193
194 let state = if !detected {
195 "not_detected".to_string()
196 } else if !target.path.exists() {
197 "missing".to_string()
198 } else {
199 match std::fs::read_to_string(&target.path) {
200 Ok(content) => {
201 if content.contains(MARKER) {
202 if content.contains(RULES_VERSION) {
203 "up_to_date".to_string()
204 } else {
205 "outdated".to_string()
206 }
207 } else {
208 "present_without_marker".to_string()
209 }
210 }
211 Err(_) => "read_error".to_string(),
212 }
213 };
214
215 out.push(RulesTargetStatus {
216 name: target.name.to_string(),
217 detected,
218 path,
219 state,
220 note: None,
221 });
222 }
223
224 out
225}
226
227enum RulesResult {
232 Injected,
233 Updated,
234 AlreadyPresent,
235}
236
237fn rules_content(format: &RulesFormat) -> &'static str {
238 match format {
239 RulesFormat::SharedMarkdown => RULES_SHARED,
240 RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
241 RulesFormat::CursorMdc => RULES_CURSOR_MDC,
242 }
243}
244
245fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
246 if target.path.exists() {
247 let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
248 if content.contains(MARKER) {
249 if content.contains(RULES_VERSION) {
250 return Ok(RulesResult::AlreadyPresent);
251 }
252 ensure_parent(&target.path)?;
253 return match target.format {
254 RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
255 RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
256 write_dedicated(&target.path, rules_content(&target.format))
257 }
258 };
259 }
260 }
261
262 ensure_parent(&target.path)?;
263
264 match target.format {
265 RulesFormat::SharedMarkdown => append_to_shared(&target.path),
266 RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
267 write_dedicated(&target.path, rules_content(&target.format))
268 }
269 }
270}
271
272fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
273 if let Some(parent) = path.parent() {
274 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
275 }
276 Ok(())
277}
278
279fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
280 let mut content = if path.exists() {
281 std::fs::read_to_string(path).map_err(|e| e.to_string())?
282 } else {
283 String::new()
284 };
285
286 if !content.is_empty() && !content.ends_with('\n') {
287 content.push('\n');
288 }
289 if !content.is_empty() {
290 content.push('\n');
291 }
292 content.push_str(RULES_SHARED);
293 content.push('\n');
294
295 std::fs::write(path, content).map_err(|e| e.to_string())?;
296 Ok(RulesResult::Injected)
297}
298
299fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
300 let start = content.find(MARKER);
301 let end = content.find(END_MARKER);
302
303 let new_content = match (start, end) {
304 (Some(s), Some(e)) => {
305 let before = &content[..s];
306 let after_end = e + END_MARKER.len();
307 let after = content[after_end..].trim_start_matches('\n');
308 let mut result = before.to_string();
309 result.push_str(RULES_SHARED);
310 if !after.is_empty() {
311 result.push('\n');
312 result.push_str(after);
313 }
314 result
315 }
316 (Some(s), None) => {
317 let before = &content[..s];
318 let mut result = before.to_string();
319 result.push_str(RULES_SHARED);
320 result.push('\n');
321 result
322 }
323 _ => return Ok(RulesResult::AlreadyPresent),
324 };
325
326 std::fs::write(path, new_content).map_err(|e| e.to_string())?;
327 Ok(RulesResult::Updated)
328}
329
330fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
331 let is_update = path.exists() && {
332 let existing = std::fs::read_to_string(path).unwrap_or_default();
333 existing.contains(MARKER)
334 };
335
336 std::fs::write(path, content).map_err(|e| e.to_string())?;
337
338 if is_update {
339 Ok(RulesResult::Updated)
340 } else {
341 Ok(RulesResult::Injected)
342 }
343}
344
345fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
350 match target.name {
351 "Claude Code" => {
352 if command_exists("claude") {
353 return true;
354 }
355 let state_dir = crate::core::editor_registry::claude_state_dir(home);
356 crate::core::editor_registry::claude_mcp_json_path(home).exists() || state_dir.exists()
357 }
358 "Codex CLI" => home.join(".codex").exists() || command_exists("codex"),
359 "Cursor" => home.join(".cursor").exists(),
360 "Windsurf" => home.join(".codeium/windsurf").exists(),
361 "Gemini CLI" => home.join(".gemini").exists(),
362 "VS Code / Copilot" => detect_vscode_installed(home),
363 "Zed" => home.join(".config/zed").exists(),
364 "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
365 "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
366 "OpenCode" => home.join(".config/opencode").exists(),
367 "Continue" => detect_extension_installed(home, "continue.continue"),
368 "Aider" => command_exists("aider") || home.join(".aider.conf.yml").exists(),
369 "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
370 "Qwen Code" => home.join(".qwen").exists(),
371 "Trae" => home.join(".trae").exists(),
372 "Amazon Q Developer" => home.join(".aws/amazonq").exists(),
373 "JetBrains IDEs" => detect_jetbrains_installed(home),
374 "Antigravity" => home.join(".gemini/antigravity").exists(),
375 "Pi Coding Agent" => home.join(".pi").exists() || command_exists("pi"),
376 "AWS Kiro" => home.join(".kiro").exists(),
377 "Crush" => home.join(".config/crush").exists() || command_exists("crush"),
378 "Verdent" => home.join(".verdent").exists(),
379 _ => false,
380 }
381}
382
383fn command_exists(name: &str) -> bool {
384 #[cfg(target_os = "windows")]
385 let result = std::process::Command::new("where")
386 .arg(name)
387 .output()
388 .map(|o| o.status.success())
389 .unwrap_or(false);
390
391 #[cfg(not(target_os = "windows"))]
392 let result = std::process::Command::new("which")
393 .arg(name)
394 .output()
395 .map(|o| o.status.success())
396 .unwrap_or(false);
397
398 result
399}
400
401fn detect_vscode_installed(_home: &std::path::Path) -> bool {
402 let check_dir = |dir: PathBuf| -> bool {
403 dir.join("settings.json").exists() || dir.join("mcp.json").exists()
404 };
405
406 #[cfg(target_os = "macos")]
407 if check_dir(_home.join("Library/Application Support/Code/User")) {
408 return true;
409 }
410 #[cfg(target_os = "linux")]
411 if check_dir(_home.join(".config/Code/User")) {
412 return true;
413 }
414 #[cfg(target_os = "windows")]
415 if let Ok(appdata) = std::env::var("APPDATA") {
416 if check_dir(PathBuf::from(&appdata).join("Code/User")) {
417 return true;
418 }
419 }
420 false
421}
422
423fn detect_jetbrains_installed(home: &std::path::Path) -> bool {
424 #[cfg(target_os = "macos")]
425 if home.join("Library/Application Support/JetBrains").exists() {
426 return true;
427 }
428 #[cfg(target_os = "linux")]
429 if home.join(".config/JetBrains").exists() {
430 return true;
431 }
432 home.join(".jb-mcp.json").exists()
433}
434
435fn detect_extension_installed(_home: &std::path::Path, extension_id: &str) -> bool {
436 #[cfg(target_os = "macos")]
437 {
438 if _home
439 .join(format!(
440 "Library/Application Support/Code/User/globalStorage/{extension_id}"
441 ))
442 .exists()
443 {
444 return true;
445 }
446 }
447 #[cfg(target_os = "linux")]
448 {
449 if _home
450 .join(format!(".config/Code/User/globalStorage/{extension_id}"))
451 .exists()
452 {
453 return true;
454 }
455 }
456 #[cfg(target_os = "windows")]
457 {
458 if let Ok(appdata) = std::env::var("APPDATA") {
459 if std::path::PathBuf::from(&appdata)
460 .join(format!("Code/User/globalStorage/{extension_id}"))
461 .exists()
462 {
463 return true;
464 }
465 }
466 }
467 false
468}
469
470fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
475 vec![
476 RulesTarget {
478 name: "Claude Code",
479 path: crate::core::editor_registry::claude_rules_dir(home).join("lean-ctx.md"),
480 format: RulesFormat::DedicatedMarkdown,
481 },
482 RulesTarget {
483 name: "Codex CLI",
484 path: home.join(".codex/instructions.md"),
485 format: RulesFormat::SharedMarkdown,
486 },
487 RulesTarget {
488 name: "Gemini CLI",
489 path: home.join(".gemini/GEMINI.md"),
490 format: RulesFormat::SharedMarkdown,
491 },
492 RulesTarget {
493 name: "VS Code / Copilot",
494 path: copilot_instructions_path(home),
495 format: RulesFormat::SharedMarkdown,
496 },
497 RulesTarget {
499 name: "Cursor",
500 path: home.join(".cursor/rules/lean-ctx.mdc"),
501 format: RulesFormat::CursorMdc,
502 },
503 RulesTarget {
504 name: "Windsurf",
505 path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
506 format: RulesFormat::DedicatedMarkdown,
507 },
508 RulesTarget {
509 name: "Zed",
510 path: home.join(".config/zed/rules/lean-ctx.md"),
511 format: RulesFormat::DedicatedMarkdown,
512 },
513 RulesTarget {
514 name: "Cline",
515 path: home.join(".cline/rules/lean-ctx.md"),
516 format: RulesFormat::DedicatedMarkdown,
517 },
518 RulesTarget {
519 name: "Roo Code",
520 path: home.join(".roo/rules/lean-ctx.md"),
521 format: RulesFormat::DedicatedMarkdown,
522 },
523 RulesTarget {
524 name: "OpenCode",
525 path: home.join(".config/opencode/rules/lean-ctx.md"),
526 format: RulesFormat::DedicatedMarkdown,
527 },
528 RulesTarget {
529 name: "Continue",
530 path: home.join(".continue/rules/lean-ctx.md"),
531 format: RulesFormat::DedicatedMarkdown,
532 },
533 RulesTarget {
534 name: "Aider",
535 path: home.join(".aider/rules/lean-ctx.md"),
536 format: RulesFormat::DedicatedMarkdown,
537 },
538 RulesTarget {
539 name: "Amp",
540 path: home.join(".ampcoder/rules/lean-ctx.md"),
541 format: RulesFormat::DedicatedMarkdown,
542 },
543 RulesTarget {
544 name: "Qwen Code",
545 path: home.join(".qwen/rules/lean-ctx.md"),
546 format: RulesFormat::DedicatedMarkdown,
547 },
548 RulesTarget {
549 name: "Trae",
550 path: home.join(".trae/rules/lean-ctx.md"),
551 format: RulesFormat::DedicatedMarkdown,
552 },
553 RulesTarget {
554 name: "Amazon Q Developer",
555 path: home.join(".aws/amazonq/rules/lean-ctx.md"),
556 format: RulesFormat::DedicatedMarkdown,
557 },
558 RulesTarget {
559 name: "JetBrains IDEs",
560 path: home.join(".jb-rules/lean-ctx.md"),
561 format: RulesFormat::DedicatedMarkdown,
562 },
563 RulesTarget {
564 name: "Antigravity",
565 path: home.join(".gemini/antigravity/rules/lean-ctx.md"),
566 format: RulesFormat::DedicatedMarkdown,
567 },
568 RulesTarget {
569 name: "Pi Coding Agent",
570 path: home.join(".pi/rules/lean-ctx.md"),
571 format: RulesFormat::DedicatedMarkdown,
572 },
573 RulesTarget {
574 name: "AWS Kiro",
575 path: home.join(".kiro/steering/lean-ctx.md"),
576 format: RulesFormat::DedicatedMarkdown,
577 },
578 RulesTarget {
579 name: "Verdent",
580 path: home.join(".verdent/rules/lean-ctx.md"),
581 format: RulesFormat::DedicatedMarkdown,
582 },
583 RulesTarget {
584 name: "Crush",
585 path: home.join(".config/crush/rules/lean-ctx.md"),
586 format: RulesFormat::DedicatedMarkdown,
587 },
588 ]
589}
590
591fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
592 #[cfg(target_os = "macos")]
593 {
594 return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
595 }
596 #[cfg(target_os = "linux")]
597 {
598 return home.join(".config/Code/User/github-copilot-instructions.md");
599 }
600 #[cfg(target_os = "windows")]
601 {
602 if let Ok(appdata) = std::env::var("APPDATA") {
603 return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
604 }
605 }
606 #[allow(unreachable_code)]
607 home.join(".config/Code/User/github-copilot-instructions.md")
608}
609
610#[cfg(test)]
615mod tests {
616 use super::*;
617
618 #[test]
619 fn shared_rules_have_markers() {
620 assert!(RULES_SHARED.contains(MARKER));
621 assert!(RULES_SHARED.contains(END_MARKER));
622 assert!(RULES_SHARED.contains(RULES_VERSION));
623 }
624
625 #[test]
626 fn dedicated_rules_have_markers() {
627 assert!(RULES_DEDICATED.contains(MARKER));
628 assert!(RULES_DEDICATED.contains(END_MARKER));
629 assert!(RULES_DEDICATED.contains(RULES_VERSION));
630 }
631
632 #[test]
633 fn cursor_mdc_has_markers_and_frontmatter() {
634 assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
635 assert!(RULES_CURSOR_MDC.contains(END_MARKER));
636 assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
637 assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
638 }
639
640 #[test]
641 fn shared_rules_contain_tool_mapping() {
642 assert!(RULES_SHARED.contains("ctx_read"));
643 assert!(RULES_SHARED.contains("ctx_shell"));
644 assert!(RULES_SHARED.contains("ctx_search"));
645 assert!(RULES_SHARED.contains("ctx_tree"));
646 assert!(RULES_SHARED.contains("Write"));
647 }
648
649 #[test]
650 fn shared_rules_litm_optimized() {
651 let lines: Vec<&str> = RULES_SHARED.lines().collect();
652 let first_5 = lines[..5.min(lines.len())].join("\n");
653 assert!(
654 first_5.contains("PREFER") || first_5.contains("lean-ctx"),
655 "LITM: preference instruction must be near start"
656 );
657 let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
658 assert!(
659 last_5.contains("fallback") || last_5.contains("native"),
660 "LITM: fallback note must be near end"
661 );
662 }
663
664 #[test]
665 fn dedicated_rules_contain_modes() {
666 assert!(RULES_DEDICATED.contains("auto"));
667 assert!(RULES_DEDICATED.contains("full"));
668 assert!(RULES_DEDICATED.contains("map"));
669 assert!(RULES_DEDICATED.contains("signatures"));
670 assert!(RULES_DEDICATED.contains("diff"));
671 assert!(RULES_DEDICATED.contains("aggressive"));
672 assert!(RULES_DEDICATED.contains("entropy"));
673 assert!(RULES_DEDICATED.contains("task"));
674 assert!(RULES_DEDICATED.contains("reference"));
675 assert!(RULES_DEDICATED.contains("ctx_read"));
676 }
677
678 #[test]
679 fn dedicated_rules_litm_optimized() {
680 let lines: Vec<&str> = RULES_DEDICATED.lines().collect();
681 let first_5 = lines[..5.min(lines.len())].join("\n");
682 assert!(
683 first_5.contains("PREFER") || first_5.contains("lean-ctx"),
684 "LITM: preference instruction must be near start"
685 );
686 let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
687 assert!(
688 last_5.contains("fallback") || last_5.contains("ctx_compress"),
689 "LITM: practical note must be near end"
690 );
691 }
692
693 #[test]
694 fn cursor_mdc_litm_optimized() {
695 let lines: Vec<&str> = RULES_CURSOR_MDC.lines().collect();
696 let first_10 = lines[..10.min(lines.len())].join("\n");
697 assert!(
698 first_10.contains("PREFER") || first_10.contains("lean-ctx"),
699 "LITM: preference instruction must be near start of MDC"
700 );
701 let last_5 = lines[lines.len().saturating_sub(5)..].join("\n");
702 assert!(
703 last_5.contains("fallback") || last_5.contains("native"),
704 "LITM: fallback note must be near end of MDC"
705 );
706 }
707
708 fn ensure_temp_dir() {
709 let tmp = std::env::temp_dir();
710 if !tmp.exists() {
711 std::fs::create_dir_all(&tmp).ok();
712 }
713 }
714
715 #[test]
716 fn replace_section_with_end_marker() {
717 ensure_temp_dir();
718 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";
719 let path = std::env::temp_dir().join("test_replace_with_end.md");
720 std::fs::write(&path, old).unwrap();
721
722 let result = replace_markdown_section(&path, old).unwrap();
723 assert!(matches!(result, RulesResult::Updated));
724
725 let new_content = std::fs::read_to_string(&path).unwrap();
726 assert!(new_content.contains(RULES_VERSION));
727 assert!(new_content.starts_with("user stuff"));
728 assert!(new_content.contains("more user stuff"));
729 assert!(!new_content.contains("lean-ctx-rules-v2"));
730
731 std::fs::remove_file(&path).ok();
732 }
733
734 #[test]
735 fn replace_section_without_end_marker() {
736 ensure_temp_dir();
737 let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
738 let path = std::env::temp_dir().join("test_replace_no_end.md");
739 std::fs::write(&path, old).unwrap();
740
741 let result = replace_markdown_section(&path, old).unwrap();
742 assert!(matches!(result, RulesResult::Updated));
743
744 let new_content = std::fs::read_to_string(&path).unwrap();
745 assert!(new_content.contains(RULES_VERSION));
746 assert!(new_content.starts_with("user stuff"));
747
748 std::fs::remove_file(&path).ok();
749 }
750
751 #[test]
752 fn append_to_shared_preserves_existing() {
753 ensure_temp_dir();
754 let path = std::env::temp_dir().join("test_append_shared.md");
755 std::fs::write(&path, "existing user rules\n").unwrap();
756
757 let result = append_to_shared(&path).unwrap();
758 assert!(matches!(result, RulesResult::Injected));
759
760 let content = std::fs::read_to_string(&path).unwrap();
761 assert!(content.starts_with("existing user rules"));
762 assert!(content.contains(MARKER));
763 assert!(content.contains(END_MARKER));
764
765 std::fs::remove_file(&path).ok();
766 }
767
768 #[test]
769 fn write_dedicated_creates_file() {
770 ensure_temp_dir();
771 let path = std::env::temp_dir().join("test_write_dedicated.md");
772 if path.exists() {
773 std::fs::remove_file(&path).ok();
774 }
775
776 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
777 assert!(matches!(result, RulesResult::Injected));
778
779 let content = std::fs::read_to_string(&path).unwrap();
780 assert!(content.contains(MARKER));
781 assert!(content.contains("ctx_read modes"));
782
783 std::fs::remove_file(&path).ok();
784 }
785
786 #[test]
787 fn write_dedicated_updates_existing() {
788 ensure_temp_dir();
789 let path = std::env::temp_dir().join("test_write_dedicated_update.md");
790 std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
791
792 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
793 assert!(matches!(result, RulesResult::Updated));
794
795 std::fs::remove_file(&path).ok();
796 }
797
798 #[test]
799 fn target_count() {
800 let home = std::path::PathBuf::from("/tmp/fake_home");
801 let targets = build_rules_targets(&home);
802 assert_eq!(targets.len(), 22);
803 }
804}