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