Skip to main content

lean_ctx_cli/uninstall/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2mod agents;
3mod binary;
4mod parsers;
5
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use agents::{
10    remove_hook_files, remove_mcp_configs, remove_plan_mode_settings, remove_project_agent_files,
11    remove_rules_files, remove_shell_hook,
12};
13
14pub(super) fn backup_before_modify(path: &Path, dry_run: bool) {
15    if dry_run {
16        return;
17    }
18    if path.exists() {
19        // GHSA-x992-2945-crwx: a cloned repository can ship
20        // `<file>.lean-ctx.bak` as a symlink; never write the backup through it.
21        let bak = bak_path_for(path);
22        if let Ok(bytes) = fs::read(path) {
23            let _ = lean_ctx::config_io::write_backup_nofollow(path, &bak, &bytes);
24        }
25    }
26}
27
28pub fn bak_path_for(path: &Path) -> PathBuf {
29    let filename = path.file_name().unwrap_or_default().to_string_lossy();
30    path.with_file_name(format!("{filename}.lean-ctx.bak"))
31}
32
33fn cleanup_bak(path: &Path) {
34    let bak = bak_path_for(path);
35    if bak.exists() {
36        let _ = fs::remove_file(&bak);
37    }
38}
39
40pub(super) fn shorten(path: &Path, home: &Path) -> String {
41    match path.strip_prefix(home) {
42        Ok(rel) => format!("~/{}", rel.display()),
43        Err(_) => path.display().to_string(),
44    }
45}
46
47pub(super) fn copilot_instructions_path(home: &Path) -> PathBuf {
48    #[cfg(target_os = "macos")]
49    {
50        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
51    }
52    #[cfg(target_os = "linux")]
53    {
54        let user_dirs = [
55            home.join(".config/Code/User"),
56            home.join(".config/Code - Insiders/User"),
57            home.join(".vscode-server/data/User"),
58        ];
59        let user_dir = user_dirs
60            .iter()
61            .find(|p| p.exists())
62            .cloned()
63            .unwrap_or_else(|| user_dirs[0].clone());
64        return user_dir.join("github-copilot-instructions.md");
65    }
66    #[cfg(target_os = "windows")]
67    {
68        if let Ok(appdata) = std::env::var("APPDATA") {
69            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
70        }
71    }
72    #[allow(unreachable_code)]
73    home.join(".config/Code/User/github-copilot-instructions.md")
74}
75
76/// Write `content` to `path` only if not in dry-run mode.
77pub(super) fn safe_write(path: &Path, content: &str, dry_run: bool) -> Result<(), std::io::Error> {
78    if dry_run {
79        return Ok(());
80    }
81    fs::write(path, content)?;
82    // If we successfully wrote the cleaned file, the backup is no longer needed.
83    cleanup_bak(path);
84    Ok(())
85}
86
87/// Rewrite a rules file only if not in dry-run mode: atomically (temp file +
88/// rename), owner-only, and through a symlink only when it stays within
89/// `$HOME` — the writer setup uses. The caller already took the
90/// `.lean-ctx.bak` copy, which goes once the write succeeded.
91pub(super) fn safe_write_rules(path: &Path, content: &str, dry_run: bool) -> Result<(), String> {
92    if dry_run {
93        return Ok(());
94    }
95    lean_ctx::config_io::write_atomic(path, content)?;
96    cleanup_bak(path);
97    Ok(())
98}
99
100/// Remove `path` only if not in dry-run mode.
101pub(super) fn safe_remove(path: &Path, dry_run: bool) -> Result<(), std::io::Error> {
102    if dry_run {
103        return Ok(());
104    }
105    fs::remove_file(path)?;
106    // If we successfully removed the file, also remove its backup.
107    cleanup_bak(path);
108    Ok(())
109}
110
111// ---------------------------------------------------------------------------
112// Help
113// ---------------------------------------------------------------------------
114
115/// Print usage for `lean-ctx uninstall`.
116///
117/// This MUST stay side-effect free: `lean-ctx uninstall --help` previously fell
118/// through to [`run`] and removed everything, so help is now short-circuited in
119/// the CLI dispatch before any removal happens.
120pub fn print_help() {
121    println!(
122        "\
123lean-ctx uninstall — remove lean-ctx cleanly
124
125USAGE:
126    lean-ctx uninstall [OPTIONS]
127
128OPTIONS:
129    --dry-run        Preview every change without modifying anything
130    --keep-config    Preserve MCP configs and rules (for a later reinstall)
131    --keep-binary    Leave the lean-ctx binary in place
132    -h, --help       Show this help and exit (does NOT uninstall)
133
134WHAT IT REMOVES:
135    • Running processes (daemon, proxy) and autostart entries
136    • Shell hooks and proxy environment from your shell rc files
137    • MCP server configs and rules from every detected AI tool/IDE
138    • Skill directories and project integration files
139    • The data directory and the lean-ctx binary
140
141    Modified files are backed up as <file>.lean-ctx.bak before removal.
142
143EXAMPLES:
144    lean-ctx uninstall --dry-run     # see exactly what would change
145    lean-ctx uninstall               # full clean removal"
146    );
147}
148
149/// Options of `lean-ctx uninstall`: `(dry_run, keep_config, keep_binary)`.
150///
151/// Every argument must be a known flag. A typo such as `--dry-rnu` used to be
152/// ignored and ran a full, irreversible uninstall; it is now an error.
153pub fn parse_args(rest: &[String]) -> Result<(bool, bool, bool), String> {
154    let (mut dry_run, mut keep_config, mut keep_binary) = (false, false, false);
155    for arg in rest {
156        match arg.as_str() {
157            "--dry-run" => dry_run = true,
158            "--keep-config" => keep_config = true,
159            "--keep-binary" => keep_binary = true,
160            other => {
161                return Err(format!(
162                    "lean-ctx uninstall: unknown argument '{other}'; nothing was removed.\n\
163                     Usage: lean-ctx uninstall [--dry-run] [--keep-config] [--keep-binary] \
164                     (see: lean-ctx uninstall --help)"
165                ));
166            }
167        }
168    }
169    Ok((dry_run, keep_config, keep_binary))
170}
171
172// ---------------------------------------------------------------------------
173// Main entry
174// ---------------------------------------------------------------------------
175
176pub fn run(dry_run: bool, keep_config: bool, keep_binary: bool) {
177    let Some(home) = dirs::home_dir() else {
178        tracing::warn!("Could not determine home directory");
179        return;
180    };
181
182    let mode_label = if keep_config {
183        "uninstall --keep-config"
184    } else {
185        "uninstall"
186    };
187
188    if dry_run {
189        println!("\n  lean-ctx {mode_label} --dry-run\n  ──────────────────────────────────\n");
190        println!("  Preview mode — no files will be modified.\n");
191    } else {
192        println!("\n  lean-ctx {mode_label}\n  ──────────────────────────────────\n");
193    }
194
195    if keep_config {
196        println!("  Mode: keep-config (MCP configs and rules preserved for reinstall)\n");
197    }
198
199    // Stop everything first so nothing respawns or holds the files/data we remove next.
200    binary::stop_processes(dry_run);
201
202    let mut removed_any = false;
203
204    removed_any |= remove_shell_hook(&home, dry_run);
205    if dry_run {
206        crate::proxy_setup::preview_proxy_cleanup(&home);
207    } else {
208        crate::proxy_setup::uninstall_proxy_env(&home, false);
209    }
210
211    if keep_config {
212        println!("  · Skipped: MCP configs (--keep-config)");
213        println!("  · Skipped: Rules files (--keep-config)");
214    } else {
215        removed_any |= remove_mcp_configs(&home, dry_run);
216        removed_any |= remove_rules_files(&home, dry_run);
217        if !dry_run {
218            try_claude_mcp_remove();
219        }
220    }
221
222    removed_any |= remove_hook_files(&home, dry_run);
223    removed_any |= remove_plan_mode_settings(&home, dry_run);
224    removed_any |= remove_skill_dirs(&home, dry_run);
225    removed_any |= remove_project_agent_files(dry_run);
226
227    if dry_run {
228        println!("  Would remove proxy autostart (LaunchAgent/systemd)");
229        println!("  Would remove daemon autostart (LaunchAgent/systemd)");
230        println!("  Would remove auto-update schedule (LaunchAgent/systemd/Task)");
231    } else {
232        lean_ctx::proxy_autostart::uninstall(true);
233        lean_ctx::daemon_autostart::uninstall(true);
234        // The 6-hourly self-update agent (com.leanctx.autoupdate) is a *separate*
235        // autostart entry from daemon/proxy. Without this it survives uninstall and
236        // keeps relaunching the now-deleted binary every 6h. remove_schedule() is the
237        // same idempotent routine used elsewhere (macOS/Linux/Windows aware).
238        let had_schedule = lean_ctx::core::update_scheduler::schedule_status().enabled;
239        match lean_ctx::core::update_scheduler::remove_schedule() {
240            Ok(()) if had_schedule => {
241                println!("  ✓ Auto-update schedule removed");
242                removed_any = true;
243            }
244            Ok(()) => {}
245            Err(e) => tracing::warn!("Failed to remove auto-update schedule: {e}"),
246        }
247    }
248
249    if !dry_run {
250        cleanup_bak_files(&home);
251    }
252
253    removed_any |= remove_data_dir(&home, dry_run);
254
255    // Last filesystem step: every file-removal pass above has run, so
256    // installer-created directories that are empty now stay empty.
257    if !dry_run {
258        sweep_empty_installer_dirs(&home);
259    }
260
261    // Remove the binary itself last: once it's gone we can't re-exec, and on Unix the
262    // running process keeps working until exit.
263    removed_any |= binary::remove_binaries(&home, dry_run, keep_binary);
264
265    println!();
266
267    if removed_any {
268        println!("  ──────────────────────────────────");
269        if dry_run {
270            println!(
271                "  The above changes WOULD be applied.\n  Run `lean-ctx {mode_label}` to execute.\n"
272            );
273        } else if keep_config {
274            println!(
275                "  Runtime data removed. MCP configs preserved for reinstall.\n  \
276                 Reinstall with: cargo install lean-ctx\n"
277            );
278        } else {
279            println!(
280                "  lean-ctx fully removed. Restart your shell to drop stale aliases.\n  \
281                 Verify with: command -v lean-ctx   # should print nothing\n"
282            );
283        }
284    } else {
285        println!("  Nothing to remove — lean-ctx was not configured.\n");
286    }
287}
288
289// ---------------------------------------------------------------------------
290// Marked block removal (for AGENTS.md, SharedMarkdown)
291// ---------------------------------------------------------------------------
292
293/// Remove the block from the `start` marker line through the first `end`
294/// marker line after it. Markers count only as whole lines (GL #1158): a
295/// marker quoted inside user prose is user text, and without an end line
296/// after the start the content is returned unchanged.
297pub(super) fn remove_marked_block(content: &str, start: &str, end: &str) -> String {
298    use lean_ctx::marked_block::marker_line_span;
299    let span = marker_line_span(content, start).and_then(|(si, after_start)| {
300        marker_line_span(&content[after_start..], end).map(|(_, e)| (si, after_start + e))
301    });
302    match span {
303        Some((si, after_end)) => {
304            let before = &content[..si];
305            let after = &content[after_end..];
306            let mut out = String::new();
307            // `\r` too: in a CRLF file a `\n`-only trim stops at the `\r`,
308            // and every install/uninstall cycle would add blank lines.
309            out.push_str(before.trim_end_matches(['\r', '\n']));
310            out.push('\n');
311            if !after.trim().is_empty() {
312                out.push('\n');
313                out.push_str(after.trim_start_matches(['\r', '\n']));
314            }
315            out
316        }
317        _ => content.to_string(),
318    }
319}
320
321// ---------------------------------------------------------------------------
322// Skill directories: lean-ctx SKILL.md + scripts
323// ---------------------------------------------------------------------------
324
325fn remove_skill_dirs(home: &Path, dry_run: bool) -> bool {
326    let claude_state = lean_ctx::core::editor_registry::claude_state_dir(home);
327    let codebuddy_state = lean_ctx::core::editor_registry::codebuddy_state_dir(home);
328    let mut skill_dirs: Vec<(&str, PathBuf)> = vec![
329        ("Claude Code", claude_state.join("skills/lean-ctx")),
330        ("CodeBuddy", codebuddy_state.join("skills/lean-ctx")),
331        ("Cursor", home.join(".cursor/skills/lean-ctx")),
332        (
333            "Codex CLI",
334            lean_ctx::core::home::resolve_codex_dir()
335                .unwrap_or_else(|| home.join(".codex"))
336                .join("skills/lean-ctx"),
337        ),
338        ("Grok", home.join(".grok/skills/lean-ctx")),
339        ("Copilot", home.join(".copilot/skills/lean-ctx")),
340        ("OpenClaw", home.join(".openclaw/skills/lean-ctx")),
341    ];
342
343    // If CLAUDE_CONFIG_DIR differs from ~/.claude, also clean default path
344    let default_claude_skill = home.join(".claude/skills/lean-ctx");
345    if !skill_dirs.iter().any(|(_, p)| *p == default_claude_skill) {
346        skill_dirs.push(("Claude Code (default)", default_claude_skill));
347    }
348
349    // If CODEBUDDY_CONFIG_DIR differs from ~/.codebuddy, also clean default path
350    let default_codebuddy_skill = home.join(".codebuddy/skills/lean-ctx");
351    if !skill_dirs
352        .iter()
353        .any(|(_, p)| *p == default_codebuddy_skill)
354    {
355        skill_dirs.push(("CodeBuddy (default)", default_codebuddy_skill));
356    }
357
358    let mut removed = false;
359    for (name, dir) in &skill_dirs {
360        if !dir.exists() {
361            continue;
362        }
363        if dry_run {
364            println!("  Would remove {name} skill directory");
365            removed = true;
366        } else if let Err(e) = fs::remove_dir_all(dir) {
367            tracing::warn!("Failed to remove {name} skill dir: {e}");
368        } else {
369            println!("  ✓ {name} skill directory removed");
370            removed = true;
371        }
372    }
373    removed
374}
375
376// ---------------------------------------------------------------------------
377// Data directory
378// ---------------------------------------------------------------------------
379
380/// Every lean-ctx directory an uninstall must delete, de-duplicated and
381/// order-preserving.
382///
383/// Historically this used `dirs::data_dir()` / `dirs::data_local_dir()`, which on
384/// macOS both resolve to `~/Library/Application Support` — so the *real* runtime
385/// dirs (`~/.local/share`, `~/.local/state`, `~/.cache`) were never removed and a
386/// "full" uninstall left >150 MB of data + cache behind. We now resolve through the
387/// exact same [`core::paths`](lean_ctx::core::paths) functions the daemon/proxy use,
388/// so every XDG category (config/data/state/cache, honoring `LEAN_CTX_*_DIR` and
389/// `XDG_*` overrides) is covered, plus the legacy single-dir and macOS
390/// Application Support locations for older installs.
391fn data_dirs_to_remove(home: &Path) -> Vec<PathBuf> {
392    let mut dirs = vec![home.join(".lean-ctx"), home.join(".config/lean-ctx")];
393
394    let push = |dirs: &mut Vec<PathBuf>, p: PathBuf| {
395        if !dirs.contains(&p) {
396            dirs.push(p);
397        }
398    };
399
400    // Canonical XDG categories actually written at runtime.
401    for resolved in [
402        lean_ctx::core::paths::config_dir(),
403        lean_ctx::core::paths::data_dir(),
404        lean_ctx::core::paths::state_dir(),
405        lean_ctx::core::paths::cache_dir(),
406    ]
407    .into_iter()
408    .flatten()
409    {
410        push(&mut dirs, resolved);
411    }
412
413    // Older installs (and Windows %LOCALAPPDATA%) may have used the platform dir.
414    for platform_dir in [dirs::data_local_dir(), dirs::data_dir()]
415        .into_iter()
416        .flatten()
417    {
418        push(&mut dirs, platform_dir.join("lean-ctx"));
419    }
420
421    dirs
422}
423
424fn remove_data_dir(home: &Path, dry_run: bool) -> bool {
425    let mut removed = false;
426
427    let dirs_to_remove = data_dirs_to_remove(home);
428
429    for data_dir in &dirs_to_remove {
430        if !data_dir.exists() {
431            continue;
432        }
433        let short = shorten(data_dir, home);
434        if dry_run {
435            println!("  Would remove data directory ({short})");
436            removed = true;
437            continue;
438        }
439        match fs::remove_dir_all(data_dir) {
440            Ok(()) => {
441                println!("  ✓ Data directory removed ({short})");
442                removed = true;
443            }
444            Err(e) => tracing::warn!("Failed to remove {short}: {e}"),
445        }
446    }
447
448    // Project-local .lean-ctx/ and .lean-ctx-id in CWD
449    if let Ok(cwd) = std::env::current_dir() {
450        let project_dir = cwd.join(".lean-ctx");
451        let project_id = cwd.join(".lean-ctx-id");
452        for p in [&project_dir, &project_id] {
453            if p.exists() {
454                if dry_run {
455                    println!("  Would remove {}", p.display());
456                    removed = true;
457                } else if p.is_dir() {
458                    if fs::remove_dir_all(p).is_ok() {
459                        println!("  ✓ Removed {}", p.display());
460                        removed = true;
461                    }
462                } else if fs::remove_file(p).is_ok() {
463                    println!("  ✓ Removed {}", p.display());
464                    removed = true;
465                }
466            }
467        }
468    }
469
470    if !removed {
471        println!("  · No data directory found");
472    }
473    removed
474}
475
476fn try_claude_mcp_remove() {
477    let result = std::process::Command::new("claude")
478        .args(["mcp", "remove", "lean-ctx", "--scope", "user"])
479        .stdout(std::process::Stdio::null())
480        .stderr(std::process::Stdio::null())
481        .status();
482    match result {
483        Ok(s) if s.success() => println!("  ✓ Removed lean-ctx from Claude MCP registry"),
484        _ => {} // claude CLI not available or already removed
485    }
486}
487
488// ---------------------------------------------------------------------------
489// .bak cleanup: remove orphaned backup files after successful surgical removal
490// ---------------------------------------------------------------------------
491
492/// Every directory the installer may have written backups or files into:
493/// agent config roots, their well-known subdirectories, and the project-local
494/// config dirs in CWD.
495fn scan_dirs(home: &Path) -> Vec<PathBuf> {
496    let base_dirs: Vec<PathBuf> = vec![
497        home.join(".cursor"),
498        home.join(".claude"),
499        lean_ctx::core::editor_registry::claude_state_dir(home),
500        home.join(".codebuddy"),
501        lean_ctx::core::editor_registry::codebuddy_state_dir(home),
502        lean_ctx::core::editor_registry::zed_config_dir(home),
503        home.join(".gemini"),
504        home.join(".gemini/antigravity"),
505        home.join(".gemini/antigravity-cli"),
506        lean_ctx::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex")),
507        home.join(".codeium"),
508        home.join(".codeium/windsurf"),
509        home.join(".config/opencode"),
510        home.join(".config/amp"),
511        home.join(".config/crush"),
512        home.join(".config/zed"),
513        home.join(".qwen"),
514        home.join(".trae"),
515        home.join(".codewhale"),
516        home.join(".deepseek"),
517        lean_ctx::core::editor_registry::muse_config_dir(home),
518        home.join(".aws/amazonq"),
519        home.join(".kiro"),
520        home.join(".kiro/settings"),
521        home.join(".ampcoder"),
522        home.join(".pi"),
523        home.join(".pi/agent"),
524        home.join(".hermes"),
525        home.join(".grok"),
526        home.join(".verdent"),
527        home.join(".cline"),
528        home.join(".roo"),
529        home.join(".continue"),
530        home.join(".jb-rules"),
531        home.join(".openclaw"),
532        home.join(".augment"),
533        home.join(".qoder"),
534        home.join(".qoderwork"),
535        home.join(".aider"),
536        home.join(".emacs.d"),
537        home.join(".copilot"),
538        home.join(".github"),
539        home.join(".config/mcphub"),
540        home.join(".config/sublime-text"),
541    ];
542
543    // Installers write into well-known subdirectories (hook scripts, rules
544    // files, steering docs, …). read_dir below is non-recursive, so backups in
545    // those subdirectories were previously missed (GL #558).
546    const KNOWN_SUBDIRS: [&str; 6] = ["hooks", "rules", "skills", "steering", "settings", "User"];
547    let mut dirs_to_scan: Vec<PathBuf> = Vec::with_capacity(base_dirs.len() * 4);
548    for dir in base_dirs {
549        for sub in KNOWN_SUBDIRS {
550            let p = dir.join(sub);
551            if p.is_dir() {
552                dirs_to_scan.push(p);
553            }
554        }
555        dirs_to_scan.push(dir);
556    }
557
558    // Project-local config dirs in CWD get the same backup treatment as HOME:
559    // setup writes (and uninstall removes) rules/hooks there too.
560    if let Ok(cwd) = std::env::current_dir() {
561        for rel in [
562            ".cursor/rules",
563            ".claude",
564            ".claude/rules",
565            ".claude/hooks",
566            ".codebuddy",
567            ".codebuddy/rules",
568            ".codebuddy/hooks",
569            ".kiro/steering",
570            ".github",
571            ".github/hooks",
572            ".vscode",
573        ] {
574            let p = cwd.join(rel);
575            if p.is_dir() {
576                dirs_to_scan.push(p);
577            }
578        }
579    }
580
581    dirs_to_scan
582}
583
584fn cleanup_bak_files(home: &Path) {
585    let dirs_to_scan = scan_dirs(home);
586    let mut cleaned = 0;
587    for dir in &dirs_to_scan {
588        if !dir.exists() {
589            continue;
590        }
591        if let Ok(entries) = fs::read_dir(dir) {
592            for entry in entries.flatten() {
593                let name = entry.file_name();
594                let name_str = name.to_string_lossy();
595                if name_str.ends_with(".lean-ctx.tmp") {
596                    let _ = fs::remove_file(entry.path());
597                    cleaned += 1;
598                    continue;
599                }
600                // Backups of our own hook scripts / rules files
601                // (lean-ctx-rewrite.sh.bak, lean-ctx.mdc.bak, …): the originals
602                // are lean-ctx-owned and already removed at this point, so the
603                // backups are pure leftovers.
604                if name_str.ends_with(".bak")
605                    && (name_str.starts_with("lean-ctx-") || name_str.starts_with("lean-ctx."))
606                {
607                    let _ = fs::remove_file(entry.path());
608                    cleaned += 1;
609                    continue;
610                }
611                if name_str.contains(".lean-ctx.invalid.") && name_str.ends_with(".bak") {
612                    let _ = fs::remove_file(entry.path());
613                    cleaned += 1;
614                    continue;
615                }
616                if name_str.ends_with(".lean-ctx.bak") {
617                    let original_name = name_str.trim_end_matches(".lean-ctx.bak");
618                    let original = entry.path().with_file_name(original_name);
619                    if original.exists() {
620                        match fs::read_to_string(&original) {
621                            Ok(c) if !c.contains("lean-ctx") => {
622                                let _ = fs::remove_file(entry.path());
623                                cleaned += 1;
624                            }
625                            _ => {}
626                        }
627                    } else {
628                        let _ = fs::remove_file(entry.path());
629                        cleaned += 1;
630                    }
631                    continue;
632                }
633                // Plain .bak files next to known config files (created by
634                // config_io). Removed whether or not the original still exists:
635                // when uninstall deletes a config file that only contained
636                // lean-ctx content, its backup would otherwise be orphaned.
637                if name_str.ends_with(".bak")
638                    && !name_str.contains(".lean-ctx")
639                    && let Ok(bak_content) = fs::read_to_string(entry.path())
640                    && bak_content.contains("lean-ctx")
641                {
642                    let _ = fs::remove_file(entry.path());
643                    cleaned += 1;
644                }
645            }
646        }
647    }
648
649    // Also clean shell RC backups
650    let rc_baks = [
651        home.join(".zshrc.lean-ctx.bak"),
652        home.join(".zshenv.lean-ctx.bak"),
653        home.join(".bashrc.lean-ctx.bak"),
654        home.join(".bashenv.lean-ctx.bak"),
655    ];
656    for bak in &rc_baks {
657        if bak.exists() {
658            let original_name = bak
659                .file_name()
660                .unwrap_or_default()
661                .to_string_lossy()
662                .trim_end_matches(".lean-ctx.bak")
663                .to_string();
664            let original = bak.with_file_name(original_name);
665            if original.exists() {
666                if let Ok(c) = fs::read_to_string(&original)
667                    && !c.contains("lean-ctx")
668                {
669                    let _ = fs::remove_file(bak);
670                    cleaned += 1;
671                }
672            } else {
673                let _ = fs::remove_file(bak);
674                cleaned += 1;
675            }
676        }
677    }
678
679    if cleaned > 0 {
680        println!("  ✓ Cleaned up {cleaned} backup file(s)");
681    }
682}
683
684/// Sweep now-empty installer-created directories (hooks/, rules/, skills/,
685/// steering/). `fs::remove_dir` refuses to delete non-empty directories, so
686/// anything still holding user content survives untouched. Runs as the last
687/// filesystem step of `run()` — after every file-removal pass has finished.
688fn sweep_empty_installer_dirs(home: &Path) {
689    let mut swept = 0;
690    for dir in scan_dirs(home) {
691        let is_installer_dir = dir
692            .file_name()
693            .and_then(|n| n.to_str())
694            .is_some_and(|n| matches!(n, "hooks" | "rules" | "skills" | "steering"));
695        if is_installer_dir && fs::remove_dir(&dir).is_ok() {
696            swept += 1;
697        }
698    }
699    if swept > 0 {
700        println!("  ✓ Removed {swept} empty installer director(y/ies)");
701    }
702}
703
704#[cfg(test)]
705mod tests {
706    use super::*;
707    use std::collections::HashSet;
708
709    fn args(list: &[&str]) -> Vec<String> {
710        list.iter().map(|s| (*s).to_string()).collect()
711    }
712
713    #[test]
714    fn parse_args_accepts_known_flags_and_rejects_typos() {
715        assert_eq!(parse_args(&[]), Ok((false, false, false)));
716        assert_eq!(
717            parse_args(&args(&["--keep-binary", "--dry-run", "--keep-config"])),
718            Ok((true, true, true))
719        );
720        for bad in ["--dry-rnu", "--keep", "yes", "-y"] {
721            let err = parse_args(&args(&["--dry-run", bad])).unwrap_err();
722            assert!(err.contains(&format!("'{bad}'")), "{err}");
723            assert!(err.contains("nothing was removed"), "{err}");
724            assert!(err.contains("lean-ctx uninstall --help"), "{err}");
725        }
726    }
727
728    #[test]
729    fn remove_rules_files_cleans_loaded_and_legacy_pi_antigravity_codex_rules() {
730        let _lock = lean_ctx::core::data_dir::test_env_lock();
731        let tmp = tempfile::tempdir().unwrap();
732        let home = tmp.path();
733        let _pi = lean_ctx::test_env::EnvVarGuard::set(
734            "PI_CODING_AGENT_DIR",
735            home.join("custom-pi").to_string_lossy().as_ref(),
736        );
737        let _codex = lean_ctx::test_env::EnvVarGuard::set(
738            "CODEX_HOME",
739            home.join(".codex").to_string_lossy().as_ref(),
740        );
741        let block = format!(
742            "{}\nrules\n{}\n",
743            lean_ctx::core::rules_canonical::START_MARK,
744            lean_ctx::core::rules_canonical::END_MARK
745        );
746        let write = |rel: &str, body: &str| {
747            let path = home.join(rel);
748            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
749            std::fs::write(path, body).unwrap();
750        };
751        // Setup ran with the default Pi dir; uninstall sees the override too.
752        write(".pi/agent/AGENTS.md", &format!("# Mine\n\n{block}"));
753        write("custom-pi/AGENTS.md", &block);
754        write(".gemini/AGENTS.md", &block);
755        write(
756            ".gemini/config/rules/lean-ctx.md",
757            &format!("---\ntrigger: always_on\n---\n\n{block}"),
758        );
759        write(".codex/instructions.md", &block);
760        write(".pi/rules/lean-ctx.md", &format!("lean-ctx\n{block}"));
761        write(
762            ".gemini/antigravity/rules/lean-ctx.md",
763            &format!("lean-ctx\n{block}"),
764        );
765
766        assert!(remove_rules_files(home, false));
767
768        let pi = std::fs::read_to_string(home.join(".pi/agent/AGENTS.md")).unwrap();
769        assert_eq!(pi.trim(), "# Mine", "Pi user content survives: {pi}");
770        for gone in [
771            ".gemini/AGENTS.md",
772            "custom-pi/AGENTS.md",
773            ".gemini/config/rules/lean-ctx.md",
774            ".codex/instructions.md",
775            ".pi/rules/lean-ctx.md",
776            ".gemini/antigravity/rules/lean-ctx.md",
777        ] {
778            assert!(!home.join(gone).exists(), "{gone} must be removed");
779        }
780    }
781
782    /// Antigravity's `~/.gemini/AGENTS.md` only ever held a marked block, so
783    /// a pre-v13 heading plus a quoted end marker in the user's own text is
784    /// not a lean-ctx block and stays.
785    #[test]
786    fn marker_only_shared_file_ignores_heading_and_quoted_end_marker() {
787        let _lock = lean_ctx::core::data_dir::test_env_lock();
788        let tmp = tempfile::tempdir().unwrap();
789        let home = tmp.path();
790        let path = home.join(".gemini/AGENTS.md");
791        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
792        let mine = format!(
793            "# Context Engineering Layer\nMy notes on lean-ctx: its block ends with `{}`.\n\n## Keep\nthis\n",
794            lean_ctx::core::rules_canonical::END_MARK
795        );
796        std::fs::write(&path, &mine).unwrap();
797
798        remove_rules_files(home, false);
799
800        assert_eq!(std::fs::read_to_string(&path).unwrap(), mine);
801    }
802
803    /// A shared file whose lean-ctx block lost its end line keeps every
804    /// byte: the block's extent is unknown, and the user's text after the
805    /// start marker would otherwise go together with the backup.
806    #[test]
807    fn shared_file_with_unterminated_block_is_left_untouched() {
808        let _lock = lean_ctx::core::data_dir::test_env_lock();
809        let tmp = tempfile::tempdir().unwrap();
810        let home = tmp.path();
811        let _codex = lean_ctx::test_env::EnvVarGuard::set(
812            "CODEX_HOME",
813            home.join(".codex").to_string_lossy().as_ref(),
814        );
815        let path = home.join(".config/opencode/AGENTS.md");
816        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
817        let mine = format!(
818            "# Mine\nintro\n{}\nold rule\n\nMy own paragraph\nkeep me\n## My heading\ntail\n",
819            lean_ctx::core::rules_canonical::START_MARK
820        );
821        std::fs::write(&path, &mine).unwrap();
822
823        remove_rules_files(home, false);
824
825        assert_eq!(std::fs::read_to_string(&path).unwrap(), mine);
826    }
827
828    /// Setup appends the shared block to a CRLF file; uninstall must give
829    /// back the exact bytes, so repeated cycles do not grow blank lines.
830    #[test]
831    fn crlf_shared_file_install_uninstall_round_trip_is_byte_stable() {
832        let _lock = lean_ctx::core::data_dir::test_env_lock();
833        let tmp = tempfile::tempdir().unwrap();
834        let home = tmp.path();
835        let _codex = lean_ctx::test_env::EnvVarGuard::set(
836            "CODEX_HOME",
837            home.join(".codex").to_string_lossy().as_ref(),
838        );
839        let path = home.join(".config/opencode/AGENTS.md");
840        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
841        let original = "# Mine\r\nnotes\r\n\r\n## After\r\nkeep\r\n";
842        let fresh = lean_ctx::rules_inject::rules_shared_content();
843        std::fs::write(&path, original).unwrap();
844
845        for _ in 0..2 {
846            let current = std::fs::read_to_string(&path).unwrap();
847            let installed =
848                lean_ctx::core::rules_canonical::RulesFile::parse(&current).merged_with(&fresh);
849            std::fs::write(&path, installed).unwrap();
850            remove_rules_files(home, false);
851            assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
852        }
853    }
854
855    /// A dedicated rules file is deleted only for the lean-ctx marker line;
856    /// the user's notes beside the block survive, and a file that merely
857    /// mentions lean-ctx is not ours.
858    #[test]
859    fn dedicated_rules_file_needs_the_marker_line_and_keeps_user_notes() {
860        let _lock = lean_ctx::core::data_dir::test_env_lock();
861        let tmp = tempfile::tempdir().unwrap();
862        let home = tmp.path();
863        let dir = home.join(".cline/rules");
864        std::fs::create_dir_all(&dir).unwrap();
865        let mention = dir.join("lean-ctx.md");
866        std::fs::write(&mention, "# My lean-ctx cheat sheet\n").unwrap();
867        let roo = home.join(".roo/rules/lean-ctx.md");
868        std::fs::create_dir_all(roo.parent().unwrap()).unwrap();
869        std::fs::write(
870            &roo,
871            format!(
872                "# My notes\n\n{}\nrules\n{}\n",
873                lean_ctx::core::rules_canonical::START_MARK,
874                lean_ctx::core::rules_canonical::END_MARK
875            ),
876        )
877        .unwrap();
878
879        remove_rules_files(home, false);
880
881        assert_eq!(
882            std::fs::read_to_string(&mention).unwrap(),
883            "# My lean-ctx cheat sheet\n"
884        );
885        assert_eq!(std::fs::read_to_string(&roo).unwrap(), "# My notes\n");
886    }
887
888    #[test]
889    fn data_dirs_to_remove_covers_canonical_xdg_categories() {
890        // `core::paths::*_dir()` reads the (test-sandboxed) data-dir env, which a
891        // parallel `isolated_data_dir()` repoints under `test_env_lock`. We resolve
892        // those dirs twice — once inside `data_dirs_to_remove` and once in the
893        // assertion loop — so without the lock the value can flip between the two
894        // reads (override active → dropped) and the set won't contain the second
895        // value. Hold the lock so the env stays fixed across both reads (#991).
896        let _lock = lean_ctx::core::data_dir::test_env_lock();
897        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
898        let dirs = data_dirs_to_remove(&home);
899
900        // Legacy single-dir + pre-split config dir are always targeted.
901        assert!(dirs.contains(&home.join(".lean-ctx")));
902        assert!(dirs.contains(&home.join(".config/lean-ctx")));
903
904        // Regression guard for the macOS data/state/cache leak (#uninstall-completeness):
905        // the set MUST include whatever core::paths actually resolves for every XDG
906        // category. The old dirs::data_dir()-based code missed these — on macOS they
907        // collapse onto Application Support — leaving the real ~/.local/share +
908        // ~/.local/state + ~/.cache (>150 MB) behind after a "full" uninstall.
909        for resolved in [
910            lean_ctx::core::paths::config_dir(),
911            lean_ctx::core::paths::data_dir(),
912            lean_ctx::core::paths::state_dir(),
913            lean_ctx::core::paths::cache_dir(),
914        ]
915        .into_iter()
916        .flatten()
917        {
918            assert!(
919                dirs.contains(&resolved),
920                "uninstall would NOT remove canonical dir: {}",
921                resolved.display()
922            );
923        }
924
925        // Each directory is listed exactly once (removed once, no churn).
926        let mut seen = HashSet::new();
927        for d in &dirs {
928            assert!(seen.insert(d.clone()), "duplicate dir: {}", d.display());
929        }
930    }
931
932    /// #2175 review: the live config migration journal, an unfinished
933    /// receipt update and the archived journals
934    /// (`*.v4-migration.[original.]<sha16>.*`) all live beside the config, so
935    /// uninstall removes them in the same pass as the config directory —
936    /// archives are handled exactly like the live journal.
937    #[test]
938    fn config_migration_journals_and_archives_go_with_the_config_dir() {
939        let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
940        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
941        let config = lean_ctx::core::config::Config::path().expect("isolated config path");
942        fs::create_dir_all(config.parent().unwrap()).unwrap();
943        fs::write(&config, "compression_level = \"standard\"\n").unwrap();
944        let (backup, receipt) =
945            lean_ctx::config_io::config_migration_journal_files(&config).unwrap();
946        let next = lean_ctx::config_io::config_migration_next_receipt_file(&config).unwrap();
947        let archive =
948            backup.with_file_name("config.toml.v4-migration.original.0123456789abcdef.bak");
949        let removed: Vec<PathBuf> = data_dirs_to_remove(&home)
950            .iter()
951            .filter_map(|dir| dir.canonicalize().ok())
952            .collect();
953        for file in [&backup, &receipt, &next, &archive] {
954            let parent = file.parent().unwrap().canonicalize().unwrap();
955            assert!(
956                removed.iter().any(|dir| parent.starts_with(dir)),
957                "uninstall would leave {} behind",
958                file.display()
959            );
960        }
961    }
962}