Skip to main content

lean_ctx/cli/
rules_dedup.rs

1//! `lean-ctx rules dedup` — collapse duplicated lean-ctx guidance (#578).
2//!
3//! A client should pay for lean-ctx rules exactly once per session. Older
4//! installs (and parent-directory walks in monorepos) left full rule copies
5//! in several auto-loaded files; `doctor overhead` detects the duplication,
6//! this command repairs it:
7//!
8//!  1. lean-ctx-OWNED dedicated rule files outside the canonical global
9//!     location (project/parent `.cursor/rules/lean-ctx.mdc`,
10//!     `.claude/rules/lean-ctx.md`, …) → deleted.
11//!  2. `.cursorrules` lean-ctx blocks → removed when the canonical global
12//!     Cursor mdc exists (Cursor auto-loads both; pointer lives in AGENTS.md).
13//!  3. Stale compression blocks in `.cursorrules` → removed under the same
14//!     condition (the global mdc carries the block).
15//!  4. Compression block in a shared `AGENTS.md` (#684) → removed (pointer
16//!     kept) once every AGENTS.md reader is covered by its own canonical
17//!     carrier; otherwise reported and left as the carrier.
18//!
19//! Only lean-ctx-owned files and lean-ctx-marked blocks are ever touched.
20//! Unmarked user content is reported, never modified. Default is a dry-run
21//! report; `--apply` executes with `.bak` backups for partial edits.
22
23use 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/// One planned dedup action.
29#[derive(Debug, PartialEq, Eq)]
30pub(crate) enum Action {
31    /// Delete a wholly lean-ctx-owned duplicate rules file.
32    DeleteFile { path: PathBuf, reason: String },
33    /// Strip lean-ctx-marked blocks from a shared file (keeps user content).
34    StripBlocks { path: PathBuf, reason: String },
35    /// Strip only the compression block from a shared file, keeping the
36    /// `<!-- lean-ctx -->` pointer and all user content (#684 — thins a shared
37    /// AGENTS.md whose readers are all covered by their own canonical carrier).
38    StripCompression { path: PathBuf, reason: String },
39    /// Informational only — lean-ctx guidance in user-maintained content.
40    Report { path: PathBuf, note: String },
41}
42
43/// A file is "lean-ctx-owned" when lean-ctx wrote the whole file: dedicated
44/// rule files start with the canonical header and carry a rules-version
45/// marker, project LEAN-CTX.md carries its ownership marker.
46fn 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        // CursorMdc has YAML frontmatter before the header.
51        || (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
59/// #1289: older installs wrote dedicated rule files with versioned markers
60/// (`<!-- lean-ctx-rules-v9 -->`) and no `<!-- version: N -->` line. Those
61/// files never matched the canonical ownership test above, so stale guidance
62/// (e.g. "Write, Delete, Glob → use normally" contradicting the shadow-mode
63/// Glob deny) survived every update and dedup run. A legacy file counts as
64/// owned when lean-ctx plausibly wrote all of it: a legacy rules marker sits
65/// in the first few lines and nothing but whitespace follows the last closing
66/// lean-ctx marker — user-extended files keep getting the Report instead.
67fn is_owned_legacy_rules_file(content: &str) -> bool {
68    let mut lines = content.trim_start().lines();
69    // Legacy files start with a `# lean-ctx …` heading (marker on the next
70    // line) or with the marker itself — a marker merely mentioned mid-text
71    // does not make a file lean-ctx-owned.
72    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
90/// Line-based marker pair detection (GL #1158): prose mentions of a marker
91/// must not count as a block.
92fn 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
102/// Strips every lean-ctx-marked block (rules + compression) from `content`.
103pub(crate) fn strip_lean_ctx_blocks(content: &str) -> String {
104    let mut out = content.to_string();
105    // Repeat until stable — a file can contain both block kinds (and in
106    // pathological cases several of the same kind).
107    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
132/// Strips only the compression block, keeping the `<!-- lean-ctx -->` pointer
133/// and every line of user content. Used to thin a shared AGENTS.md once each
134/// reader is covered by its own canonical carrier (#684).
135pub(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
152/// Dedicated lean-ctx rule files that may linger in a project / parent chain
153/// from older versions. Canonical copies live under `home` (global targets).
154fn 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
165/// Plans the dedup for `project` (walking parents up to, excluding, `home`).
166pub(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    // 1. Owned dedicated duplicates in the project + parent chain.
171    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    // 2./3. `.cursorrules`: marked blocks are redundant once the canonical
199    // global mdc exists (Cursor loads both files every session).
200    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    // 4. Shared project AGENTS.md (#684): Cursor, Codex and other agents all
221    // auto-load it, so a compression block here duplicates each reader's own
222    // canonical carrier. Strip only the compression block (the pointer stays)
223    // once every reader present on this machine is covered elsewhere.
224    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
246/// Executes one action. Returns a human-readable result line.
247fn 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
302/// Non-interactive auto-heal used by `lean-ctx setup` and `doctor --fix`
303/// (#578): applies every *fixable* dedup action (owned duplicates deleted,
304/// marked blocks stripped with `.bak` backups) and returns one result line per
305/// action. `Report`-only findings (user-maintained content) are never touched.
306pub 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
314/// CLI entry: `lean-ctx rules dedup [--apply]`.
315pub 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        // User file mentioning lean-ctx is NOT owned.
397        assert!(!is_owned_rules_file("# My rules\nuse lean-ctx tools\n"));
398        // Marker buried mid-file (user prepended content) is NOT owned.
399        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    /// #1289: legacy versioned-marker files (rules-v9 era, no `<!-- version:`)
425    /// are owned when wholly lean-ctx-written; user-extended copies are not.
426    #[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        // A user file that merely mentions the marker mid-text is not owned.
439        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        // Canonical global mdc (must never be planned for deletion).
452        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        // Stale project + parent copies.
455        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        // User-customized file — must only be reported.
460        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        // Without the global mdc, .cursorrules is the carrier — report only.
493        let actions = plan(home, &project);
494        assert!(
495            !actions
496                .iter()
497                .any(|a| matches!(a, Action::StripBlocks { .. })),
498            "{actions:?}"
499        );
500
501        // With the canonical mdc, the block is a duplicate — strip.
502        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        // Isolate codex resolution to this empty home (no codex present).
556        crate::test_env::set_var("CODEX_HOME", home.join(".codex"));
557
558        // Canonical global mdc carries the compression block → cursor covered.
559        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        // Project AGENTS.md still carries pointer + compression.
570        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        // No global mdc → cursor not covered → AGENTS.md must stay the carrier.
599        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        // Reported instead, so the user understands why it was left alone.
615        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}