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-v11";
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
16pub fn rules_shared_content() -> &'static str {
17 RULES_SHARED
18}
19
20const RULES_SHARED: &str = r#"# lean-ctx — Context Engineering Layer
26<!-- lean-ctx-rules-v11 -->
27
28## Tool Mapping (MANDATORY — use instead of native equivalents)
29| Instead of | Use | Example |
30|------------|-----|---------|
31| Read/cat/head/tail | `ctx_read(path, mode)` | `ctx_read("src/main.rs", "full")` |
32| Grep/rg/find | `ctx_search(pattern, path)` | `ctx_search("fn handle", "src/")` |
33| Shell/bash | `ctx_shell(command)` | `ctx_shell("cargo test")` |
34| Edit (when Read unavailable) | `ctx_edit(path, old, new)` | `ctx_edit("f.rs", "old", "new")` |
35
36## ctx_read Mode Selection
37| Goal | Mode | When |
38|------|------|------|
39| Edit this file | `full` | Before any edit |
40| Understand API | `signatures` | Context-only, won't edit |
41| Re-read after edit | `diff` | Post-edit verification |
42| Large file overview | `map` | >500 lines, won't edit |
43| Specific region | `lines:N-M` | Know exact location |
44
45## Workflow (follow this order)
461. **Orient:** `ctx_overview(task)` or `ctx_compose(task, path)` for unfamiliar tasks
472. **Locate:** `ctx_search(pattern, path)` for exact text; `ctx_semantic_search(query)` for concepts
483. **Read:** `ctx_read(path, mode)` with appropriate mode from table above
494. **Edit:** `ctx_edit(path, old_string, new_string)` or native Edit if available
505. **Verify:** `ctx_read(path, "diff")` + `ctx_shell("test command")`
516. **Record:** `ctx_knowledge(action="remember", content="...")` for non-obvious findings
52
53## Session
54- **Start:** `ctx_session(action="status")` + `ctx_knowledge(action="wakeup")`
55- **End:** `ctx_session(action="decision", content="what was done + next steps")`
56- **On [CHECKPOINT]:** `ctx_session(action="task", value="current status")`
57
58NEVER use native Read/Grep/Shell when ctx_* equivalents are available.
59<!-- /lean-ctx -->"#;
60
61const RULES_DEDICATED: &str = r#"# lean-ctx — Context Engineering Layer
67<!-- lean-ctx-rules-v11 -->
68
69## Tool Mapping (MANDATORY — use instead of native equivalents)
70| Instead of | Use | Example |
71|------------|-----|---------|
72| Read/cat/head/tail | `ctx_read(path, mode)` | `ctx_read("src/main.rs", "full")` |
73| Grep/rg/find | `ctx_search(pattern, path)` | `ctx_search("fn handle", "src/")` |
74| Shell/bash | `ctx_shell(command)` | `ctx_shell("cargo test")` |
75| Edit (when Read unavailable) | `ctx_edit(path, old, new)` | `ctx_edit("f.rs", "old", "new")` |
76
77## ctx_read Mode Selection
78| Goal | Mode | When |
79|------|------|------|
80| Edit this file | `full` | Before any edit |
81| Understand API | `signatures` | Context-only, won't edit |
82| Re-read after edit | `diff` | Post-edit verification |
83| Large file overview | `map` | >500 lines, won't edit |
84| Specific region | `lines:N-M` | Know exact location |
85| Unsure | `auto` | System selects optimal mode |
86
87## Workflow (follow this order)
881. **Orient:** `ctx_overview(task)` or `ctx_compose(task, path)` for unfamiliar tasks
892. **Locate:** `ctx_search(pattern, path)` for exact text; `ctx_semantic_search(query)` for concepts
903. **Read:** `ctx_read(path, mode)` with appropriate mode from table above
914. **Edit:** `ctx_edit(path, old_string, new_string)` or native Edit if available
925. **Verify:** `ctx_read(path, "diff")` + `ctx_shell("test command")`
936. **Record:** `ctx_knowledge(action="remember", content="...")` for non-obvious findings
94
95## Proactive (use without being asked)
96- `ctx_overview(task)` — at session start for orientation
97- `ctx_compress` — when context grows large (at phase boundaries)
98- `ctx_knowledge(action="wakeup")` — at session start to surface prior findings
99
100## Compression Bypass (only when compressed output hides needed detail)
101`ctx_read(path, "lines:N-M")` → `ctx_read(path, "full")` → `ctx_shell(cmd, raw=true)`
102Return to compressed defaults after one expanded retrieval.
103
104## Risk Gate (before high-impact edits)
105Before editing exported symbols, auth, DB schemas, or 3+ files: run `ctx_impact(action="analyze")`
106and `ctx_callgraph(action="callers")` to confirm blast radius.
107
108## Session
109- **Start:** `ctx_session(action="status")` + `ctx_knowledge(action="wakeup")`
110- **End:** `ctx_session(action="decision", content="what was done + next steps")`
111- **On [CHECKPOINT]:** `ctx_session(action="task", value="current status")`
112
113NEVER use native Read/Grep/Shell when ctx_* equivalents are available.
114<!-- /lean-ctx -->"#;
115
116const RULES_CURSOR_MDC: &str = include_str!("templates/lean-ctx.mdc");
120
121struct RulesTarget {
124 name: &'static str,
125 path: PathBuf,
126 format: RulesFormat,
127}
128
129enum RulesFormat {
130 SharedMarkdown,
131 DedicatedMarkdown,
132 CursorMdc,
133}
134
135#[derive(Debug, Default)]
136pub struct InjectResult {
137 pub injected: Vec<String>,
138 pub updated: Vec<String>,
139 pub already: Vec<String>,
140 pub errors: Vec<String>,
141 pub backed_up: Vec<String>,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct RulesTargetStatus {
146 pub name: String,
147 pub detected: bool,
148 pub path: String,
149 pub state: String,
150 pub note: Option<String>,
151}
152
153pub fn inject_all_rules(home: &std::path::Path) -> InjectResult {
154 if crate::core::config::Config::load().rules_scope_effective()
155 == crate::core::config::RulesScope::Project
156 {
157 return InjectResult::default();
158 }
159
160 let targets = build_rules_targets(home);
161
162 let mut result = InjectResult::default();
163
164 for target in &targets {
165 if !is_tool_detected(target, home) {
166 continue;
167 }
168
169 let bak_path = target.path.with_extension(format!(
170 "{}.bak",
171 target
172 .path
173 .extension()
174 .and_then(|e| e.to_str())
175 .unwrap_or("")
176 ));
177 let bak_existed_before = bak_path.exists();
178 let bak_mtime_before = bak_existed_before
179 .then(|| {
180 std::fs::metadata(&bak_path)
181 .ok()
182 .and_then(|m| m.modified().ok())
183 })
184 .flatten();
185
186 match inject_rules(target) {
187 Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
188 Ok(RulesResult::Updated) => {
189 result.updated.push(target.name.to_string());
190 let bak_is_new = if bak_existed_before {
191 std::fs::metadata(&bak_path)
192 .ok()
193 .and_then(|m| m.modified().ok())
194 != bak_mtime_before
195 } else {
196 bak_path.exists()
197 };
198 if bak_is_new {
199 result
200 .backed_up
201 .push(bak_path.to_string_lossy().to_string());
202 }
203 }
204 Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
205 Err(e) => result.errors.push(format!("{}: {e}", target.name)),
206 }
207 }
208
209 result
210}
211
212pub fn inject_rules_for_agent(home: &std::path::Path, agent_key: &str) -> InjectResult {
215 if crate::core::config::Config::load().rules_scope_effective()
216 == crate::core::config::RulesScope::Project
217 {
218 return InjectResult::default();
219 }
220
221 let targets = build_rules_targets(home);
222 let mut result = InjectResult::default();
223
224 for target in &targets {
225 if !match_agent_name(agent_key, target.name) {
226 continue;
227 }
228
229 let bak_path = target.path.with_extension(format!(
230 "{}.bak",
231 target
232 .path
233 .extension()
234 .and_then(|e| e.to_str())
235 .unwrap_or("")
236 ));
237 let bak_existed_before = bak_path.exists();
238
239 match inject_rules(target) {
240 Ok(RulesResult::Injected) => result.injected.push(target.name.to_string()),
241 Ok(RulesResult::Updated) => {
242 result.updated.push(target.name.to_string());
243 if !bak_existed_before && bak_path.exists() {
244 result
245 .backed_up
246 .push(bak_path.to_string_lossy().to_string());
247 }
248 }
249 Ok(RulesResult::AlreadyPresent) => result.already.push(target.name.to_string()),
250 Err(e) => result.errors.push(format!("{}: {e}", target.name)),
251 }
252 }
253
254 result
255}
256
257fn match_agent_name(cli_key: &str, target_name: &str) -> bool {
258 let needle = cli_key.to_lowercase();
259 let tn = target_name.to_lowercase();
260 needle.contains(&tn)
261 || tn.contains(&needle)
262 || (needle.contains("cursor") && tn.contains("cursor"))
263 || (needle.contains("claude") && tn.contains("claude"))
264 || (needle.contains("windsurf") && tn.contains("windsurf"))
265 || (needle.contains("codex") && tn.contains("claude"))
266 || (needle.contains("zed") && tn.contains("zed"))
267 || (needle.contains("copilot") && tn.contains("copilot"))
268 || (needle.contains("jetbrains") && tn.contains("jetbrains"))
269 || (needle.contains("kiro") && tn.contains("kiro"))
270 || (needle.contains("gemini") && tn.contains("gemini"))
271 || (needle == "opencode" && tn.contains("opencode"))
272 || (needle == "cline" && tn.contains("cline"))
273 || (needle == "roo" && tn.contains("roo"))
274 || (needle == "amp" && tn.contains("amp"))
275 || (needle == "trae" && tn.contains("trae"))
276 || (needle == "amazonq" && tn.contains("amazon"))
277 || (needle == "pi" && tn.contains("pi coding"))
278 || (needle == "crush" && tn.contains("crush"))
279 || (needle == "verdent" && tn.contains("verdent"))
280 || (needle == "continue" && tn.contains("continue"))
281 || (needle == "qwen" && tn.contains("qwen"))
282 || (needle == "antigravity" && tn.contains("antigravity"))
283 || (needle == "augment" && tn.contains("augment"))
284 || (needle == "openclaw" && tn.contains("openclaw"))
285 || (needle == "vscode" && (tn.contains("vs code") || tn.contains("vscode")))
286}
287
288pub fn check_rules_freshness(client_name: &str) -> Option<String> {
291 let home = dirs::home_dir()?;
292 let targets = build_rules_targets(&home);
293
294 let matched: Vec<&RulesTarget> = targets
295 .iter()
296 .filter(|t| match_agent_name(client_name, t.name))
297 .collect();
298
299 if matched.is_empty() {
300 return None;
301 }
302
303 for target in &matched {
304 if !target.path.exists() {
305 continue;
306 }
307 let content = std::fs::read_to_string(&target.path).ok()?;
308 if content.contains(MARKER) && !content.contains(RULES_VERSION) {
309 return Some(format!(
310 "[RULES OUTDATED] Your {} rules were written by an older lean-ctx version. \
311 Re-read your rules file ({}) or run `lean-ctx setup` to update, \
312 then start a new session for full compatibility.",
313 target.name,
314 target.path.display()
315 ));
316 }
317 }
318
319 None
320}
321
322pub fn collect_rules_status(home: &std::path::Path) -> Vec<RulesTargetStatus> {
323 let targets = build_rules_targets(home);
324 let mut out = Vec::new();
325
326 for target in &targets {
327 let detected = is_tool_detected(target, home);
328 let path = target.path.to_string_lossy().to_string();
329
330 let state = if !detected {
331 "not_detected".to_string()
332 } else if !target.path.exists() {
333 "missing".to_string()
334 } else {
335 match std::fs::read_to_string(&target.path) {
336 Ok(content) => {
337 if content.contains(MARKER) {
338 if content.contains(RULES_VERSION) {
339 "up_to_date".to_string()
340 } else {
341 "outdated".to_string()
342 }
343 } else {
344 "present_without_marker".to_string()
345 }
346 }
347 Err(_) => "read_error".to_string(),
348 }
349 };
350
351 out.push(RulesTargetStatus {
352 name: target.name.to_string(),
353 detected,
354 path,
355 state,
356 note: None,
357 });
358 }
359
360 out
361}
362
363enum RulesResult {
368 Injected,
369 Updated,
370 AlreadyPresent,
371}
372
373fn rules_content(format: &RulesFormat) -> &'static str {
374 match format {
375 RulesFormat::SharedMarkdown => RULES_SHARED,
376 RulesFormat::DedicatedMarkdown => RULES_DEDICATED,
377 RulesFormat::CursorMdc => RULES_CURSOR_MDC,
378 }
379}
380
381fn inject_rules(target: &RulesTarget) -> Result<RulesResult, String> {
382 if target.path.exists() {
383 let content = std::fs::read_to_string(&target.path).map_err(|e| e.to_string())?;
384 if content.contains(MARKER) {
385 if content.contains(RULES_VERSION) {
386 return Ok(RulesResult::AlreadyPresent);
387 }
388 ensure_parent(&target.path)?;
389 return match target.format {
390 RulesFormat::SharedMarkdown => replace_markdown_section(&target.path, &content),
391 RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
392 write_dedicated(&target.path, rules_content(&target.format))
393 }
394 };
395 }
396 }
397
398 ensure_parent(&target.path)?;
399
400 match target.format {
401 RulesFormat::SharedMarkdown => append_to_shared(&target.path),
402 RulesFormat::DedicatedMarkdown | RulesFormat::CursorMdc => {
403 write_dedicated(&target.path, rules_content(&target.format))
404 }
405 }
406}
407
408fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
409 if let Some(parent) = path.parent() {
410 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
411 }
412 Ok(())
413}
414
415fn append_to_shared(path: &std::path::Path) -> Result<RulesResult, String> {
416 let mut content = if path.exists() {
417 std::fs::read_to_string(path).map_err(|e| e.to_string())?
418 } else {
419 String::new()
420 };
421
422 if !content.is_empty() && !content.ends_with('\n') {
423 content.push('\n');
424 }
425 if !content.is_empty() {
426 content.push('\n');
427 }
428 content.push_str(RULES_SHARED);
429 content.push('\n');
430
431 crate::config_io::write_atomic_with_backup(path, &content)?;
432 Ok(RulesResult::Injected)
433}
434
435fn replace_markdown_section(path: &std::path::Path, content: &str) -> Result<RulesResult, String> {
436 let start = content.find(MARKER);
437 let end = content.find(END_MARKER);
438
439 let new_content = match (start, end) {
440 (Some(s), Some(e)) => {
441 let before = &content[..s];
442 let after_end = e + END_MARKER.len();
443 let after = content[after_end..].trim_start_matches('\n');
444 let mut result = before.to_string();
445 result.push_str(RULES_SHARED);
446 if !after.is_empty() {
447 result.push('\n');
448 result.push_str(after);
449 }
450 result
451 }
452 (Some(s), None) => {
453 let before = &content[..s];
454 let mut result = before.to_string();
455 result.push_str(RULES_SHARED);
456 result.push('\n');
457 result
458 }
459 _ => return Ok(RulesResult::AlreadyPresent),
460 };
461
462 crate::config_io::write_atomic_with_backup(path, &new_content)?;
463 Ok(RulesResult::Updated)
464}
465
466fn write_dedicated(path: &std::path::Path, content: &'static str) -> Result<RulesResult, String> {
467 if !path.exists() {
468 crate::config_io::write_atomic_with_backup(path, content)?;
469 return Ok(RulesResult::Injected);
470 }
471
472 let existing = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
473 if !existing.contains(MARKER) {
474 crate::config_io::write_atomic_with_backup(path, content)?;
475 return Ok(RulesResult::Injected);
476 }
477
478 let start = existing.find(MARKER);
479 let end = existing.find(END_MARKER);
480
481 let (before, after) = match (start, end) {
482 (Some(s), Some(e)) => {
483 let before = &existing[..s];
484 let after_end = e + END_MARKER.len();
485 let after = existing[after_end..].trim_start_matches('\n');
486 (before.to_string(), after.to_string())
487 }
488 (Some(s), None) => (existing[..s].to_string(), String::new()),
489 _ => (String::new(), String::new()),
490 };
491
492 let has_user_content = !before.trim().is_empty() || !after.trim().is_empty();
493
494 if has_user_content {
495 let new_section = if let Some(marker_pos) = content.find(MARKER) {
496 &content[marker_pos..]
497 } else {
498 content
499 };
500
501 let mut result = before.clone();
502 result.push_str(new_section);
503 if !after.is_empty() {
504 if !result.ends_with('\n') {
505 result.push('\n');
506 }
507 result.push_str(&after);
508 }
509 if !result.ends_with('\n') {
510 result.push('\n');
511 }
512 crate::config_io::write_atomic_with_backup(path, &result)?;
513 } else {
514 crate::config_io::write_atomic_with_backup(path, content)?;
515 }
516
517 Ok(RulesResult::Updated)
518}
519
520fn is_tool_detected(target: &RulesTarget, home: &std::path::Path) -> bool {
525 match target.name {
526 "Claude Code" => {
527 if command_exists("claude") {
528 return true;
529 }
530 let state_dir = crate::core::editor_registry::claude_state_dir(home);
531 crate::core::editor_registry::claude_mcp_json_path(home).exists() || state_dir.exists()
532 }
533 "Codex CLI" => {
534 let codex_dir =
535 crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
536 codex_dir.exists() || command_exists("codex")
537 }
538 "Cursor" => home.join(".cursor").exists(),
539 "Windsurf" => home.join(".codeium/windsurf").exists(),
540 "Gemini CLI" => home.join(".gemini").exists(),
541 "VS Code" => detect_vscode_installed(home),
542 "Copilot CLI" => home.join(".copilot").exists() || command_exists("copilot"),
543 "Zed" => crate::core::editor_registry::zed_config_dir(home).exists(),
544 "Cline" => detect_extension_installed(home, "saoudrizwan.claude-dev"),
545 "Roo Code" => detect_extension_installed(home, "rooveterinaryinc.roo-cline"),
546 "OpenCode" => home.join(".config/opencode").exists(),
547 "Continue" => detect_extension_installed(home, "continue.continue"),
548 "Amp" => command_exists("amp") || home.join(".ampcoder").exists(),
549 "Qwen Code" => home.join(".qwen").exists(),
550 "Trae" => home.join(".trae").exists(),
551 "Amazon Q Developer" => home.join(".aws/amazonq").exists(),
552 "JetBrains IDEs" => detect_jetbrains_installed(home),
553 "Antigravity" => home.join(".gemini/antigravity").exists(),
554 "Pi Coding Agent" => home.join(".pi").exists() || command_exists("pi"),
555 "AWS Kiro" => home.join(".kiro").exists(),
556 "Crush" => home.join(".config/crush").exists() || command_exists("crush"),
557 "Verdent" => home.join(".verdent").exists(),
558 "Augment" => {
561 command_exists("auggie")
562 || home.join(".augment").exists()
563 || detect_extension_installed(home, "augment.vscode-augment")
564 }
565 _ => false,
566 }
567}
568
569fn command_exists(name: &str) -> bool {
570 #[cfg(target_os = "windows")]
571 let result = std::process::Command::new("where")
572 .arg(name)
573 .output()
574 .is_ok_and(|o| o.status.success());
575
576 #[cfg(not(target_os = "windows"))]
577 let result = std::process::Command::new("which")
578 .arg(name)
579 .output()
580 .is_ok_and(|o| o.status.success());
581
582 result
583}
584
585fn detect_vscode_installed(_home: &std::path::Path) -> bool {
586 let check_dir = |dir: PathBuf| -> bool {
587 dir.join("settings.json").exists() || dir.join("mcp.json").exists()
588 };
589
590 #[cfg(target_os = "macos")]
591 if check_dir(_home.join("Library/Application Support/Code/User")) {
592 return true;
593 }
594 #[cfg(target_os = "linux")]
595 if check_dir(_home.join(".config/Code/User")) {
596 return true;
597 }
598 #[cfg(target_os = "windows")]
599 if let Ok(appdata) = std::env::var("APPDATA") {
600 if check_dir(PathBuf::from(&appdata).join("Code/User")) {
601 return true;
602 }
603 }
604 false
605}
606
607fn detect_jetbrains_installed(home: &std::path::Path) -> bool {
608 #[cfg(target_os = "macos")]
609 if home.join("Library/Application Support/JetBrains").exists() {
610 return true;
611 }
612 #[cfg(target_os = "linux")]
613 if home.join(".config/JetBrains").exists() {
614 return true;
615 }
616 home.join(".jb-mcp.json").exists()
617}
618
619fn detect_extension_installed(_home: &std::path::Path, extension_id: &str) -> bool {
620 #[cfg(target_os = "macos")]
621 {
622 if _home
623 .join(format!(
624 "Library/Application Support/Code/User/globalStorage/{extension_id}"
625 ))
626 .exists()
627 {
628 return true;
629 }
630 }
631 #[cfg(target_os = "linux")]
632 {
633 if _home
634 .join(format!(".config/Code/User/globalStorage/{extension_id}"))
635 .exists()
636 {
637 return true;
638 }
639 }
640 #[cfg(target_os = "windows")]
641 {
642 if let Ok(appdata) = std::env::var("APPDATA") {
643 if std::path::PathBuf::from(&appdata)
644 .join(format!("Code/User/globalStorage/{extension_id}"))
645 .exists()
646 {
647 return true;
648 }
649 }
650 }
651 false
652}
653
654fn build_rules_targets(home: &std::path::Path) -> Vec<RulesTarget> {
659 vec![
660 RulesTarget {
662 name: "Claude Code",
663 path: crate::core::editor_registry::claude_rules_dir(home).join("lean-ctx.md"),
664 format: RulesFormat::DedicatedMarkdown,
665 },
666 RulesTarget {
667 name: "Gemini CLI",
668 path: home.join(".gemini/GEMINI.md"),
669 format: RulesFormat::SharedMarkdown,
670 },
671 RulesTarget {
672 name: "VS Code",
673 path: copilot_instructions_path(home),
674 format: RulesFormat::SharedMarkdown,
675 },
676 RulesTarget {
677 name: "Copilot CLI",
678 path: home.join(".copilot/instructions.md"),
679 format: RulesFormat::SharedMarkdown,
680 },
681 RulesTarget {
683 name: "Cursor",
684 path: home.join(".cursor/rules/lean-ctx.mdc"),
685 format: RulesFormat::CursorMdc,
686 },
687 RulesTarget {
688 name: "Windsurf",
689 path: home.join(".codeium/windsurf/rules/lean-ctx.md"),
690 format: RulesFormat::DedicatedMarkdown,
691 },
692 RulesTarget {
693 name: "Zed",
694 path: crate::core::editor_registry::zed_config_dir(home).join("rules/lean-ctx.md"),
697 format: RulesFormat::DedicatedMarkdown,
698 },
699 RulesTarget {
700 name: "Cline",
701 path: home.join(".cline/rules/lean-ctx.md"),
702 format: RulesFormat::DedicatedMarkdown,
703 },
704 RulesTarget {
705 name: "Roo Code",
706 path: home.join(".roo/rules/lean-ctx.md"),
707 format: RulesFormat::DedicatedMarkdown,
708 },
709 RulesTarget {
710 name: "OpenCode",
711 path: home.join(".config/opencode/AGENTS.md"),
712 format: RulesFormat::SharedMarkdown,
713 },
714 RulesTarget {
715 name: "Continue",
716 path: home.join(".continue/rules/lean-ctx.md"),
717 format: RulesFormat::DedicatedMarkdown,
718 },
719 RulesTarget {
720 name: "Amp",
721 path: home.join(".ampcoder/rules/lean-ctx.md"),
722 format: RulesFormat::DedicatedMarkdown,
723 },
724 RulesTarget {
725 name: "Qwen Code",
726 path: home.join(".qwen/rules/lean-ctx.md"),
727 format: RulesFormat::DedicatedMarkdown,
728 },
729 RulesTarget {
730 name: "Trae",
731 path: home.join(".trae/rules/lean-ctx.md"),
732 format: RulesFormat::DedicatedMarkdown,
733 },
734 RulesTarget {
735 name: "Amazon Q Developer",
736 path: home.join(".aws/amazonq/rules/lean-ctx.md"),
737 format: RulesFormat::DedicatedMarkdown,
738 },
739 RulesTarget {
740 name: "JetBrains IDEs",
741 path: home.join(".jb-rules/lean-ctx.md"),
742 format: RulesFormat::DedicatedMarkdown,
743 },
744 RulesTarget {
745 name: "Antigravity",
746 path: home.join(".gemini/antigravity/rules/lean-ctx.md"),
747 format: RulesFormat::DedicatedMarkdown,
748 },
749 RulesTarget {
750 name: "Pi Coding Agent",
751 path: home.join(".pi/rules/lean-ctx.md"),
752 format: RulesFormat::DedicatedMarkdown,
753 },
754 RulesTarget {
755 name: "AWS Kiro",
756 path: home.join(".kiro/steering/lean-ctx.md"),
757 format: RulesFormat::DedicatedMarkdown,
758 },
759 RulesTarget {
760 name: "Verdent",
761 path: home.join(".verdent/rules/lean-ctx.md"),
762 format: RulesFormat::DedicatedMarkdown,
763 },
764 RulesTarget {
765 name: "Crush",
766 path: home.join(".config/crush/rules/lean-ctx.md"),
767 format: RulesFormat::DedicatedMarkdown,
768 },
769 RulesTarget {
770 name: "Augment",
771 path: home.join(".augment/rules/lean-ctx.md"),
772 format: RulesFormat::DedicatedMarkdown,
773 },
774 RulesTarget {
775 name: "OpenClaw",
776 path: home.join(".openclaw/rules/lean-ctx.md"),
777 format: RulesFormat::DedicatedMarkdown,
778 },
779 ]
780}
781
782fn copilot_instructions_path(home: &std::path::Path) -> PathBuf {
783 #[cfg(target_os = "macos")]
784 {
785 return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
786 }
787 #[cfg(target_os = "linux")]
788 {
789 return home.join(".config/Code/User/github-copilot-instructions.md");
790 }
791 #[cfg(target_os = "windows")]
792 {
793 if let Ok(appdata) = std::env::var("APPDATA") {
794 return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
795 }
796 }
797 #[allow(unreachable_code)]
798 home.join(".config/Code/User/github-copilot-instructions.md")
799}
800
801const SKILL_TEMPLATE: &str = include_str!("templates/SKILL.md");
806
807struct SkillTarget {
808 agent_key: &'static str,
809 display_name: &'static str,
810 skill_dir: PathBuf,
811}
812
813fn build_skill_targets(home: &std::path::Path) -> Vec<SkillTarget> {
814 vec![
815 SkillTarget {
816 agent_key: "claude",
817 display_name: "Claude Code",
818 skill_dir: crate::setup::claude_config_dir(home).join("skills/lean-ctx"),
819 },
820 SkillTarget {
821 agent_key: "cursor",
822 display_name: "Cursor",
823 skill_dir: home.join(".cursor/skills/lean-ctx"),
824 },
825 SkillTarget {
826 agent_key: "codex",
827 display_name: "Codex CLI",
828 skill_dir: crate::core::home::resolve_codex_dir()
829 .unwrap_or_else(|| home.join(".codex"))
830 .join("skills/lean-ctx"),
831 },
832 SkillTarget {
833 agent_key: "copilot",
834 display_name: "GitHub Copilot",
835 skill_dir: home.join(".copilot/skills/lean-ctx"),
836 },
837 SkillTarget {
838 agent_key: "openclaw",
839 display_name: "OpenClaw",
840 skill_dir: home.join(".openclaw/skills/lean-ctx"),
841 },
842 ]
843}
844
845fn is_skill_agent_detected(agent_key: &str, home: &std::path::Path) -> bool {
846 match agent_key {
847 "claude" => {
848 command_exists("claude")
849 || crate::core::editor_registry::claude_mcp_json_path(home).exists()
850 || crate::core::editor_registry::claude_state_dir(home).exists()
851 }
852 "cursor" => home.join(".cursor").exists(),
853 "codex" => {
854 let codex_dir =
855 crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
856 codex_dir.exists() || command_exists("codex")
857 }
858 "copilot" => {
859 home.join(".copilot").exists()
860 || home.join(".copilot/mcp-config.json").exists()
861 || command_exists("copilot")
862 }
863 "openclaw" => home.join(".openclaw").exists() || command_exists("openclaw"),
864 _ => false,
865 }
866}
867
868pub fn install_skill_for_agent(home: &std::path::Path, agent_key: &str) -> Result<PathBuf, String> {
870 let targets = build_skill_targets(home);
871 let target = targets
872 .into_iter()
873 .find(|t| t.agent_key == agent_key)
874 .ok_or_else(|| format!("No skill target for agent '{agent_key}'"))?;
875
876 let skill_path = target.skill_dir.join("SKILL.md");
877 std::fs::create_dir_all(&target.skill_dir).map_err(|e| e.to_string())?;
878
879 if skill_path.exists() {
880 let existing = std::fs::read_to_string(&skill_path).unwrap_or_default();
881 if existing == SKILL_TEMPLATE {
882 return Ok(skill_path);
883 }
884 }
885
886 crate::config_io::write_atomic_with_backup(&skill_path, SKILL_TEMPLATE)?;
887 Ok(skill_path)
888}
889
890pub fn install_all_skills(home: &std::path::Path) -> Vec<(String, bool)> {
893 let targets = build_skill_targets(home);
894 let mut results = Vec::new();
895
896 for target in &targets {
897 if !is_skill_agent_detected(target.agent_key, home) {
898 continue;
899 }
900
901 let skill_path = target.skill_dir.join("SKILL.md");
902 let already_current = skill_path.exists()
903 && std::fs::read_to_string(&skill_path).is_ok_and(|c| c == SKILL_TEMPLATE);
904
905 if already_current {
906 results.push((target.display_name.to_string(), false));
907 continue;
908 }
909
910 if let Err(e) = std::fs::create_dir_all(&target.skill_dir) {
911 tracing::warn!(
912 "Failed to create skill dir for {}: {e}",
913 target.display_name
914 );
915 continue;
916 }
917
918 match crate::config_io::write_atomic_with_backup(&skill_path, SKILL_TEMPLATE) {
919 Ok(()) => results.push((target.display_name.to_string(), true)),
920 Err(e) => {
921 tracing::warn!("Failed to write SKILL.md for {}: {e}", target.display_name);
922 }
923 }
924 }
925
926 results
927}
928
929#[cfg(test)]
934mod tests {
935 use super::*;
936
937 #[test]
938 fn shared_rules_have_markers() {
939 assert!(RULES_SHARED.contains(MARKER));
940 assert!(RULES_SHARED.contains(END_MARKER));
941 assert!(RULES_SHARED.contains(RULES_VERSION));
942 }
943
944 #[test]
945 fn zed_rules_path_is_os_aware_and_matches_config_dir() {
946 let home = std::path::Path::new("/home/tester");
950 let zed = build_rules_targets(home)
951 .into_iter()
952 .find(|t| t.name == "Zed")
953 .expect("Zed rules target must exist");
954 let expected = crate::core::editor_registry::zed_config_dir(home).join("rules/lean-ctx.md");
955 assert_eq!(zed.path, expected);
956 }
957
958 #[test]
959 fn dedicated_rules_have_markers() {
960 assert!(RULES_DEDICATED.contains(MARKER));
961 assert!(RULES_DEDICATED.contains(END_MARKER));
962 assert!(RULES_DEDICATED.contains(RULES_VERSION));
963 }
964
965 #[test]
966 fn cursor_mdc_has_markers_and_frontmatter() {
967 assert!(RULES_CURSOR_MDC.contains("lean-ctx"));
968 assert!(RULES_CURSOR_MDC.contains(END_MARKER));
969 assert!(RULES_CURSOR_MDC.contains(RULES_VERSION));
970 assert!(RULES_CURSOR_MDC.contains("alwaysApply: true"));
971 }
972
973 #[test]
974 fn shared_rules_contain_mode_selection() {
975 assert!(RULES_SHARED.contains("Mode Selection"));
976 assert!(RULES_SHARED.contains("full"));
977 assert!(RULES_SHARED.contains("map"));
978 assert!(RULES_SHARED.contains("signatures"));
979 assert!(RULES_SHARED.contains("NEVER"));
980 }
981
982 #[test]
983 fn shared_rules_has_never_native() {
984 assert!(RULES_SHARED.contains("NEVER use native"));
985 assert!(RULES_SHARED.contains("ctx_read"));
986 }
987
988 #[test]
989 fn dedicated_rules_contain_modes() {
990 assert!(RULES_DEDICATED.contains("auto"));
991 assert!(RULES_DEDICATED.contains("full"));
992 assert!(RULES_DEDICATED.contains("map"));
993 assert!(RULES_DEDICATED.contains("signatures"));
994 assert!(RULES_DEDICATED.contains("lines:N-M"));
995 assert!(RULES_DEDICATED.contains("diff"));
996 }
997
998 #[test]
999 fn dedicated_rules_has_proactive_section() {
1000 assert!(RULES_DEDICATED.contains("Proactive"));
1001 assert!(RULES_DEDICATED.contains("ctx_overview"));
1002 assert!(RULES_DEDICATED.contains("ctx_compress"));
1003 }
1004
1005 #[test]
1006 fn cursor_mdc_contains_tool_mapping() {
1007 assert!(RULES_CURSOR_MDC.contains("Tool Mapping"));
1008 assert!(RULES_CURSOR_MDC.contains("ctx_read"));
1009 assert!(RULES_CURSOR_MDC.contains("ctx_search"));
1010 assert!(RULES_CURSOR_MDC.contains("Workflow"));
1011 }
1012
1013 fn ensure_temp_dir() {
1014 let tmp = std::env::temp_dir();
1015 if !tmp.exists() {
1016 std::fs::create_dir_all(&tmp).ok();
1017 }
1018 }
1019
1020 #[test]
1021 fn replace_section_with_end_marker() {
1022 ensure_temp_dir();
1023 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";
1024 let path = std::env::temp_dir().join("test_replace_with_end.md");
1025 std::fs::write(&path, old).unwrap();
1026
1027 let result = replace_markdown_section(&path, old).unwrap();
1028 assert!(matches!(result, RulesResult::Updated));
1029
1030 let new_content = std::fs::read_to_string(&path).unwrap();
1031 assert!(new_content.contains(RULES_VERSION));
1032 assert!(new_content.starts_with("user stuff"));
1033 assert!(new_content.contains("more user stuff"));
1034 assert!(!new_content.contains("lean-ctx-rules-v2"));
1035
1036 std::fs::remove_file(&path).ok();
1037 }
1038
1039 #[test]
1040 fn replace_section_without_end_marker() {
1041 ensure_temp_dir();
1042 let old = "user stuff\n\n# lean-ctx — Context Engineering Layer\nold rules only\n";
1043 let path = std::env::temp_dir().join("test_replace_no_end.md");
1044 std::fs::write(&path, old).unwrap();
1045
1046 let result = replace_markdown_section(&path, old).unwrap();
1047 assert!(matches!(result, RulesResult::Updated));
1048
1049 let new_content = std::fs::read_to_string(&path).unwrap();
1050 assert!(new_content.contains(RULES_VERSION));
1051 assert!(new_content.starts_with("user stuff"));
1052
1053 std::fs::remove_file(&path).ok();
1054 }
1055
1056 #[test]
1057 fn append_to_shared_preserves_existing() {
1058 ensure_temp_dir();
1059 let path = std::env::temp_dir().join("test_append_shared.md");
1060 std::fs::write(&path, "existing user rules\n").unwrap();
1061
1062 let result = append_to_shared(&path).unwrap();
1063 assert!(matches!(result, RulesResult::Injected));
1064
1065 let content = std::fs::read_to_string(&path).unwrap();
1066 assert!(content.starts_with("existing user rules"));
1067 assert!(content.contains(MARKER));
1068 assert!(content.contains(END_MARKER));
1069
1070 std::fs::remove_file(&path).ok();
1071 }
1072
1073 #[test]
1074 fn write_dedicated_creates_file() {
1075 ensure_temp_dir();
1076 let path = std::env::temp_dir().join("test_write_dedicated.md");
1077 if path.exists() {
1078 std::fs::remove_file(&path).ok();
1079 }
1080
1081 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
1082 assert!(matches!(result, RulesResult::Injected));
1083
1084 let content = std::fs::read_to_string(&path).unwrap();
1085 assert!(content.contains(MARKER));
1086 assert!(content.contains("Mode Selection"));
1087
1088 std::fs::remove_file(&path).ok();
1089 }
1090
1091 #[test]
1092 fn write_dedicated_updates_existing() {
1093 ensure_temp_dir();
1094 let path = std::env::temp_dir().join("test_write_dedicated_update.md");
1095 std::fs::write(&path, "# lean-ctx — Context Engineering Layer\nold version").unwrap();
1096
1097 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
1098 assert!(matches!(result, RulesResult::Updated));
1099
1100 std::fs::remove_file(&path).ok();
1101 }
1102
1103 #[test]
1104 fn target_count() {
1105 let home = std::path::PathBuf::from("/tmp/fake_home");
1106 let targets = build_rules_targets(&home);
1107 assert_eq!(targets.len(), 23);
1108 }
1109
1110 #[test]
1111 fn skill_template_not_empty() {
1112 assert!(!SKILL_TEMPLATE.is_empty());
1113 assert!(SKILL_TEMPLATE.contains("lean-ctx"));
1114 }
1115
1116 #[test]
1117 fn skill_targets_count() {
1118 let home = std::path::PathBuf::from("/tmp/fake_home");
1119 let targets = build_skill_targets(&home);
1120 assert_eq!(targets.len(), 5);
1121 }
1122
1123 #[test]
1124 fn install_skill_creates_file() {
1125 ensure_temp_dir();
1126 let home = std::env::temp_dir().join("test_skill_install");
1127 let _ = std::fs::create_dir_all(&home);
1128
1129 let fake_cursor = home.join(".cursor");
1130 let _ = std::fs::create_dir_all(&fake_cursor);
1131
1132 let result = install_skill_for_agent(&home, "cursor");
1133 assert!(result.is_ok());
1134
1135 let path = result.unwrap();
1136 assert!(path.exists());
1137 let content = std::fs::read_to_string(&path).unwrap();
1138 assert_eq!(content, SKILL_TEMPLATE);
1139
1140 let _ = std::fs::remove_dir_all(&home);
1141 }
1142
1143 #[test]
1144 fn install_skill_idempotent() {
1145 ensure_temp_dir();
1146 let home = std::env::temp_dir().join("test_skill_idempotent");
1147 let _ = std::fs::create_dir_all(&home);
1148
1149 let fake_cursor = home.join(".cursor");
1150 let _ = std::fs::create_dir_all(&fake_cursor);
1151
1152 let p1 = install_skill_for_agent(&home, "cursor").unwrap();
1153 let p2 = install_skill_for_agent(&home, "cursor").unwrap();
1154 assert_eq!(p1, p2);
1155
1156 let _ = std::fs::remove_dir_all(&home);
1157 }
1158
1159 #[test]
1160 fn install_skill_unknown_agent() {
1161 let home = std::path::PathBuf::from("/tmp/fake_home");
1162 let result = install_skill_for_agent(&home, "unknown_agent");
1163 assert!(result.is_err());
1164 }
1165
1166 #[test]
1167 fn match_agent_name_basic() {
1168 assert!(match_agent_name("cursor", "Cursor"));
1169 assert!(match_agent_name("opencode", "OpenCode"));
1170 assert!(match_agent_name("claude", "Claude Code"));
1171 assert!(match_agent_name("vscode", "VS Code"));
1172 assert!(match_agent_name("copilot", "Copilot CLI"));
1173 assert!(match_agent_name("kiro", "AWS Kiro"));
1174 assert!(match_agent_name("pi", "Pi Coding Agent"));
1175 assert!(match_agent_name("crush", "Crush"));
1176 assert!(match_agent_name("amp", "Amp"));
1177 assert!(match_agent_name("cline", "Cline"));
1178 assert!(match_agent_name("roo", "Roo Code"));
1179 assert!(match_agent_name("trae", "Trae"));
1180 assert!(match_agent_name("amazonq", "Amazon Q Developer"));
1181 assert!(match_agent_name("verdent", "Verdent"));
1182 assert!(match_agent_name("continue", "Continue"));
1183 assert!(match_agent_name("antigravity", "Antigravity"));
1184 assert!(match_agent_name("gemini", "Gemini CLI"));
1185 assert!(match_agent_name("augment", "Augment"));
1186 assert!(match_agent_name("openclaw", "OpenClaw"));
1187 }
1188
1189 #[test]
1190 fn match_agent_name_no_false_positives() {
1191 assert!(!match_agent_name("cursor", "Claude Code"));
1192 assert!(!match_agent_name("opencode", "Cursor"));
1193 assert!(!match_agent_name("unknown_agent", "Cursor"));
1194 }
1195
1196 #[test]
1197 fn inject_rules_for_agent_opencode() {
1198 ensure_temp_dir();
1199 let home = std::env::temp_dir().join("test_inject_rules_agent");
1200 let _ = std::fs::remove_dir_all(&home);
1201 let _ = std::fs::create_dir_all(&home);
1202
1203 let opencode_dir = home.join(".config/opencode");
1204 let _ = std::fs::create_dir_all(&opencode_dir);
1205
1206 let result = inject_rules_for_agent(&home, "opencode");
1207 assert!(
1208 !result.injected.is_empty() || !result.already.is_empty(),
1209 "should inject or find rules for OpenCode"
1210 );
1211 assert!(result.errors.is_empty(), "no errors expected");
1212
1213 let agents_md = opencode_dir.join("AGENTS.md");
1214 if agents_md.exists() {
1215 let content = std::fs::read_to_string(&agents_md).unwrap();
1216 assert!(content.contains(RULES_VERSION));
1217 }
1218
1219 let _ = std::fs::remove_dir_all(&home);
1220 }
1221
1222 #[test]
1223 fn inject_rules_for_agent_cursor() {
1224 ensure_temp_dir();
1225 let home = std::env::temp_dir().join("test_inject_rules_cursor");
1226 let _ = std::fs::remove_dir_all(&home);
1227 let _ = std::fs::create_dir_all(&home);
1228
1229 let cursor_dir = home.join(".cursor");
1230 let _ = std::fs::create_dir_all(&cursor_dir);
1231
1232 let result = inject_rules_for_agent(&home, "cursor");
1233 assert!(result.errors.is_empty(), "no errors expected");
1234
1235 let mdc_path = home.join(".cursor/rules/lean-ctx.mdc");
1236 if mdc_path.exists() {
1237 let content = std::fs::read_to_string(&mdc_path).unwrap();
1238 assert!(content.contains(RULES_VERSION));
1239 }
1240
1241 let _ = std::fs::remove_dir_all(&home);
1242 }
1243
1244 #[test]
1245 fn inject_rules_for_unknown_agent_is_empty() {
1246 let home = std::path::PathBuf::from("/tmp/fake_home_unknown");
1247 let result = inject_rules_for_agent(&home, "unknown_agent_xyz");
1248 assert!(result.injected.is_empty());
1249 assert!(result.updated.is_empty());
1250 assert!(result.already.is_empty());
1251 assert!(result.errors.is_empty());
1252 }
1253
1254 #[test]
1255 fn write_dedicated_preserves_user_content_before_marker() {
1256 ensure_temp_dir();
1257 let path = std::env::temp_dir().join("test_dedicated_preserve_before.md");
1258 let old = format!(
1259 "# My custom rules\nDo not delete this!\n\n{MARKER}\n<!-- lean-ctx-rules-v2 -->\nold content\n{END_MARKER}"
1260 );
1261 std::fs::write(&path, &old).unwrap();
1262
1263 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
1264 assert!(matches!(result, RulesResult::Updated));
1265
1266 let content = std::fs::read_to_string(&path).unwrap();
1267 assert!(
1268 content.contains("My custom rules"),
1269 "user content before marker must be preserved"
1270 );
1271 assert!(
1272 content.contains("Do not delete this!"),
1273 "user content before marker must be preserved"
1274 );
1275 assert!(
1276 content.contains(RULES_VERSION),
1277 "new rules version must be present"
1278 );
1279 assert!(
1280 !content.contains("lean-ctx-rules-v2"),
1281 "old version must be replaced"
1282 );
1283
1284 std::fs::remove_file(&path).ok();
1285 }
1286
1287 #[test]
1288 fn write_dedicated_preserves_user_content_after_marker() {
1289 ensure_temp_dir();
1290 let path = std::env::temp_dir().join("test_dedicated_preserve_after.md");
1291 let old = format!(
1292 "{MARKER}\n<!-- lean-ctx-rules-v2 -->\nold content\n{END_MARKER}\n\n# User's extra notes\nKeep this too!\n"
1293 );
1294 std::fs::write(&path, &old).unwrap();
1295
1296 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
1297 assert!(matches!(result, RulesResult::Updated));
1298
1299 let content = std::fs::read_to_string(&path).unwrap();
1300 assert!(
1301 content.contains("User's extra notes"),
1302 "user content after marker must be preserved"
1303 );
1304 assert!(
1305 content.contains("Keep this too!"),
1306 "user content after marker must be preserved"
1307 );
1308 assert!(
1309 content.contains(RULES_VERSION),
1310 "new rules version must be present"
1311 );
1312
1313 std::fs::remove_file(&path).ok();
1314 }
1315
1316 #[test]
1317 fn write_dedicated_preserves_content_both_sides() {
1318 ensure_temp_dir();
1319 let path = std::env::temp_dir().join("test_dedicated_preserve_both.md");
1320 let old = format!(
1321 "BEFORE CONTENT\n\n{MARKER}\n<!-- lean-ctx-rules-v2 -->\nold\n{END_MARKER}\n\nAFTER CONTENT\n"
1322 );
1323 std::fs::write(&path, &old).unwrap();
1324
1325 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
1326 assert!(matches!(result, RulesResult::Updated));
1327
1328 let content = std::fs::read_to_string(&path).unwrap();
1329 assert!(content.contains("BEFORE CONTENT"));
1330 assert!(content.contains("AFTER CONTENT"));
1331 assert!(content.contains(RULES_VERSION));
1332
1333 std::fs::remove_file(&path).ok();
1334 }
1335
1336 #[test]
1337 fn write_dedicated_no_user_content_uses_template_directly() {
1338 ensure_temp_dir();
1339 let path = std::env::temp_dir().join("test_dedicated_no_user.md");
1340 let old = format!("{MARKER}\n<!-- lean-ctx-rules-v2 -->\nold content\n{END_MARKER}");
1341 std::fs::write(&path, &old).unwrap();
1342
1343 let result = write_dedicated(&path, RULES_DEDICATED).unwrap();
1344 assert!(matches!(result, RulesResult::Updated));
1345
1346 let content = std::fs::read_to_string(&path).unwrap();
1347 assert_eq!(
1348 content, RULES_DEDICATED,
1349 "without user content, template should be written as-is"
1350 );
1351
1352 std::fs::remove_file(&path).ok();
1353 }
1354
1355 #[test]
1356 fn write_dedicated_preserves_mdc_frontmatter() {
1357 ensure_temp_dir();
1358 let path = std::env::temp_dir().join("test_dedicated_mdc_frontmatter.mdc");
1359 let old = format!(
1360 "---\ndescription: custom\nglobs: **/*\nalwaysApply: true\n---\n\nUser preamble here\n\n{MARKER}\n<!-- lean-ctx-rules-v2 -->\nold\n{END_MARKER}\n"
1361 );
1362 std::fs::write(&path, &old).unwrap();
1363
1364 let result = write_dedicated(&path, RULES_CURSOR_MDC).unwrap();
1365 assert!(matches!(result, RulesResult::Updated));
1366
1367 let content = std::fs::read_to_string(&path).unwrap();
1368 assert!(
1369 content.contains("User preamble here"),
1370 "user preamble must be preserved"
1371 );
1372 assert!(
1373 content.contains("custom"),
1374 "user frontmatter description must be preserved"
1375 );
1376 assert!(content.contains(RULES_VERSION));
1377
1378 std::fs::remove_file(&path).ok();
1379 }
1380
1381 #[test]
1382 fn inject_result_tracks_backed_up_files() {
1383 let result = InjectResult {
1384 backed_up: vec!["/tmp/test.md.bak".to_string()],
1385 ..Default::default()
1386 };
1387 assert_eq!(result.backed_up.len(), 1);
1388 assert!(std::path::Path::new(&result.backed_up[0])
1389 .extension()
1390 .is_some_and(|ext| ext.eq_ignore_ascii_case("bak")));
1391 }
1392}