lean-ctx 3.12.12

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
// SPDX-License-Identifier: Apache-2.0

/// Something uninstall could not remove or clean: one plain line on
/// stderr (the CLI logs only errors), and counted so the summary never
/// claims a clean removal.
macro_rules! leftover {
    ($($arg:tt)*) => {
        $crate::uninstall::report_leftover(&format!($($arg)*))
    };
}

mod agents;
mod binary;
mod parsers;

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

use agents::{
    remove_hook_files, remove_mcp_configs, remove_plan_mode_settings, remove_project_agent_files,
    remove_rules_files, remove_shell_hook,
};

pub(super) fn backup_before_modify(path: &Path, dry_run: bool) {
    if dry_run {
        return;
    }
    if path.exists() {
        // GHSA-x992-2945-crwx: a cloned repository can ship
        // `<file>.lean-ctx.bak` as a symlink; never write the backup through it.
        let bak = bak_path_for(path);
        if let Ok(bytes) = fs::read(path) {
            let _ = lean_ctx::config_io::write_backup_nofollow(path, &bak, &bytes);
        }
    }
}

/// What this run left in place (see [`leftover!`]).
static LEFTOVERS: AtomicUsize = AtomicUsize::new(0);

pub(crate) fn report_leftover(message: &str) {
    LEFTOVERS.fetch_add(1, Ordering::Relaxed);
    eprintln!("  ! {message}");
}

pub fn bak_path_for(path: &Path) -> PathBuf {
    let filename = path.file_name().unwrap_or_default().to_string_lossy();
    path.with_file_name(format!("{filename}.lean-ctx.bak"))
}

fn cleanup_bak(path: &Path) {
    let bak = bak_path_for(path);
    if bak.exists() {
        let _ = fs::remove_file(&bak);
    }
}

pub(super) fn shorten(path: &Path, home: &Path) -> String {
    match path.strip_prefix(home) {
        Ok(rel) => format!("~/{}", rel.display()),
        Err(_) => path.display().to_string(),
    }
}

pub(super) fn copilot_instructions_path(home: &Path) -> PathBuf {
    #[cfg(target_os = "macos")]
    {
        return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
    }
    #[cfg(target_os = "linux")]
    {
        let user_dirs = [
            home.join(".config/Code/User"),
            home.join(".config/Code - Insiders/User"),
            home.join(".vscode-server/data/User"),
        ];
        let user_dir = user_dirs
            .iter()
            .find(|p| p.exists())
            .cloned()
            .unwrap_or_else(|| user_dirs[0].clone());
        return user_dir.join("github-copilot-instructions.md");
    }
    #[cfg(target_os = "windows")]
    {
        if let Ok(appdata) = std::env::var("APPDATA") {
            return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
        }
    }
    #[allow(unreachable_code)]
    home.join(".config/Code/User/github-copilot-instructions.md")
}

/// Write `content` to `path` only if not in dry-run mode.
pub(super) fn safe_write(path: &Path, content: &str, dry_run: bool) -> Result<(), std::io::Error> {
    if dry_run {
        return Ok(());
    }
    fs::write(path, content)?;
    // If we successfully wrote the cleaned file, the backup is no longer needed.
    cleanup_bak(path);
    Ok(())
}

/// Rewrite a rules file only if not in dry-run mode: atomically (temp file +
/// rename), owner-only, and through a symlink only when it stays within
/// `$HOME` — the writer setup uses. The caller already took the
/// `.lean-ctx.bak` copy, which goes once the write succeeded.
pub(super) fn safe_write_rules(path: &Path, content: &str, dry_run: bool) -> Result<(), String> {
    if dry_run {
        return Ok(());
    }
    lean_ctx::config_io::write_atomic(path, content)?;
    cleanup_bak(path);
    Ok(())
}

/// Remove `path` only if not in dry-run mode.
pub(super) fn safe_remove(path: &Path, dry_run: bool) -> Result<(), std::io::Error> {
    if dry_run {
        return Ok(());
    }
    fs::remove_file(path)?;
    // If we successfully removed the file, also remove its backup.
    cleanup_bak(path);
    Ok(())
}

// ---------------------------------------------------------------------------
// Help
// ---------------------------------------------------------------------------

/// Print usage for `lean-ctx uninstall`.
///
/// This MUST stay side-effect free: `lean-ctx uninstall --help` previously fell
/// through to [`run`] and removed everything, so help is now short-circuited in
/// the CLI dispatch before any removal happens.
pub fn print_help() {
    println!(
        "\
lean-ctx uninstall — remove lean-ctx cleanly

USAGE:
    lean-ctx uninstall [OPTIONS]

OPTIONS:
    --dry-run        Preview every change without modifying anything
    --keep-config    Preserve MCP configs and rules (for a later reinstall)
    --keep-binary    Leave the lean-ctx binary in place
    -h, --help       Show this help and exit (does NOT uninstall)

WHAT IT REMOVES:
    • Running processes (daemon, proxy) and autostart entries
    • Shell hooks and proxy environment from your shell rc files
    • MCP server configs and rules from every detected AI tool/IDE
    • Skill directories and project integration files
    • The data directory and the lean-ctx binary

    Modified files are backed up as <file>.lean-ctx.bak before removal.

EXAMPLES:
    lean-ctx uninstall --dry-run     # see exactly what would change
    lean-ctx uninstall               # full clean removal"
    );
}

/// Options of `lean-ctx uninstall`: `(dry_run, keep_config, keep_binary)`.
///
/// Every argument must be a known flag. A typo such as `--dry-rnu` used to be
/// ignored and ran a full, irreversible uninstall; it is now an error.
pub fn parse_args(rest: &[String]) -> Result<(bool, bool, bool), String> {
    let (mut dry_run, mut keep_config, mut keep_binary) = (false, false, false);
    for arg in rest {
        match arg.as_str() {
            "--dry-run" => dry_run = true,
            "--keep-config" => keep_config = true,
            "--keep-binary" => keep_binary = true,
            other => {
                return Err(format!(
                    "lean-ctx uninstall: unknown argument '{other}'; nothing was removed.\n\
                     Usage: lean-ctx uninstall [--dry-run] [--keep-config] [--keep-binary] \
                     (see: lean-ctx uninstall --help)"
                ));
            }
        }
    }
    Ok((dry_run, keep_config, keep_binary))
}

// ---------------------------------------------------------------------------
// Main entry
// ---------------------------------------------------------------------------

/// Returns whether the uninstall finished: `false` when items were left
/// (or the home directory is unknown), so the command exits non-zero.
#[must_use]
pub fn run(dry_run: bool, keep_config: bool, keep_binary: bool) -> bool {
    let Some(home) = dirs::home_dir() else {
        eprintln!(
            "lean-ctx uninstall: could not determine the home directory; nothing was removed."
        );
        return false;
    };
    LEFTOVERS.store(0, Ordering::Relaxed);

    let mode_label = if keep_config {
        "uninstall --keep-config"
    } else {
        "uninstall"
    };

    if dry_run {
        println!("\n  lean-ctx {mode_label} --dry-run\n  ──────────────────────────────────\n");
        println!("  Preview mode — no files will be modified.\n");
    } else {
        println!("\n  lean-ctx {mode_label}\n  ──────────────────────────────────\n");
    }

    if keep_config {
        println!("  Mode: keep-config (MCP configs and rules preserved for reinstall)\n");
    }

    // Stop everything first so nothing respawns or holds the files/data we remove next.
    binary::stop_processes(dry_run);

    let mut removed_any = false;

    removed_any |= remove_shell_hook(&home, dry_run);
    if dry_run {
        crate::proxy_setup::preview_proxy_cleanup(&home);
    } else {
        crate::proxy_setup::uninstall_proxy_env(&home, false);
    }

    if keep_config {
        println!("  · Skipped: MCP configs (--keep-config)");
        println!("  · Skipped: Rules files (--keep-config)");
    } else {
        removed_any |= remove_mcp_configs(&home, dry_run);
        removed_any |= remove_rules_files(&home, dry_run);
        if !dry_run {
            try_claude_mcp_remove();
        }
    }

    removed_any |= remove_hook_files(&home, dry_run);
    removed_any |= remove_plan_mode_settings(&home, dry_run);
    removed_any |= remove_skill_dirs(&home, dry_run);
    removed_any |= remove_project_agent_files(dry_run);

    if dry_run {
        println!("  Would remove proxy autostart (LaunchAgent/systemd)");
        println!("  Would remove daemon autostart (LaunchAgent/systemd)");
        println!("  Would remove auto-update schedule (LaunchAgent/systemd/Task)");
    } else {
        lean_ctx::proxy_autostart::uninstall(true);
        lean_ctx::daemon_autostart::uninstall(true);
        // The 6-hourly self-update agent (com.leanctx.autoupdate) is a *separate*
        // autostart entry from daemon/proxy. Without this it survives uninstall and
        // keeps relaunching the now-deleted binary every 6h. remove_schedule() is the
        // same idempotent routine used elsewhere (macOS/Linux/Windows aware).
        // Another instance's schedule (the default install's) is left
        // alone on purpose: not a leftover of this uninstall.
        let had_schedule = lean_ctx::core::update_scheduler::schedule_status().enabled;
        match lean_ctx::core::update_scheduler::remove_schedule() {
            Ok(()) if had_schedule => {
                println!("  ✓ Auto-update schedule removed");
                removed_any = true;
            }
            Ok(()) => {}
            Err(_) if !lean_ctx::daemon_autostart::controls_user_services() => {
                println!(
                    "  · Auto-update schedule: {}",
                    lean_ctx::daemon_autostart::not_this_instance_message()
                );
            }
            Err(e) => leftover!("Failed to remove auto-update schedule: {e}"),
        }
    }

    if !dry_run {
        cleanup_bak_files(&home);
    }

    removed_any |= remove_data_dir(&home, dry_run);

    // Last filesystem step: every file-removal pass above has run, so
    // installer-created directories that are empty now stay empty.
    if !dry_run {
        sweep_empty_installer_dirs(&home);
    }

    // Remove the binary itself last: once it's gone we can't re-exec, and on Unix the
    // running process keeps working until exit.
    removed_any |= binary::remove_binaries(&home, dry_run, keep_binary);

    println!();

    let leftovers = LEFTOVERS.swap(0, Ordering::Relaxed);
    for line in summary_lines(removed_any, leftovers, dry_run, keep_config, mode_label) {
        println!("{line}");
    }
    finished(leftovers, dry_run)
}

/// A preview always finishes; a real run only when nothing was left.
fn finished(leftovers: usize, dry_run: bool) -> bool {
    dry_run || leftovers == 0
}

/// The closing block. Any leftover (a file it could not clean or remove)
/// replaces the success words: uninstall never claims a clean removal it
/// did not do.
fn summary_lines(
    removed_any: bool,
    leftovers: usize,
    dry_run: bool,
    keep_config: bool,
    mode_label: &str,
) -> Vec<String> {
    let rule = "  ──────────────────────────────────".to_string();
    if !dry_run && leftovers > 0 {
        let what = if leftovers == 1 { "item" } else { "items" };
        return vec![
            rule,
            format!(
                "  lean-ctx was NOT fully removed: {leftovers} {what} could not be cleaned (listed above).\n  \
                 Fix them (permissions, open files) and run `lean-ctx {mode_label}` again.\n"
            ),
        ];
    }
    if !removed_any {
        return vec!["  Nothing to remove — lean-ctx was not configured.\n".into()];
    }
    let done = if dry_run {
        format!(
            "  The above changes WOULD be applied.\n  Run `lean-ctx {mode_label}` to execute.\n"
        )
    } else if keep_config {
        "  Runtime data removed. MCP configs preserved for reinstall.\n  \
         Reinstall with: cargo install lean-ctx\n"
            .into()
    } else {
        "  lean-ctx fully removed. Restart your shell to drop stale aliases.\n  \
         Verify with: command -v lean-ctx   # should print nothing\n"
            .into()
    };
    vec![rule, done]
}

// ---------------------------------------------------------------------------
// Marked block removal (for AGENTS.md, SharedMarkdown)
// ---------------------------------------------------------------------------

/// Remove the block from the `start` marker line through the first `end`
/// marker line after it. Markers count only as whole lines (GL #1158): a
/// marker quoted inside user prose is user text, and without an end line
/// after the start the content is returned unchanged.
pub(super) fn remove_marked_block(content: &str, start: &str, end: &str) -> String {
    use lean_ctx::marked_block::marker_line_span;
    let span = marker_line_span(content, start).and_then(|(si, after_start)| {
        marker_line_span(&content[after_start..], end).map(|(_, e)| (si, after_start + e))
    });
    match span {
        Some((si, after_end)) => {
            let before = &content[..si];
            let after = &content[after_end..];
            let mut out = String::new();
            // `\r` too: in a CRLF file a `\n`-only trim stops at the `\r`,
            // and every install/uninstall cycle would add blank lines.
            out.push_str(before.trim_end_matches(['\r', '\n']));
            out.push('\n');
            if !after.trim().is_empty() {
                out.push('\n');
                out.push_str(after.trim_start_matches(['\r', '\n']));
            }
            out
        }
        _ => content.to_string(),
    }
}

// ---------------------------------------------------------------------------
// Skill directories: lean-ctx SKILL.md + scripts
// ---------------------------------------------------------------------------

fn remove_skill_dirs(home: &Path, dry_run: bool) -> bool {
    let claude_state = lean_ctx::core::editor_registry::claude_state_dir(home);
    let codebuddy_state = lean_ctx::core::editor_registry::codebuddy_state_dir(home);
    let mut skill_dirs: Vec<(&str, PathBuf)> = vec![
        ("Claude Code", claude_state.join("skills/lean-ctx")),
        ("CodeBuddy", codebuddy_state.join("skills/lean-ctx")),
        ("Cursor", home.join(".cursor/skills/lean-ctx")),
        (
            "Codex CLI",
            lean_ctx::core::home::resolve_codex_dir()
                .unwrap_or_else(|| home.join(".codex"))
                .join("skills/lean-ctx"),
        ),
        ("Grok", home.join(".grok/skills/lean-ctx")),
        ("Copilot", home.join(".copilot/skills/lean-ctx")),
        ("OpenClaw", home.join(".openclaw/skills/lean-ctx")),
    ];

    // If CLAUDE_CONFIG_DIR differs from ~/.claude, also clean default path
    let default_claude_skill = home.join(".claude/skills/lean-ctx");
    if !skill_dirs.iter().any(|(_, p)| *p == default_claude_skill) {
        skill_dirs.push(("Claude Code (default)", default_claude_skill));
    }

    // If CODEBUDDY_CONFIG_DIR differs from ~/.codebuddy, also clean default path
    let default_codebuddy_skill = home.join(".codebuddy/skills/lean-ctx");
    if !skill_dirs
        .iter()
        .any(|(_, p)| *p == default_codebuddy_skill)
    {
        skill_dirs.push(("CodeBuddy (default)", default_codebuddy_skill));
    }

    let mut removed = false;
    for (name, dir) in &skill_dirs {
        if !dir.exists() {
            continue;
        }
        if dry_run {
            println!("  Would remove {name} skill directory");
            removed = true;
        } else if let Err(e) = fs::remove_dir_all(dir) {
            leftover!("Failed to remove {name} skill dir: {e}");
        } else {
            println!("  ✓ {name} skill directory removed");
            removed = true;
        }
    }
    removed
}

// ---------------------------------------------------------------------------
// Data directory
// ---------------------------------------------------------------------------

/// Every lean-ctx directory an uninstall must delete, de-duplicated and
/// order-preserving.
///
/// Historically this used `dirs::data_dir()` / `dirs::data_local_dir()`, which on
/// macOS both resolve to `~/Library/Application Support` — so the *real* runtime
/// dirs (`~/.local/share`, `~/.local/state`, `~/.cache`) were never removed and a
/// "full" uninstall left >150 MB of data + cache behind. We now resolve through the
/// exact same [`core::paths`](lean_ctx::core::paths) functions the daemon/proxy use,
/// so every XDG category (config/data/state/cache, honoring `LEAN_CTX_*_DIR` and
/// `XDG_*` overrides) is covered, plus the legacy single-dir and macOS
/// Application Support locations for older installs.
fn data_dirs_to_remove(home: &Path) -> Vec<PathBuf> {
    let mut dirs = vec![home.join(".lean-ctx"), home.join(".config/lean-ctx")];

    let push = |dirs: &mut Vec<PathBuf>, p: PathBuf| {
        if !dirs.contains(&p) {
            dirs.push(p);
        }
    };

    // Canonical XDG categories actually written at runtime.
    for resolved in [
        lean_ctx::core::paths::config_dir(),
        lean_ctx::core::paths::data_dir(),
        lean_ctx::core::paths::state_dir(),
        lean_ctx::core::paths::cache_dir(),
    ]
    .into_iter()
    .flatten()
    {
        push(&mut dirs, resolved);
    }

    // Older installs (and Windows %LOCALAPPDATA%) may have used the platform dir.
    for platform_dir in [dirs::data_local_dir(), dirs::data_dir()]
        .into_iter()
        .flatten()
    {
        push(&mut dirs, platform_dir.join("lean-ctx"));
    }

    dirs
}

fn remove_data_dir(home: &Path, dry_run: bool) -> bool {
    let mut removed = false;

    let dirs_to_remove = data_dirs_to_remove(home);

    for data_dir in &dirs_to_remove {
        if !data_dir.exists() {
            continue;
        }
        let short = shorten(data_dir, home);
        if dry_run {
            println!("  Would remove data directory ({short})");
            removed = true;
            continue;
        }
        match fs::remove_dir_all(data_dir) {
            Ok(()) => {
                println!("  ✓ Data directory removed ({short})");
                removed = true;
            }
            Err(e) => leftover!("Failed to remove {short}: {e}"),
        }
    }

    // Project-local .lean-ctx/ and .lean-ctx-id in CWD
    if let Ok(cwd) = std::env::current_dir() {
        let project_dir = cwd.join(".lean-ctx");
        let project_id = cwd.join(".lean-ctx-id");
        for p in [&project_dir, &project_id] {
            if p.exists() {
                if dry_run {
                    println!("  Would remove {}", p.display());
                    removed = true;
                } else if p.is_dir() {
                    if fs::remove_dir_all(p).is_ok() {
                        println!("  ✓ Removed {}", p.display());
                        removed = true;
                    }
                } else if fs::remove_file(p).is_ok() {
                    println!("  ✓ Removed {}", p.display());
                    removed = true;
                }
            }
        }
    }

    if !removed {
        println!("  · No data directory found");
    }
    removed
}

fn try_claude_mcp_remove() {
    let result = std::process::Command::new("claude")
        .args(["mcp", "remove", "lean-ctx", "--scope", "user"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
    match result {
        Ok(s) if s.success() => println!("  ✓ Removed lean-ctx from Claude MCP registry"),
        _ => {} // claude CLI not available or already removed
    }
}

// ---------------------------------------------------------------------------
// .bak cleanup: remove orphaned backup files after successful surgical removal
// ---------------------------------------------------------------------------

/// Every directory the installer may have written backups or files into:
/// agent config roots, their well-known subdirectories, and the project-local
/// config dirs in CWD.
fn scan_dirs(home: &Path) -> Vec<PathBuf> {
    let base_dirs: Vec<PathBuf> = vec![
        home.join(".cursor"),
        home.join(".claude"),
        lean_ctx::core::editor_registry::claude_state_dir(home),
        home.join(".codebuddy"),
        lean_ctx::core::editor_registry::codebuddy_state_dir(home),
        lean_ctx::core::editor_registry::zed_config_dir(home),
        home.join(".gemini"),
        home.join(".gemini/antigravity"),
        home.join(".gemini/antigravity-cli"),
        lean_ctx::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex")),
        home.join(".codeium"),
        home.join(".codeium/windsurf"),
        home.join(".config/opencode"),
        home.join(".config/amp"),
        home.join(".config/crush"),
        home.join(".config/zed"),
        home.join(".qwen"),
        home.join(".trae"),
        home.join(".codewhale"),
        home.join(".deepseek"),
        lean_ctx::core::editor_registry::muse_config_dir(home),
        home.join(".aws/amazonq"),
        home.join(".kiro"),
        home.join(".kiro/settings"),
        home.join(".ampcoder"),
        home.join(".pi"),
        home.join(".pi/agent"),
        home.join(".hermes"),
        home.join(".grok"),
        home.join(".verdent"),
        home.join(".cline"),
        home.join(".roo"),
        home.join(".continue"),
        home.join(".jb-rules"),
        home.join(".openclaw"),
        home.join(".augment"),
        home.join(".qoder"),
        home.join(".qoderwork"),
        home.join(".aider"),
        home.join(".emacs.d"),
        home.join(".copilot"),
        home.join(".github"),
        home.join(".config/mcphub"),
        home.join(".config/sublime-text"),
    ];

    // Installers write into well-known subdirectories (hook scripts, rules
    // files, steering docs, …). read_dir below is non-recursive, so backups in
    // those subdirectories were previously missed (GL #558).
    const KNOWN_SUBDIRS: [&str; 6] = ["hooks", "rules", "skills", "steering", "settings", "User"];
    let mut dirs_to_scan: Vec<PathBuf> = Vec::with_capacity(base_dirs.len() * 4);
    for dir in base_dirs {
        for sub in KNOWN_SUBDIRS {
            let p = dir.join(sub);
            if p.is_dir() {
                dirs_to_scan.push(p);
            }
        }
        dirs_to_scan.push(dir);
    }

    // Project-local config dirs in CWD get the same backup treatment as HOME:
    // setup writes (and uninstall removes) rules/hooks there too.
    if let Ok(cwd) = std::env::current_dir() {
        for rel in [
            ".cursor/rules",
            ".claude",
            ".claude/rules",
            ".claude/hooks",
            ".codebuddy",
            ".codebuddy/rules",
            ".codebuddy/hooks",
            ".kiro/steering",
            ".github",
            ".github/hooks",
            ".vscode",
        ] {
            let p = cwd.join(rel);
            if p.is_dir() {
                dirs_to_scan.push(p);
            }
        }
    }

    dirs_to_scan
}

fn cleanup_bak_files(home: &Path) {
    let dirs_to_scan = scan_dirs(home);
    let mut cleaned = 0;
    for dir in &dirs_to_scan {
        if !dir.exists() {
            continue;
        }
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy();
                if name_str.ends_with(".lean-ctx.tmp") {
                    let _ = fs::remove_file(entry.path());
                    cleaned += 1;
                    continue;
                }
                // Backups of our own hook scripts / rules files
                // (lean-ctx-rewrite.sh.bak, lean-ctx.mdc.bak, …): the originals
                // are lean-ctx-owned and already removed at this point, so the
                // backups are pure leftovers.
                if name_str.ends_with(".bak")
                    && (name_str.starts_with("lean-ctx-") || name_str.starts_with("lean-ctx."))
                {
                    let _ = fs::remove_file(entry.path());
                    cleaned += 1;
                    continue;
                }
                if name_str.contains(".lean-ctx.invalid.") && name_str.ends_with(".bak") {
                    let _ = fs::remove_file(entry.path());
                    cleaned += 1;
                    continue;
                }
                if name_str.ends_with(".lean-ctx.bak") {
                    let original_name = name_str.trim_end_matches(".lean-ctx.bak");
                    let original = entry.path().with_file_name(original_name);
                    if original.exists() {
                        match fs::read_to_string(&original) {
                            Ok(c) if !c.contains("lean-ctx") => {
                                let _ = fs::remove_file(entry.path());
                                cleaned += 1;
                            }
                            _ => {}
                        }
                    } else {
                        let _ = fs::remove_file(entry.path());
                        cleaned += 1;
                    }
                    continue;
                }
                // Plain .bak files next to known config files (created by
                // config_io). Removed whether or not the original still exists:
                // when uninstall deletes a config file that only contained
                // lean-ctx content, its backup would otherwise be orphaned.
                if name_str.ends_with(".bak")
                    && !name_str.contains(".lean-ctx")
                    && let Ok(bak_content) = fs::read_to_string(entry.path())
                    && bak_content.contains("lean-ctx")
                {
                    let _ = fs::remove_file(entry.path());
                    cleaned += 1;
                }
            }
        }
    }

    // Also clean shell RC backups
    let rc_baks = [
        home.join(".zshrc.lean-ctx.bak"),
        home.join(".zshenv.lean-ctx.bak"),
        home.join(".bashrc.lean-ctx.bak"),
        home.join(".bashenv.lean-ctx.bak"),
    ];
    for bak in &rc_baks {
        if bak.exists() {
            let original_name = bak
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .trim_end_matches(".lean-ctx.bak")
                .to_string();
            let original = bak.with_file_name(original_name);
            if original.exists() {
                if let Ok(c) = fs::read_to_string(&original)
                    && !c.contains("lean-ctx")
                {
                    let _ = fs::remove_file(bak);
                    cleaned += 1;
                }
            } else {
                let _ = fs::remove_file(bak);
                cleaned += 1;
            }
        }
    }

    if cleaned > 0 {
        println!("  ✓ Cleaned up {cleaned} backup file(s)");
    }
}

/// Sweep now-empty installer-created directories (hooks/, rules/, skills/,
/// steering/). `fs::remove_dir` refuses to delete non-empty directories, so
/// anything still holding user content survives untouched. Runs as the last
/// filesystem step of `run()` — after every file-removal pass has finished.
fn sweep_empty_installer_dirs(home: &Path) {
    let mut swept = 0;
    for dir in scan_dirs(home) {
        let is_installer_dir = dir
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| matches!(n, "hooks" | "rules" | "skills" | "steering"));
        if is_installer_dir && fs::remove_dir(&dir).is_ok() {
            swept += 1;
        }
    }
    if swept > 0 {
        println!("  ✓ Removed {swept} empty installer director(y/ies)");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    fn args(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| (*s).to_string()).collect()
    }

    /// MR !569 review: the CLI logs only errors, so a file uninstall could
    /// not clean is a plain line and the summary never claims success.
    #[test]
    fn uninstall_with_leftovers_does_not_claim_a_full_removal() {
        let clean = summary_lines(true, 0, false, false, "uninstall").join("\n");
        assert!(clean.contains("lean-ctx fully removed"));
        let left = summary_lines(true, 2, false, false, "uninstall").join("\n");
        assert!(!left.contains("lean-ctx fully removed"), "{left}");
        assert!(left.contains("NOT fully removed: 2 items"), "{left}");
        let kept = summary_lines(true, 1, false, true, "uninstall --keep-config").join("\n");
        assert!(!kept.contains("Runtime data removed"), "{kept}");
        assert!(kept.contains("1 item could not"), "{kept}");
        // Nothing removed but something left: still not "nothing to remove".
        let none = summary_lines(false, 1, false, false, "uninstall").join("\n");
        assert!(!none.contains("Nothing to remove"), "{none}");
        // The uninstall sources report failures through `leftover!`, not
        // through a WARN log record the CLI level hides.
        for (name, source) in [
            ("agents.rs", include_str!("agents.rs").replace("\r\n", "\n")),
            ("binary.rs", include_str!("binary.rs").replace("\r\n", "\n")),
            (
                "shell_init.rs",
                include_str!("../cli/shell_init.rs").replace("\r\n", "\n"),
            ),
        ] {
            assert!(!source.contains("tracing::warn!"), "{name}");
        }
        // Items left: the command exits non-zero after the summary.
        assert!(finished(0, false));
        assert!(!finished(2, false));
        assert!(finished(2, true));
        let dispatch = include_str!("../cli/dispatch/mod.rs").replace("\r\n", "\n");
        assert!(
            dispatch.contains("if !uninstall::run(dry_run, keep_config, keep_binary) {\n                            std::process::exit(1);"),
            "uninstall exits 0 with items left"
        );
        let before = LEFTOVERS.load(Ordering::Relaxed);
        report_leftover("test leftover");
        assert!(LEFTOVERS.load(Ordering::Relaxed) > before);
    }

    #[test]
    fn parse_args_accepts_known_flags_and_rejects_typos() {
        assert_eq!(parse_args(&[]), Ok((false, false, false)));
        assert_eq!(
            parse_args(&args(&["--keep-binary", "--dry-run", "--keep-config"])),
            Ok((true, true, true))
        );
        for bad in ["--dry-rnu", "--keep", "yes", "-y"] {
            let err = parse_args(&args(&["--dry-run", bad])).unwrap_err();
            assert!(err.contains(&format!("'{bad}'")), "{err}");
            assert!(err.contains("nothing was removed"), "{err}");
            assert!(err.contains("lean-ctx uninstall --help"), "{err}");
        }
    }

    #[test]
    fn remove_rules_files_cleans_loaded_and_legacy_pi_antigravity_codex_rules() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let _pi = lean_ctx::test_env::EnvVarGuard::set(
            "PI_CODING_AGENT_DIR",
            home.join("custom-pi").to_string_lossy().as_ref(),
        );
        let _codex = lean_ctx::test_env::EnvVarGuard::set(
            "CODEX_HOME",
            home.join(".codex").to_string_lossy().as_ref(),
        );
        let block = format!(
            "{}\nrules\n{}\n",
            lean_ctx::core::rules_canonical::START_MARK,
            lean_ctx::core::rules_canonical::END_MARK
        );
        let write = |rel: &str, body: &str| {
            let path = home.join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, body).unwrap();
        };
        // Setup ran with the default Pi dir; uninstall sees the override too.
        write(".pi/agent/AGENTS.md", &format!("# Mine\n\n{block}"));
        write("custom-pi/AGENTS.md", &block);
        write(".gemini/AGENTS.md", &block);
        write(
            ".gemini/config/rules/lean-ctx.md",
            &format!("---\ntrigger: always_on\n---\n\n{block}"),
        );
        write(".codex/instructions.md", &block);
        write(".pi/rules/lean-ctx.md", &format!("lean-ctx\n{block}"));
        write(
            ".gemini/antigravity/rules/lean-ctx.md",
            &format!("lean-ctx\n{block}"),
        );

        assert!(remove_rules_files(home, false));

        let pi = std::fs::read_to_string(home.join(".pi/agent/AGENTS.md")).unwrap();
        assert_eq!(pi.trim(), "# Mine", "Pi user content survives: {pi}");
        for gone in [
            ".gemini/AGENTS.md",
            "custom-pi/AGENTS.md",
            ".gemini/config/rules/lean-ctx.md",
            ".codex/instructions.md",
            ".pi/rules/lean-ctx.md",
            ".gemini/antigravity/rules/lean-ctx.md",
        ] {
            assert!(!home.join(gone).exists(), "{gone} must be removed");
        }
    }

    /// Antigravity's `~/.gemini/AGENTS.md` only ever held a marked block, so
    /// a pre-v13 heading plus a quoted end marker in the user's own text is
    /// not a lean-ctx block and stays.
    #[test]
    fn marker_only_shared_file_ignores_heading_and_quoted_end_marker() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let path = home.join(".gemini/AGENTS.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let mine = format!(
            "# Context Engineering Layer\nMy notes on lean-ctx: its block ends with `{}`.\n\n## Keep\nthis\n",
            lean_ctx::core::rules_canonical::END_MARK
        );
        std::fs::write(&path, &mine).unwrap();

        remove_rules_files(home, false);

        assert_eq!(std::fs::read_to_string(&path).unwrap(), mine);
    }

    /// A shared file whose lean-ctx block lost its end line keeps every
    /// byte: the block's extent is unknown, and the user's text after the
    /// start marker would otherwise go together with the backup.
    #[test]
    fn shared_file_with_unterminated_block_is_left_untouched() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let _codex = lean_ctx::test_env::EnvVarGuard::set(
            "CODEX_HOME",
            home.join(".codex").to_string_lossy().as_ref(),
        );
        let path = home.join(".config/opencode/AGENTS.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let mine = format!(
            "# Mine\nintro\n{}\nold rule\n\nMy own paragraph\nkeep me\n## My heading\ntail\n",
            lean_ctx::core::rules_canonical::START_MARK
        );
        std::fs::write(&path, &mine).unwrap();

        remove_rules_files(home, false);

        assert_eq!(std::fs::read_to_string(&path).unwrap(), mine);
    }

    /// Setup appends the shared block to a CRLF file; uninstall must give
    /// back the exact bytes, so repeated cycles do not grow blank lines.
    #[test]
    fn crlf_shared_file_install_uninstall_round_trip_is_byte_stable() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let _codex = lean_ctx::test_env::EnvVarGuard::set(
            "CODEX_HOME",
            home.join(".codex").to_string_lossy().as_ref(),
        );
        let path = home.join(".config/opencode/AGENTS.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        let original = "# Mine\r\nnotes\r\n\r\n## After\r\nkeep\r\n";
        let fresh = lean_ctx::rules_inject::rules_shared_content();
        std::fs::write(&path, original).unwrap();

        for _ in 0..2 {
            let current = std::fs::read_to_string(&path).unwrap();
            let installed =
                lean_ctx::core::rules_canonical::RulesFile::parse(&current).merged_with(&fresh);
            std::fs::write(&path, installed).unwrap();
            remove_rules_files(home, false);
            assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
        }
    }

    /// A dedicated rules file is deleted only for the lean-ctx marker line;
    /// the user's notes beside the block survive, and a file that merely
    /// mentions lean-ctx is not ours.
    #[test]
    fn dedicated_rules_file_needs_the_marker_line_and_keeps_user_notes() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let dir = home.join(".cline/rules");
        std::fs::create_dir_all(&dir).unwrap();
        let mention = dir.join("lean-ctx.md");
        std::fs::write(&mention, "# My lean-ctx cheat sheet\n").unwrap();
        let roo = home.join(".roo/rules/lean-ctx.md");
        std::fs::create_dir_all(roo.parent().unwrap()).unwrap();
        std::fs::write(
            &roo,
            format!(
                "# My notes\n\n{}\nrules\n{}\n",
                lean_ctx::core::rules_canonical::START_MARK,
                lean_ctx::core::rules_canonical::END_MARK
            ),
        )
        .unwrap();

        remove_rules_files(home, false);

        assert_eq!(
            std::fs::read_to_string(&mention).unwrap(),
            "# My lean-ctx cheat sheet\n"
        );
        assert_eq!(std::fs::read_to_string(&roo).unwrap(), "# My notes\n");
    }

    #[test]
    fn data_dirs_to_remove_covers_canonical_xdg_categories() {
        // `core::paths::*_dir()` reads the (test-sandboxed) data-dir env, which a
        // parallel `isolated_data_dir()` repoints under `test_env_lock`. We resolve
        // those dirs twice — once inside `data_dirs_to_remove` and once in the
        // assertion loop — so without the lock the value can flip between the two
        // reads (override active → dropped) and the set won't contain the second
        // value. Hold the lock so the env stays fixed across both reads (#991).
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
        let dirs = data_dirs_to_remove(&home);

        // Legacy single-dir + pre-split config dir are always targeted.
        assert!(dirs.contains(&home.join(".lean-ctx")));
        assert!(dirs.contains(&home.join(".config/lean-ctx")));

        // Regression guard for the macOS data/state/cache leak (#uninstall-completeness):
        // the set MUST include whatever core::paths actually resolves for every XDG
        // category. The old dirs::data_dir()-based code missed these — on macOS they
        // collapse onto Application Support — leaving the real ~/.local/share +
        // ~/.local/state + ~/.cache (>150 MB) behind after a "full" uninstall.
        for resolved in [
            lean_ctx::core::paths::config_dir(),
            lean_ctx::core::paths::data_dir(),
            lean_ctx::core::paths::state_dir(),
            lean_ctx::core::paths::cache_dir(),
        ]
        .into_iter()
        .flatten()
        {
            assert!(
                dirs.contains(&resolved),
                "uninstall would NOT remove canonical dir: {}",
                resolved.display()
            );
        }

        // Each directory is listed exactly once (removed once, no churn).
        let mut seen = HashSet::new();
        for d in &dirs {
            assert!(seen.insert(d.clone()), "duplicate dir: {}", d.display());
        }
    }

    /// #2175 review: the live config migration journal, an unfinished
    /// receipt update and the archived journals
    /// (`*.v4-migration.[original.]<sha16>.*`) all live beside the config, so
    /// uninstall removes them in the same pass as the config directory —
    /// archives are handled exactly like the live journal.
    #[test]
    fn config_migration_journals_and_archives_go_with_the_config_dir() {
        let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
        let config = lean_ctx::core::config::Config::path().expect("isolated config path");
        fs::create_dir_all(config.parent().unwrap()).unwrap();
        fs::write(&config, "compression_level = \"standard\"\n").unwrap();
        let (backup, receipt) =
            lean_ctx::config_io::config_migration_journal_files(&config).unwrap();
        let next = lean_ctx::config_io::config_migration_next_receipt_file(&config).unwrap();
        let archive =
            backup.with_file_name("config.toml.v4-migration.original.0123456789abcdef.bak");
        let removed: Vec<PathBuf> = data_dirs_to_remove(&home)
            .iter()
            .filter_map(|dir| dir.canonicalize().ok())
            .collect();
        for file in [&backup, &receipt, &next, &archive] {
            let parent = file.parent().unwrap().canonicalize().unwrap();
            assert!(
                removed.iter().any(|dir| parent.starts_with(dir)),
                "uninstall would leave {} behind",
                file.display()
            );
        }
    }
}