1mod 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
72pub(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 cleanup_bak(path);
80 Ok(())
81}
82
83pub(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 cleanup_bak(path);
91 Ok(())
92}
93
94pub 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
132pub 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
155pub 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 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 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 if !dry_run {
241 sweep_empty_installer_dirs(&home);
242 }
243
244 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
272pub(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
297fn 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 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 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
352fn 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 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 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 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 _ => {} }
462}
463
464fn 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 lean_ctx::core::editor_registry::muse_config_dir(home),
494 home.join(".aws/amazonq"),
495 home.join(".kiro"),
496 home.join(".kiro/settings"),
497 home.join(".ampcoder"),
498 home.join(".pi"),
499 home.join(".pi/agent"),
500 home.join(".hermes"),
501 home.join(".grok"),
502 home.join(".verdent"),
503 home.join(".cline"),
504 home.join(".roo"),
505 home.join(".continue"),
506 home.join(".jb-rules"),
507 home.join(".openclaw"),
508 home.join(".augment"),
509 home.join(".qoder"),
510 home.join(".qoderwork"),
511 home.join(".aider"),
512 home.join(".emacs.d"),
513 home.join(".copilot"),
514 home.join(".github"),
515 home.join(".config/mcphub"),
516 home.join(".config/sublime-text"),
517 ];
518
519 const KNOWN_SUBDIRS: [&str; 6] = ["hooks", "rules", "skills", "steering", "settings", "User"];
523 let mut dirs_to_scan: Vec<PathBuf> = Vec::with_capacity(base_dirs.len() * 4);
524 for dir in base_dirs {
525 for sub in KNOWN_SUBDIRS {
526 let p = dir.join(sub);
527 if p.is_dir() {
528 dirs_to_scan.push(p);
529 }
530 }
531 dirs_to_scan.push(dir);
532 }
533
534 if let Ok(cwd) = std::env::current_dir() {
537 for rel in [
538 ".cursor/rules",
539 ".claude",
540 ".claude/rules",
541 ".claude/hooks",
542 ".codebuddy",
543 ".codebuddy/rules",
544 ".codebuddy/hooks",
545 ".kiro/steering",
546 ".github",
547 ".github/hooks",
548 ".vscode",
549 ] {
550 let p = cwd.join(rel);
551 if p.is_dir() {
552 dirs_to_scan.push(p);
553 }
554 }
555 }
556
557 dirs_to_scan
558}
559
560fn cleanup_bak_files(home: &Path) {
561 let dirs_to_scan = scan_dirs(home);
562 let mut cleaned = 0;
563 for dir in &dirs_to_scan {
564 if !dir.exists() {
565 continue;
566 }
567 if let Ok(entries) = fs::read_dir(dir) {
568 for entry in entries.flatten() {
569 let name = entry.file_name();
570 let name_str = name.to_string_lossy();
571 if name_str.ends_with(".lean-ctx.tmp") {
572 let _ = fs::remove_file(entry.path());
573 cleaned += 1;
574 continue;
575 }
576 if name_str.ends_with(".bak")
581 && (name_str.starts_with("lean-ctx-") || name_str.starts_with("lean-ctx."))
582 {
583 let _ = fs::remove_file(entry.path());
584 cleaned += 1;
585 continue;
586 }
587 if name_str.contains(".lean-ctx.invalid.") && name_str.ends_with(".bak") {
588 let _ = fs::remove_file(entry.path());
589 cleaned += 1;
590 continue;
591 }
592 if name_str.ends_with(".lean-ctx.bak") {
593 let original_name = name_str.trim_end_matches(".lean-ctx.bak");
594 let original = entry.path().with_file_name(original_name);
595 if original.exists() {
596 match fs::read_to_string(&original) {
597 Ok(c) if !c.contains("lean-ctx") => {
598 let _ = fs::remove_file(entry.path());
599 cleaned += 1;
600 }
601 _ => {}
602 }
603 } else {
604 let _ = fs::remove_file(entry.path());
605 cleaned += 1;
606 }
607 continue;
608 }
609 if name_str.ends_with(".bak")
614 && !name_str.contains(".lean-ctx")
615 && let Ok(bak_content) = fs::read_to_string(entry.path())
616 && bak_content.contains("lean-ctx")
617 {
618 let _ = fs::remove_file(entry.path());
619 cleaned += 1;
620 }
621 }
622 }
623 }
624
625 let rc_baks = [
627 home.join(".zshrc.lean-ctx.bak"),
628 home.join(".zshenv.lean-ctx.bak"),
629 home.join(".bashrc.lean-ctx.bak"),
630 home.join(".bashenv.lean-ctx.bak"),
631 ];
632 for bak in &rc_baks {
633 if bak.exists() {
634 let original_name = bak
635 .file_name()
636 .unwrap_or_default()
637 .to_string_lossy()
638 .trim_end_matches(".lean-ctx.bak")
639 .to_string();
640 let original = bak.with_file_name(original_name);
641 if original.exists() {
642 if let Ok(c) = fs::read_to_string(&original)
643 && !c.contains("lean-ctx")
644 {
645 let _ = fs::remove_file(bak);
646 cleaned += 1;
647 }
648 } else {
649 let _ = fs::remove_file(bak);
650 cleaned += 1;
651 }
652 }
653 }
654
655 if cleaned > 0 {
656 println!(" ✓ Cleaned up {cleaned} backup file(s)");
657 }
658}
659
660fn sweep_empty_installer_dirs(home: &Path) {
665 let mut swept = 0;
666 for dir in scan_dirs(home) {
667 let is_installer_dir = dir
668 .file_name()
669 .and_then(|n| n.to_str())
670 .is_some_and(|n| matches!(n, "hooks" | "rules" | "skills" | "steering"));
671 if is_installer_dir && fs::remove_dir(&dir).is_ok() {
672 swept += 1;
673 }
674 }
675 if swept > 0 {
676 println!(" ✓ Removed {swept} empty installer director(y/ies)");
677 }
678}
679
680#[cfg(test)]
681mod tests {
682 use super::*;
683 use std::collections::HashSet;
684
685 fn args(list: &[&str]) -> Vec<String> {
686 list.iter().map(|s| (*s).to_string()).collect()
687 }
688
689 #[test]
690 fn parse_args_accepts_known_flags_and_rejects_typos() {
691 assert_eq!(parse_args(&[]), Ok((false, false, false)));
692 assert_eq!(
693 parse_args(&args(&["--keep-binary", "--dry-run", "--keep-config"])),
694 Ok((true, true, true))
695 );
696 for bad in ["--dry-rnu", "--keep", "yes", "-y"] {
697 let err = parse_args(&args(&["--dry-run", bad])).unwrap_err();
698 assert!(err.contains(&format!("'{bad}'")), "{err}");
699 assert!(err.contains("nothing was removed"), "{err}");
700 assert!(err.contains("lean-ctx uninstall --help"), "{err}");
701 }
702 }
703
704 #[test]
705 fn data_dirs_to_remove_covers_canonical_xdg_categories() {
706 let _lock = lean_ctx::core::data_dir::test_env_lock();
713 let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
714 let dirs = data_dirs_to_remove(&home);
715
716 assert!(dirs.contains(&home.join(".lean-ctx")));
718 assert!(dirs.contains(&home.join(".config/lean-ctx")));
719
720 for resolved in [
726 lean_ctx::core::paths::config_dir(),
727 lean_ctx::core::paths::data_dir(),
728 lean_ctx::core::paths::state_dir(),
729 lean_ctx::core::paths::cache_dir(),
730 ]
731 .into_iter()
732 .flatten()
733 {
734 assert!(
735 dirs.contains(&resolved),
736 "uninstall would NOT remove canonical dir: {}",
737 resolved.display()
738 );
739 }
740
741 let mut seen = HashSet::new();
743 for d in &dirs {
744 assert!(seen.insert(d.clone()), "duplicate dir: {}", d.display());
745 }
746 }
747
748 #[test]
754 fn config_migration_journals_and_archives_go_with_the_config_dir() {
755 let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
756 let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
757 let config = lean_ctx::core::config::Config::path().expect("isolated config path");
758 fs::create_dir_all(config.parent().unwrap()).unwrap();
759 fs::write(&config, "compression_level = \"standard\"\n").unwrap();
760 let (backup, receipt) =
761 lean_ctx::config_io::config_migration_journal_files(&config).unwrap();
762 let next = lean_ctx::config_io::config_migration_next_receipt_file(&config).unwrap();
763 let archive =
764 backup.with_file_name("config.toml.v4-migration.original.0123456789abcdef.bak");
765 let removed: Vec<PathBuf> = data_dirs_to_remove(&home)
766 .iter()
767 .filter_map(|dir| dir.canonicalize().ok())
768 .collect();
769 for file in [&backup, &receipt, &next, &archive] {
770 let parent = file.parent().unwrap().canonicalize().unwrap();
771 assert!(
772 removed.iter().any(|dir| parent.starts_with(dir)),
773 "uninstall would leave {} behind",
774 file.display()
775 );
776 }
777 }
778}