1use std::path::{Path, PathBuf};
24
25use crate::core::rules_canonical::{END_MARK as BLOCK_END, START_MARK as BLOCK_START};
26use crate::core::rules_channel::{COMPRESSION_BLOCK_END, COMPRESSION_BLOCK_START};
27
28#[derive(Debug, PartialEq, Eq)]
30pub(crate) enum Action {
31 DeleteFile { path: PathBuf, reason: String },
33 StripBlocks { path: PathBuf, reason: String },
35 StripCompression { path: PathBuf, reason: String },
39 Report { path: PathBuf, note: String },
41}
42
43fn is_owned_rules_file(content: &str) -> bool {
47 let starts_with_header = content
48 .trim_start()
49 .starts_with(crate::core::rules_canonical::START_MARK)
50 || (content.trim_start().starts_with("---")
52 && content.contains(crate::core::rules_canonical::START_MARK));
53 if starts_with_header && content.contains("<!-- version:") {
54 return true;
55 }
56 is_owned_legacy_rules_file(content)
57}
58
59fn is_owned_legacy_rules_file(content: &str) -> bool {
68 let mut lines = content.trim_start().lines();
69 let first = lines.next().unwrap_or_default().trim();
73 let marker_line = if first.starts_with("# lean-ctx") {
74 lines.next().unwrap_or_default().trim()
75 } else {
76 first
77 };
78 if !marker_line.starts_with(crate::core::rules_canonical::RULES_MARKER_PREFIX) {
79 return false;
80 }
81 let Some(idx) = content.rfind("<!-- /lean-ctx") else {
82 return false;
83 };
84 let Some(end) = content[idx..].find("-->") else {
85 return false;
86 };
87 content[idx + end + 3..].trim().is_empty()
88}
89
90fn has_marker_pair(content: &str, start: &str, end: &str) -> bool {
93 crate::marked_block::contains_marker_line(content, start)
94 && crate::marked_block::contains_marker_line(content, end)
95}
96
97fn has_marked_block(content: &str) -> bool {
98 has_marker_pair(content, BLOCK_START, BLOCK_END)
99 || has_marker_pair(content, COMPRESSION_BLOCK_START, COMPRESSION_BLOCK_END)
100}
101
102pub(crate) fn strip_lean_ctx_blocks(content: &str) -> String {
104 let mut out = content.to_string();
105 loop {
108 let next = if has_marker_pair(&out, BLOCK_START, BLOCK_END) {
109 crate::marked_block::remove_content(&out, BLOCK_START, BLOCK_END)
110 } else if has_marker_pair(&out, COMPRESSION_BLOCK_START, COMPRESSION_BLOCK_END) {
111 crate::marked_block::remove_content(
112 &out,
113 COMPRESSION_BLOCK_START,
114 COMPRESSION_BLOCK_END,
115 )
116 } else {
117 break;
118 };
119 if next == out {
120 break;
121 }
122 out = next;
123 }
124 let trimmed = out.trim_end();
125 if trimmed.is_empty() {
126 String::new()
127 } else {
128 format!("{trimmed}\n")
129 }
130}
131
132pub(crate) fn strip_compression_block(content: &str) -> String {
136 if !(content.contains(COMPRESSION_BLOCK_START) && content.contains(COMPRESSION_BLOCK_END)) {
137 return content.to_string();
138 }
139 let stripped = crate::marked_block::remove_content(
140 content,
141 COMPRESSION_BLOCK_START,
142 COMPRESSION_BLOCK_END,
143 );
144 let trimmed = stripped.trim_end();
145 if trimmed.is_empty() {
146 String::new()
147 } else {
148 format!("{trimmed}\n")
149 }
150}
151
152fn project_owned_candidates(dir: &Path) -> Vec<PathBuf> {
155 vec![
156 dir.join(".cursor/rules/lean-ctx.mdc"),
157 dir.join(".claude/rules/lean-ctx.md"),
158 dir.join(".codebuddy/rules/lean-ctx.md"),
159 dir.join(".windsurf/rules/lean-ctx.md"),
160 dir.join(".cline/rules/lean-ctx.md"),
161 dir.join(".roo/rules/lean-ctx.md"),
162 ]
163}
164
165pub(crate) fn plan(home: &Path, project: &Path) -> Vec<Action> {
167 let mut actions = Vec::new();
168 let canonical_cursor_mdc = home.join(".cursor/rules/lean-ctx.mdc");
169
170 let mut dir = Some(project.to_path_buf());
172 while let Some(d) = dir {
173 if d == *home {
174 break;
175 }
176 for candidate in project_owned_candidates(&d) {
177 if candidate == canonical_cursor_mdc {
178 continue;
179 }
180 let Ok(content) = std::fs::read_to_string(&candidate) else {
181 continue;
182 };
183 if is_owned_rules_file(&content) {
184 actions.push(Action::DeleteFile {
185 path: candidate,
186 reason: "lean-ctx-owned duplicate of the global rules file".into(),
187 });
188 } else if !content.trim().is_empty() {
189 actions.push(Action::Report {
190 path: candidate,
191 note: "contains custom edits — not lean-ctx-owned, left untouched".into(),
192 });
193 }
194 }
195 dir = d.parent().map(Path::to_path_buf);
196 }
197
198 let cursorrules = project.join(".cursorrules");
201 if let Ok(content) = std::fs::read_to_string(&cursorrules) {
202 if canonical_cursor_mdc.exists() && has_marked_block(&content) {
203 actions.push(Action::StripBlocks {
204 path: cursorrules,
205 reason: "global ~/.cursor/rules/lean-ctx.mdc already carries these blocks".into(),
206 });
207 } else if !canonical_cursor_mdc.exists() && content.contains("lean-ctx") {
208 actions.push(Action::Report {
209 path: cursorrules,
210 note: "no global Cursor mdc found — .cursorrules stays the carrier".into(),
211 });
212 } else if content.contains("lean-ctx") && !has_marked_block(&content) {
213 actions.push(Action::Report {
214 path: cursorrules,
215 note: "mentions lean-ctx without markers (manual rules) — review by hand".into(),
216 });
217 }
218 }
219
220 let agents_md = project.join("AGENTS.md");
225 if let Ok(content) = std::fs::read_to_string(&agents_md) {
226 let has_compression =
227 content.contains(COMPRESSION_BLOCK_START) && content.contains(COMPRESSION_BLOCK_END);
228 if has_compression {
229 if crate::core::rules_channel::agents_md_can_thin(home) {
230 actions.push(Action::StripCompression {
231 path: agents_md,
232 reason: "every AGENTS.md reader already loads the compression block from its own canonical file".into(),
233 });
234 } else {
235 actions.push(Action::Report {
236 path: agents_md,
237 note: "an AGENTS.md reader has no other compression source — AGENTS.md stays the carrier".into(),
238 });
239 }
240 }
241 }
242
243 actions
244}
245
246fn apply(action: &Action) -> String {
248 match action {
249 Action::DeleteFile { path, .. } => match std::fs::remove_file(path) {
250 Ok(()) => format!("deleted {}", path.display()),
251 Err(e) => format!("FAILED {} ({e})", path.display()),
252 },
253 Action::StripBlocks { path, .. } => {
254 let Ok(content) = std::fs::read_to_string(path) else {
255 return format!("FAILED {} (unreadable)", path.display());
256 };
257 let stripped = strip_lean_ctx_blocks(&content);
258 if stripped == content {
259 return format!("unchanged {}", path.display());
260 }
261 let bak = path.with_extension("bak");
262 if let Err(e) = std::fs::write(&bak, &content) {
263 return format!("FAILED {} (backup: {e})", path.display());
264 }
265 if stripped.is_empty() {
266 match std::fs::remove_file(path) {
267 Ok(()) => format!(
268 "deleted {} (only lean-ctx blocks, backup: {})",
269 path.display(),
270 bak.display()
271 ),
272 Err(e) => format!("FAILED {} ({e})", path.display()),
273 }
274 } else {
275 match std::fs::write(path, &stripped) {
276 Ok(()) => format!("stripped {} (backup: {})", path.display(), bak.display()),
277 Err(e) => format!("FAILED {} ({e})", path.display()),
278 }
279 }
280 }
281 Action::StripCompression { path, .. } => {
282 let Ok(content) = std::fs::read_to_string(path) else {
283 return format!("FAILED {} (unreadable)", path.display());
284 };
285 let stripped = strip_compression_block(&content);
286 if stripped == content {
287 return format!("unchanged {}", path.display());
288 }
289 let bak = path.with_extension("bak");
290 if let Err(e) = std::fs::write(&bak, &content) {
291 return format!("FAILED {} (backup: {e})", path.display());
292 }
293 match std::fs::write(path, &stripped) {
294 Ok(()) => format!("thinned {} (backup: {})", path.display(), bak.display()),
295 Err(e) => format!("FAILED {} ({e})", path.display()),
296 }
297 }
298 Action::Report { path, note } => format!("info {} — {note}", path.display()),
299 }
300}
301
302pub fn auto_apply(home: &Path, project: &Path) -> Vec<String> {
307 plan(home, project)
308 .iter()
309 .filter(|a| !matches!(a, Action::Report { .. }))
310 .map(apply)
311 .collect()
312}
313
314pub fn run(apply_changes: bool) -> i32 {
316 let Some(home) = dirs::home_dir() else {
317 eprintln!("Error: could not determine home directory");
318 return 1;
319 };
320 let project = std::env::current_dir().unwrap_or_else(|_| home.clone());
321 let actions = plan(&home, &project);
322
323 if actions.is_empty() {
324 println!("No duplicated lean-ctx rules found — every client pays once.");
325 return 0;
326 }
327
328 println!(
329 "{} (project: {})\n",
330 if apply_changes {
331 "Deduplicating lean-ctx rules"
332 } else {
333 "Dedup plan (dry-run — pass --apply to execute)"
334 },
335 project.display()
336 );
337
338 let mut fixable = 0usize;
339 for action in &actions {
340 match action {
341 Action::DeleteFile { path, reason } => {
342 fixable += 1;
343 if apply_changes {
344 println!(" {}", apply(action));
345 } else {
346 println!(" delete {}\n ({reason})", path.display());
347 }
348 }
349 Action::StripBlocks { path, reason } => {
350 fixable += 1;
351 if apply_changes {
352 println!(" {}", apply(action));
353 } else {
354 println!(" strip {}\n ({reason})", path.display());
355 }
356 }
357 Action::StripCompression { path, reason } => {
358 fixable += 1;
359 if apply_changes {
360 println!(" {}", apply(action));
361 } else {
362 println!(" thin {}\n ({reason})", path.display());
363 }
364 }
365 Action::Report { .. } => println!(" {}", apply(action)),
366 }
367 }
368
369 if !apply_changes && fixable > 0 {
370 println!("\nRun `lean-ctx rules dedup --apply` to fix {fixable} duplicate(s).");
371 }
372 if apply_changes && fixable > 0 {
373 println!("\nDone. Verify with `lean-ctx doctor overhead`.");
374 }
375 0
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 fn owned_mdc() -> String {
383 format!(
384 "---\ndescription: lean-ctx\n---\n{}\n<!-- version: 1 -->\nbody\n",
385 crate::core::rules_canonical::START_MARK
386 )
387 }
388
389 #[test]
390 fn detects_owned_dedicated_files() {
391 assert!(is_owned_rules_file(&owned_mdc()));
392 assert!(is_owned_rules_file(&format!(
393 "{}\n<!-- version: 1 -->\nbody\n",
394 crate::core::rules_canonical::START_MARK
395 )));
396 assert!(!is_owned_rules_file("# My rules\nuse lean-ctx tools\n"));
398 assert!(!is_owned_rules_file(&format!(
400 "# my header\n{}\n<!-- version: 1 -->\n",
401 crate::core::rules_canonical::START_MARK
402 )));
403 }
404
405 #[test]
406 fn strip_removes_rules_and_compression_blocks() {
407 let content = format!(
408 "user line\n{BLOCK_START}\nour rules\n{BLOCK_END}\nmore user\n{COMPRESSION_BLOCK_START}\nstyle\n{COMPRESSION_BLOCK_END}\n",
409 );
410 let out = strip_lean_ctx_blocks(&content);
411 assert!(out.contains("user line"));
412 assert!(out.contains("more user"));
413 assert!(!out.contains("our rules"));
414 assert!(!out.contains("style"));
415 assert!(!out.contains("lean-ctx-compression"));
416 }
417
418 #[test]
419 fn strip_of_pure_block_file_yields_empty() {
420 let content = format!("{BLOCK_START}\nonly ours\n{BLOCK_END}\n");
421 assert_eq!(strip_lean_ctx_blocks(&content), "");
422 }
423
424 #[test]
427 fn legacy_marker_files_owned_only_when_wholly_lean_ctx() {
428 let pristine = "# lean-ctx — Context Engineering Layer\n\
429 <!-- lean-ctx-rules-v9 -->\n\n\
430 PREFER lean-ctx MCP tools.\n\
431 Write, Delete, Glob → use normally.\n\
432 <!-- /lean-ctx -->\n";
433 assert!(is_owned_rules_file(pristine));
434
435 let user_extended = format!("{pristine}\n## My own precedence rules\nkeep me\n");
436 assert!(!is_owned_rules_file(&user_extended));
437
438 assert!(!is_owned_rules_file(
440 "my notes\nabout <!-- lean-ctx-rules-v9 --> markers\n<!-- /lean-ctx -->\n"
441 ));
442 }
443
444 #[test]
445 fn plan_deletes_project_and_parent_owned_files_only() {
446 let tmp = tempfile::tempdir().unwrap();
447 let home = tmp.path();
448 let parent = home.join("projects");
449 let project = parent.join("app");
450
451 std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
453 std::fs::write(home.join(".cursor/rules/lean-ctx.mdc"), owned_mdc()).unwrap();
454 std::fs::create_dir_all(project.join(".cursor/rules")).unwrap();
456 std::fs::write(project.join(".cursor/rules/lean-ctx.mdc"), owned_mdc()).unwrap();
457 std::fs::create_dir_all(parent.join(".cursor/rules")).unwrap();
458 std::fs::write(parent.join(".cursor/rules/lean-ctx.mdc"), owned_mdc()).unwrap();
459 std::fs::create_dir_all(project.join(".claude/rules")).unwrap();
461 std::fs::write(
462 project.join(".claude/rules/lean-ctx.md"),
463 "# customized by user\nkeep me\n",
464 )
465 .unwrap();
466
467 let actions = plan(home, &project);
468 let deletes: Vec<&PathBuf> = actions
469 .iter()
470 .filter_map(|a| match a {
471 Action::DeleteFile { path, .. } => Some(path),
472 _ => None,
473 })
474 .collect();
475 assert_eq!(deletes.len(), 2, "project + parent copies: {actions:?}");
476 assert!(deletes.iter().all(|p| !p.starts_with(home.join(".cursor"))));
477 assert!(actions.iter().any(|a| matches!(
478 a,
479 Action::Report { path, .. } if path.ends_with(".claude/rules/lean-ctx.md")
480 )));
481 }
482
483 #[test]
484 fn plan_strips_cursorrules_only_with_canonical_mdc() {
485 let tmp = tempfile::tempdir().unwrap();
486 let home = tmp.path();
487 let project = home.join("app");
488 std::fs::create_dir_all(&project).unwrap();
489 let rules = format!("{BLOCK_START}\npointer\n{BLOCK_END}\n");
490 std::fs::write(project.join(".cursorrules"), rules).unwrap();
491
492 let actions = plan(home, &project);
494 assert!(
495 !actions
496 .iter()
497 .any(|a| matches!(a, Action::StripBlocks { .. })),
498 "{actions:?}"
499 );
500
501 std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
503 std::fs::write(home.join(".cursor/rules/lean-ctx.mdc"), owned_mdc()).unwrap();
504 let actions = plan(home, &project);
505 assert!(
506 actions.iter().any(|a| matches!(
507 a,
508 Action::StripBlocks { path, .. } if path.ends_with(".cursorrules")
509 )),
510 "{actions:?}"
511 );
512 }
513
514 #[test]
515 fn apply_strip_writes_backup_and_keeps_user_content() {
516 let tmp = tempfile::tempdir().unwrap();
517 let path = tmp.path().join(".cursorrules");
518 std::fs::write(
519 &path,
520 format!("my custom rule\n{BLOCK_START}\nours\n{BLOCK_END}\n"),
521 )
522 .unwrap();
523
524 let msg = apply(&Action::StripBlocks {
525 path: path.clone(),
526 reason: String::new(),
527 });
528 assert!(msg.starts_with("stripped"), "{msg}");
529 let after = std::fs::read_to_string(&path).unwrap();
530 assert_eq!(after, "my custom rule\n");
531 let bak = std::fs::read_to_string(path.with_extension("bak")).unwrap();
532 assert!(bak.contains("ours"));
533 }
534
535 #[test]
536 fn strip_compression_keeps_pointer_and_user_content() {
537 let content = format!(
538 "# Agent Instructions\n\n{BLOCK_START}\npointer\n{BLOCK_END}\n\n{COMPRESSION_BLOCK_START}\nOUTPUT STYLE\n{COMPRESSION_BLOCK_END}\n",
539 );
540 let out = strip_compression_block(&content);
541 assert!(out.contains("# Agent Instructions"));
542 assert!(out.contains(BLOCK_START));
543 assert!(out.contains("pointer"));
544 assert!(!out.contains("lean-ctx-compression"));
545 assert!(!out.contains("OUTPUT STYLE"));
546 }
547
548 #[test]
549 fn plan_thins_agents_md_when_cursor_covered_and_no_codex() {
550 let _guard = crate::core::data_dir::test_env_lock();
551 let tmp = tempfile::tempdir().unwrap();
552 let home = tmp.path();
553 let project = home.join("app");
554 std::fs::create_dir_all(&project).unwrap();
555 crate::test_env::set_var("CODEX_HOME", home.join(".codex"));
557
558 std::fs::create_dir_all(home.join(".cursor/rules")).unwrap();
560 std::fs::write(
561 home.join(".cursor/rules/lean-ctx.mdc"),
562 format!(
563 "{}\n<!-- version: 1 -->\n{COMPRESSION_BLOCK_START}\nstyle\n{COMPRESSION_BLOCK_END}\n",
564 crate::core::rules_canonical::START_MARK
565 ),
566 )
567 .unwrap();
568
569 std::fs::write(
571 project.join("AGENTS.md"),
572 format!(
573 "# Agent Instructions\n\n{BLOCK_START}\npointer\n{BLOCK_END}\n\n{COMPRESSION_BLOCK_START}\nstyle\n{COMPRESSION_BLOCK_END}\n"
574 ),
575 )
576 .unwrap();
577
578 let actions = plan(home, &project);
579 assert!(
580 actions.iter().any(|a| matches!(
581 a,
582 Action::StripCompression { path, .. } if path.ends_with("AGENTS.md")
583 )),
584 "{actions:?}"
585 );
586 crate::test_env::remove_var("CODEX_HOME");
587 }
588
589 #[test]
590 fn plan_keeps_agents_md_carrier_when_cursor_uncovered() {
591 let _guard = crate::core::data_dir::test_env_lock();
592 let tmp = tempfile::tempdir().unwrap();
593 let home = tmp.path();
594 let project = home.join("app");
595 std::fs::create_dir_all(&project).unwrap();
596 crate::test_env::set_var("CODEX_HOME", home.join(".codex"));
597
598 std::fs::write(
600 project.join("AGENTS.md"),
601 format!(
602 "# Agent Instructions\n\n{BLOCK_START}\npointer\n{BLOCK_END}\n\n{COMPRESSION_BLOCK_START}\nstyle\n{COMPRESSION_BLOCK_END}\n"
603 ),
604 )
605 .unwrap();
606
607 let actions = plan(home, &project);
608 assert!(
609 !actions
610 .iter()
611 .any(|a| matches!(a, Action::StripCompression { .. })),
612 "{actions:?}"
613 );
614 assert!(
616 actions.iter().any(|a| matches!(
617 a,
618 Action::Report { path, .. } if path.ends_with("AGENTS.md")
619 )),
620 "{actions:?}"
621 );
622 crate::test_env::remove_var("CODEX_HOME");
623 }
624
625 #[test]
626 fn apply_strip_compression_thins_and_backs_up() {
627 let tmp = tempfile::tempdir().unwrap();
628 let path = tmp.path().join("AGENTS.md");
629 std::fs::write(
630 &path,
631 format!(
632 "# Agent Instructions\n\n{BLOCK_START}\npointer\n{BLOCK_END}\n\n{COMPRESSION_BLOCK_START}\nstyle\n{COMPRESSION_BLOCK_END}\n"
633 ),
634 )
635 .unwrap();
636
637 let msg = apply(&Action::StripCompression {
638 path: path.clone(),
639 reason: String::new(),
640 });
641 assert!(msg.starts_with("thinned"), "{msg}");
642 let after = std::fs::read_to_string(&path).unwrap();
643 assert!(after.contains(BLOCK_START));
644 assert!(!after.contains("lean-ctx-compression"));
645 let bak = std::fs::read_to_string(path.with_extension("bak")).unwrap();
646 assert!(bak.contains("lean-ctx-compression"));
647 }
648
649 #[test]
650 fn apply_strip_deletes_file_that_was_only_ours() {
651 let tmp = tempfile::tempdir().unwrap();
652 let path = tmp.path().join(".cursorrules");
653 std::fs::write(&path, format!("{BLOCK_START}\nours\n{BLOCK_END}\n")).unwrap();
654
655 let msg = apply(&Action::StripBlocks {
656 path: path.clone(),
657 reason: String::new(),
658 });
659 assert!(msg.starts_with("deleted"), "{msg}");
660 assert!(!path.exists());
661 assert!(path.with_extension("bak").exists());
662 }
663}