1macro_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 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
39static 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
95pub(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 cleanup_bak(path);
103 Ok(())
104}
105
106pub(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
119pub(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 cleanup_bak(path);
127 Ok(())
128}
129
130pub 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
168pub 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#[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 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 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 if !dry_run {
291 sweep_empty_installer_dirs(&home);
292 }
293
294 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
307fn finished(leftovers: usize, dry_run: bool) -> bool {
309 dry_run || leftovers == 0
310}
311
312fn 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
352pub(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 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
384fn 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 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 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
439fn 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 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 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 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 _ => {} }
549}
550
551fn 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 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 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 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 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 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
747fn 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 #[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 let none = summary_lines(false, 1, false, false, "uninstall").join("\n");
790 assert!(!none.contains("Nothing to remove"), "{none}");
791 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 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 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 #[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 #[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 #[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(¤t).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 #[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 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 assert!(dirs.contains(&home.join(".lean-ctx")));
1006 assert!(dirs.contains(&home.join(".config/lean-ctx")));
1007
1008 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 let mut seen = HashSet::new();
1031 for d in &dirs {
1032 assert!(seen.insert(d.clone()), "duplicate dir: {}", d.display());
1033 }
1034 }
1035
1036 #[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}