Skip to main content

lean_ctx_cli/uninstall/
mod.rs

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