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);
22 if let Ok(bytes) = fs::read(path) {
23 let _ = lean_ctx::config_io::write_backup_nofollow(path, &bak, &bytes);
24 }
25 }
26}
27
28pub fn bak_path_for(path: &Path) -> PathBuf {
29 let filename = path.file_name().unwrap_or_default().to_string_lossy();
30 path.with_file_name(format!("{filename}.lean-ctx.bak"))
31}
32
33fn cleanup_bak(path: &Path) {
34 let bak = bak_path_for(path);
35 if bak.exists() {
36 let _ = fs::remove_file(&bak);
37 }
38}
39
40pub(super) fn shorten(path: &Path, home: &Path) -> String {
41 match path.strip_prefix(home) {
42 Ok(rel) => format!("~/{}", rel.display()),
43 Err(_) => path.display().to_string(),
44 }
45}
46
47pub(super) fn copilot_instructions_path(home: &Path) -> PathBuf {
48 #[cfg(target_os = "macos")]
49 {
50 return home.join("Library/Application Support/Code/User/github-copilot-instructions.md");
51 }
52 #[cfg(target_os = "linux")]
53 {
54 let user_dirs = [
55 home.join(".config/Code/User"),
56 home.join(".config/Code - Insiders/User"),
57 home.join(".vscode-server/data/User"),
58 ];
59 let user_dir = user_dirs
60 .iter()
61 .find(|p| p.exists())
62 .cloned()
63 .unwrap_or_else(|| user_dirs[0].clone());
64 return user_dir.join("github-copilot-instructions.md");
65 }
66 #[cfg(target_os = "windows")]
67 {
68 if let Ok(appdata) = std::env::var("APPDATA") {
69 return PathBuf::from(appdata).join("Code/User/github-copilot-instructions.md");
70 }
71 }
72 #[allow(unreachable_code)]
73 home.join(".config/Code/User/github-copilot-instructions.md")
74}
75
76pub(super) fn safe_write(path: &Path, content: &str, dry_run: bool) -> Result<(), std::io::Error> {
78 if dry_run {
79 return Ok(());
80 }
81 fs::write(path, content)?;
82 cleanup_bak(path);
84 Ok(())
85}
86
87pub(super) fn safe_remove(path: &Path, dry_run: bool) -> Result<(), std::io::Error> {
89 if dry_run {
90 return Ok(());
91 }
92 fs::remove_file(path)?;
93 cleanup_bak(path);
95 Ok(())
96}
97
98pub fn print_help() {
108 println!(
109 "\
110lean-ctx uninstall — remove lean-ctx cleanly
111
112USAGE:
113 lean-ctx uninstall [OPTIONS]
114
115OPTIONS:
116 --dry-run Preview every change without modifying anything
117 --keep-config Preserve MCP configs and rules (for a later reinstall)
118 --keep-binary Leave the lean-ctx binary in place
119 -h, --help Show this help and exit (does NOT uninstall)
120
121WHAT IT REMOVES:
122 • Running processes (daemon, proxy) and autostart entries
123 • Shell hooks and proxy environment from your shell rc files
124 • MCP server configs and rules from every detected AI tool/IDE
125 • Skill directories and project integration files
126 • The data directory and the lean-ctx binary
127
128 Modified files are backed up as <file>.lean-ctx.bak before removal.
129
130EXAMPLES:
131 lean-ctx uninstall --dry-run # see exactly what would change
132 lean-ctx uninstall # full clean removal"
133 );
134}
135
136pub fn parse_args(rest: &[String]) -> Result<(bool, bool, bool), String> {
141 let (mut dry_run, mut keep_config, mut keep_binary) = (false, false, false);
142 for arg in rest {
143 match arg.as_str() {
144 "--dry-run" => dry_run = true,
145 "--keep-config" => keep_config = true,
146 "--keep-binary" => keep_binary = true,
147 other => {
148 return Err(format!(
149 "lean-ctx uninstall: unknown argument '{other}'; nothing was removed.\n\
150 Usage: lean-ctx uninstall [--dry-run] [--keep-config] [--keep-binary] \
151 (see: lean-ctx uninstall --help)"
152 ));
153 }
154 }
155 }
156 Ok((dry_run, keep_config, keep_binary))
157}
158
159pub fn run(dry_run: bool, keep_config: bool, keep_binary: bool) {
164 let Some(home) = dirs::home_dir() else {
165 tracing::warn!("Could not determine home directory");
166 return;
167 };
168
169 let mode_label = if keep_config {
170 "uninstall --keep-config"
171 } else {
172 "uninstall"
173 };
174
175 if dry_run {
176 println!("\n lean-ctx {mode_label} --dry-run\n ──────────────────────────────────\n");
177 println!(" Preview mode — no files will be modified.\n");
178 } else {
179 println!("\n lean-ctx {mode_label}\n ──────────────────────────────────\n");
180 }
181
182 if keep_config {
183 println!(" Mode: keep-config (MCP configs and rules preserved for reinstall)\n");
184 }
185
186 binary::stop_processes(dry_run);
188
189 let mut removed_any = false;
190
191 removed_any |= remove_shell_hook(&home, dry_run);
192 if dry_run {
193 crate::proxy_setup::preview_proxy_cleanup(&home);
194 } else {
195 crate::proxy_setup::uninstall_proxy_env(&home, false);
196 }
197
198 if keep_config {
199 println!(" · Skipped: MCP configs (--keep-config)");
200 println!(" · Skipped: Rules files (--keep-config)");
201 } else {
202 removed_any |= remove_mcp_configs(&home, dry_run);
203 removed_any |= remove_rules_files(&home, dry_run);
204 if !dry_run {
205 try_claude_mcp_remove();
206 }
207 }
208
209 removed_any |= remove_hook_files(&home, dry_run);
210 removed_any |= remove_plan_mode_settings(&home, dry_run);
211 removed_any |= remove_skill_dirs(&home, dry_run);
212 removed_any |= remove_project_agent_files(dry_run);
213
214 if dry_run {
215 println!(" Would remove proxy autostart (LaunchAgent/systemd)");
216 println!(" Would remove daemon autostart (LaunchAgent/systemd)");
217 println!(" Would remove auto-update schedule (LaunchAgent/systemd/Task)");
218 } else {
219 lean_ctx::proxy_autostart::uninstall(true);
220 lean_ctx::daemon_autostart::uninstall(true);
221 let had_schedule = lean_ctx::core::update_scheduler::schedule_status().enabled;
226 match lean_ctx::core::update_scheduler::remove_schedule() {
227 Ok(()) if had_schedule => {
228 println!(" ✓ Auto-update schedule removed");
229 removed_any = true;
230 }
231 Ok(()) => {}
232 Err(e) => tracing::warn!("Failed to remove auto-update schedule: {e}"),
233 }
234 }
235
236 if !dry_run {
237 cleanup_bak_files(&home);
238 }
239
240 removed_any |= remove_data_dir(&home, dry_run);
241
242 if !dry_run {
245 sweep_empty_installer_dirs(&home);
246 }
247
248 removed_any |= binary::remove_binaries(&home, dry_run, keep_binary);
251
252 println!();
253
254 if removed_any {
255 println!(" ──────────────────────────────────");
256 if dry_run {
257 println!(
258 " The above changes WOULD be applied.\n Run `lean-ctx {mode_label}` to execute.\n"
259 );
260 } else if keep_config {
261 println!(
262 " Runtime data removed. MCP configs preserved for reinstall.\n \
263 Reinstall with: cargo install lean-ctx\n"
264 );
265 } else {
266 println!(
267 " lean-ctx fully removed. Restart your shell to drop stale aliases.\n \
268 Verify with: command -v lean-ctx # should print nothing\n"
269 );
270 }
271 } else {
272 println!(" Nothing to remove — lean-ctx was not configured.\n");
273 }
274}
275
276pub(super) fn remove_marked_block(content: &str, start: &str, end: &str) -> String {
281 let s = content.find(start);
282 let e = content.find(end);
283 match (s, e) {
284 (Some(si), Some(ei)) if ei >= si => {
285 let after_end = ei + end.len();
286 let before = &content[..si];
287 let after = &content[after_end..];
288 let mut out = String::new();
289 out.push_str(before.trim_end_matches('\n'));
290 out.push('\n');
291 if !after.trim().is_empty() {
292 out.push('\n');
293 out.push_str(after.trim_start_matches('\n'));
294 }
295 out
296 }
297 _ => content.to_string(),
298 }
299}
300
301fn remove_skill_dirs(home: &Path, dry_run: bool) -> bool {
306 let claude_state = lean_ctx::core::editor_registry::claude_state_dir(home);
307 let codebuddy_state = lean_ctx::core::editor_registry::codebuddy_state_dir(home);
308 let mut skill_dirs: Vec<(&str, PathBuf)> = vec![
309 ("Claude Code", claude_state.join("skills/lean-ctx")),
310 ("CodeBuddy", codebuddy_state.join("skills/lean-ctx")),
311 ("Cursor", home.join(".cursor/skills/lean-ctx")),
312 (
313 "Codex CLI",
314 lean_ctx::core::home::resolve_codex_dir()
315 .unwrap_or_else(|| home.join(".codex"))
316 .join("skills/lean-ctx"),
317 ),
318 ("Grok", home.join(".grok/skills/lean-ctx")),
319 ("Copilot", home.join(".copilot/skills/lean-ctx")),
320 ("OpenClaw", home.join(".openclaw/skills/lean-ctx")),
321 ];
322
323 let default_claude_skill = home.join(".claude/skills/lean-ctx");
325 if !skill_dirs.iter().any(|(_, p)| *p == default_claude_skill) {
326 skill_dirs.push(("Claude Code (default)", default_claude_skill));
327 }
328
329 let default_codebuddy_skill = home.join(".codebuddy/skills/lean-ctx");
331 if !skill_dirs
332 .iter()
333 .any(|(_, p)| *p == default_codebuddy_skill)
334 {
335 skill_dirs.push(("CodeBuddy (default)", default_codebuddy_skill));
336 }
337
338 let mut removed = false;
339 for (name, dir) in &skill_dirs {
340 if !dir.exists() {
341 continue;
342 }
343 if dry_run {
344 println!(" Would remove {name} skill directory");
345 removed = true;
346 } else if let Err(e) = fs::remove_dir_all(dir) {
347 tracing::warn!("Failed to remove {name} skill dir: {e}");
348 } else {
349 println!(" ✓ {name} skill directory removed");
350 removed = true;
351 }
352 }
353 removed
354}
355
356fn data_dirs_to_remove(home: &Path) -> Vec<PathBuf> {
372 let mut dirs = vec![home.join(".lean-ctx"), home.join(".config/lean-ctx")];
373
374 let push = |dirs: &mut Vec<PathBuf>, p: PathBuf| {
375 if !dirs.contains(&p) {
376 dirs.push(p);
377 }
378 };
379
380 for resolved in [
382 lean_ctx::core::paths::config_dir(),
383 lean_ctx::core::paths::data_dir(),
384 lean_ctx::core::paths::state_dir(),
385 lean_ctx::core::paths::cache_dir(),
386 ]
387 .into_iter()
388 .flatten()
389 {
390 push(&mut dirs, resolved);
391 }
392
393 for platform_dir in [dirs::data_local_dir(), dirs::data_dir()]
395 .into_iter()
396 .flatten()
397 {
398 push(&mut dirs, platform_dir.join("lean-ctx"));
399 }
400
401 dirs
402}
403
404fn remove_data_dir(home: &Path, dry_run: bool) -> bool {
405 let mut removed = false;
406
407 let dirs_to_remove = data_dirs_to_remove(home);
408
409 for data_dir in &dirs_to_remove {
410 if !data_dir.exists() {
411 continue;
412 }
413 let short = shorten(data_dir, home);
414 if dry_run {
415 println!(" Would remove data directory ({short})");
416 removed = true;
417 continue;
418 }
419 match fs::remove_dir_all(data_dir) {
420 Ok(()) => {
421 println!(" ✓ Data directory removed ({short})");
422 removed = true;
423 }
424 Err(e) => tracing::warn!("Failed to remove {short}: {e}"),
425 }
426 }
427
428 if let Ok(cwd) = std::env::current_dir() {
430 let project_dir = cwd.join(".lean-ctx");
431 let project_id = cwd.join(".lean-ctx-id");
432 for p in [&project_dir, &project_id] {
433 if p.exists() {
434 if dry_run {
435 println!(" Would remove {}", p.display());
436 removed = true;
437 } else if p.is_dir() {
438 if fs::remove_dir_all(p).is_ok() {
439 println!(" ✓ Removed {}", p.display());
440 removed = true;
441 }
442 } else if fs::remove_file(p).is_ok() {
443 println!(" ✓ Removed {}", p.display());
444 removed = true;
445 }
446 }
447 }
448 }
449
450 if !removed {
451 println!(" · No data directory found");
452 }
453 removed
454}
455
456fn try_claude_mcp_remove() {
457 let result = std::process::Command::new("claude")
458 .args(["mcp", "remove", "lean-ctx", "--scope", "user"])
459 .stdout(std::process::Stdio::null())
460 .stderr(std::process::Stdio::null())
461 .status();
462 match result {
463 Ok(s) if s.success() => println!(" ✓ Removed lean-ctx from Claude MCP registry"),
464 _ => {} }
466}
467
468fn scan_dirs(home: &Path) -> Vec<PathBuf> {
476 let base_dirs: Vec<PathBuf> = vec![
477 home.join(".cursor"),
478 home.join(".claude"),
479 lean_ctx::core::editor_registry::claude_state_dir(home),
480 home.join(".codebuddy"),
481 lean_ctx::core::editor_registry::codebuddy_state_dir(home),
482 lean_ctx::core::editor_registry::zed_config_dir(home),
483 home.join(".gemini"),
484 home.join(".gemini/antigravity"),
485 home.join(".gemini/antigravity-cli"),
486 lean_ctx::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex")),
487 home.join(".codeium"),
488 home.join(".codeium/windsurf"),
489 home.join(".config/opencode"),
490 home.join(".config/amp"),
491 home.join(".config/crush"),
492 home.join(".config/zed"),
493 home.join(".qwen"),
494 home.join(".trae"),
495 home.join(".codewhale"),
496 home.join(".deepseek"),
497 lean_ctx::core::editor_registry::muse_config_dir(home),
498 home.join(".aws/amazonq"),
499 home.join(".kiro"),
500 home.join(".kiro/settings"),
501 home.join(".ampcoder"),
502 home.join(".pi"),
503 home.join(".pi/agent"),
504 home.join(".hermes"),
505 home.join(".grok"),
506 home.join(".verdent"),
507 home.join(".cline"),
508 home.join(".roo"),
509 home.join(".continue"),
510 home.join(".jb-rules"),
511 home.join(".openclaw"),
512 home.join(".augment"),
513 home.join(".qoder"),
514 home.join(".qoderwork"),
515 home.join(".aider"),
516 home.join(".emacs.d"),
517 home.join(".copilot"),
518 home.join(".github"),
519 home.join(".config/mcphub"),
520 home.join(".config/sublime-text"),
521 ];
522
523 const KNOWN_SUBDIRS: [&str; 6] = ["hooks", "rules", "skills", "steering", "settings", "User"];
527 let mut dirs_to_scan: Vec<PathBuf> = Vec::with_capacity(base_dirs.len() * 4);
528 for dir in base_dirs {
529 for sub in KNOWN_SUBDIRS {
530 let p = dir.join(sub);
531 if p.is_dir() {
532 dirs_to_scan.push(p);
533 }
534 }
535 dirs_to_scan.push(dir);
536 }
537
538 if let Ok(cwd) = std::env::current_dir() {
541 for rel in [
542 ".cursor/rules",
543 ".claude",
544 ".claude/rules",
545 ".claude/hooks",
546 ".codebuddy",
547 ".codebuddy/rules",
548 ".codebuddy/hooks",
549 ".kiro/steering",
550 ".github",
551 ".github/hooks",
552 ".vscode",
553 ] {
554 let p = cwd.join(rel);
555 if p.is_dir() {
556 dirs_to_scan.push(p);
557 }
558 }
559 }
560
561 dirs_to_scan
562}
563
564fn cleanup_bak_files(home: &Path) {
565 let dirs_to_scan = scan_dirs(home);
566 let mut cleaned = 0;
567 for dir in &dirs_to_scan {
568 if !dir.exists() {
569 continue;
570 }
571 if let Ok(entries) = fs::read_dir(dir) {
572 for entry in entries.flatten() {
573 let name = entry.file_name();
574 let name_str = name.to_string_lossy();
575 if name_str.ends_with(".lean-ctx.tmp") {
576 let _ = fs::remove_file(entry.path());
577 cleaned += 1;
578 continue;
579 }
580 if name_str.ends_with(".bak")
585 && (name_str.starts_with("lean-ctx-") || name_str.starts_with("lean-ctx."))
586 {
587 let _ = fs::remove_file(entry.path());
588 cleaned += 1;
589 continue;
590 }
591 if name_str.contains(".lean-ctx.invalid.") && name_str.ends_with(".bak") {
592 let _ = fs::remove_file(entry.path());
593 cleaned += 1;
594 continue;
595 }
596 if name_str.ends_with(".lean-ctx.bak") {
597 let original_name = name_str.trim_end_matches(".lean-ctx.bak");
598 let original = entry.path().with_file_name(original_name);
599 if original.exists() {
600 match fs::read_to_string(&original) {
601 Ok(c) if !c.contains("lean-ctx") => {
602 let _ = fs::remove_file(entry.path());
603 cleaned += 1;
604 }
605 _ => {}
606 }
607 } else {
608 let _ = fs::remove_file(entry.path());
609 cleaned += 1;
610 }
611 continue;
612 }
613 if name_str.ends_with(".bak")
618 && !name_str.contains(".lean-ctx")
619 && let Ok(bak_content) = fs::read_to_string(entry.path())
620 && bak_content.contains("lean-ctx")
621 {
622 let _ = fs::remove_file(entry.path());
623 cleaned += 1;
624 }
625 }
626 }
627 }
628
629 let rc_baks = [
631 home.join(".zshrc.lean-ctx.bak"),
632 home.join(".zshenv.lean-ctx.bak"),
633 home.join(".bashrc.lean-ctx.bak"),
634 home.join(".bashenv.lean-ctx.bak"),
635 ];
636 for bak in &rc_baks {
637 if bak.exists() {
638 let original_name = bak
639 .file_name()
640 .unwrap_or_default()
641 .to_string_lossy()
642 .trim_end_matches(".lean-ctx.bak")
643 .to_string();
644 let original = bak.with_file_name(original_name);
645 if original.exists() {
646 if let Ok(c) = fs::read_to_string(&original)
647 && !c.contains("lean-ctx")
648 {
649 let _ = fs::remove_file(bak);
650 cleaned += 1;
651 }
652 } else {
653 let _ = fs::remove_file(bak);
654 cleaned += 1;
655 }
656 }
657 }
658
659 if cleaned > 0 {
660 println!(" ✓ Cleaned up {cleaned} backup file(s)");
661 }
662}
663
664fn sweep_empty_installer_dirs(home: &Path) {
669 let mut swept = 0;
670 for dir in scan_dirs(home) {
671 let is_installer_dir = dir
672 .file_name()
673 .and_then(|n| n.to_str())
674 .is_some_and(|n| matches!(n, "hooks" | "rules" | "skills" | "steering"));
675 if is_installer_dir && fs::remove_dir(&dir).is_ok() {
676 swept += 1;
677 }
678 }
679 if swept > 0 {
680 println!(" ✓ Removed {swept} empty installer director(y/ies)");
681 }
682}
683
684#[cfg(test)]
685mod tests {
686 use super::*;
687 use std::collections::HashSet;
688
689 fn args(list: &[&str]) -> Vec<String> {
690 list.iter().map(|s| (*s).to_string()).collect()
691 }
692
693 #[test]
694 fn parse_args_accepts_known_flags_and_rejects_typos() {
695 assert_eq!(parse_args(&[]), Ok((false, false, false)));
696 assert_eq!(
697 parse_args(&args(&["--keep-binary", "--dry-run", "--keep-config"])),
698 Ok((true, true, true))
699 );
700 for bad in ["--dry-rnu", "--keep", "yes", "-y"] {
701 let err = parse_args(&args(&["--dry-run", bad])).unwrap_err();
702 assert!(err.contains(&format!("'{bad}'")), "{err}");
703 assert!(err.contains("nothing was removed"), "{err}");
704 assert!(err.contains("lean-ctx uninstall --help"), "{err}");
705 }
706 }
707
708 #[test]
709 fn data_dirs_to_remove_covers_canonical_xdg_categories() {
710 let _lock = lean_ctx::core::data_dir::test_env_lock();
717 let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
718 let dirs = data_dirs_to_remove(&home);
719
720 assert!(dirs.contains(&home.join(".lean-ctx")));
722 assert!(dirs.contains(&home.join(".config/lean-ctx")));
723
724 for resolved in [
730 lean_ctx::core::paths::config_dir(),
731 lean_ctx::core::paths::data_dir(),
732 lean_ctx::core::paths::state_dir(),
733 lean_ctx::core::paths::cache_dir(),
734 ]
735 .into_iter()
736 .flatten()
737 {
738 assert!(
739 dirs.contains(&resolved),
740 "uninstall would NOT remove canonical dir: {}",
741 resolved.display()
742 );
743 }
744
745 let mut seen = HashSet::new();
747 for d in &dirs {
748 assert!(seen.insert(d.clone()), "duplicate dir: {}", d.display());
749 }
750 }
751
752 #[test]
758 fn config_migration_journals_and_archives_go_with_the_config_dir() {
759 let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
760 let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/home/tester"));
761 let config = lean_ctx::core::config::Config::path().expect("isolated config path");
762 fs::create_dir_all(config.parent().unwrap()).unwrap();
763 fs::write(&config, "compression_level = \"standard\"\n").unwrap();
764 let (backup, receipt) =
765 lean_ctx::config_io::config_migration_journal_files(&config).unwrap();
766 let next = lean_ctx::config_io::config_migration_next_receipt_file(&config).unwrap();
767 let archive =
768 backup.with_file_name("config.toml.v4-migration.original.0123456789abcdef.bak");
769 let removed: Vec<PathBuf> = data_dirs_to_remove(&home)
770 .iter()
771 .filter_map(|dir| dir.canonicalize().ok())
772 .collect();
773 for file in [&backup, &receipt, &next, &archive] {
774 let parent = file.parent().unwrap().canonicalize().unwrap();
775 assert!(
776 removed.iter().any(|dir| parent.starts_with(dir)),
777 "uninstall would leave {} behind",
778 file.display()
779 );
780 }
781 }
782}