lean-ctx 3.8.6

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
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
mod agents;
mod binary;
mod parsers;

use std::fs;
use std::path::{Path, PathBuf};

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() {
        let bak = bak_path_for(path);
        let _ = fs::copy(path, &bak);
    }
}

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(())
}

/// 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(())
}

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

pub fn run(dry_run: bool, keep_config: bool, keep_binary: bool) {
    let Some(home) = dirs::home_dir() else {
        tracing::warn!("Could not determine home directory");
        return;
    };

    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)");
    } else {
        crate::proxy_autostart::uninstall(true);
        crate::daemon_autostart::uninstall(true);
    }

    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!();

    if removed_any {
        println!("  ──────────────────────────────────");
        if dry_run {
            println!(
                "  The above changes WOULD be applied.\n  Run `lean-ctx {mode_label}` to execute.\n"
            );
        } else if keep_config {
            println!(
                "  Runtime data removed. MCP configs preserved for reinstall.\n  \
                 Reinstall with: cargo install lean-ctx\n"
            );
        } else {
            println!(
                "  lean-ctx fully removed. Restart your shell to drop stale aliases.\n  \
                 Verify with: command -v lean-ctx   # should print nothing\n"
            );
        }
    } else {
        println!("  Nothing to remove — lean-ctx was not configured.\n");
    }
}

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

pub(super) fn remove_marked_block(content: &str, start: &str, end: &str) -> String {
    let s = content.find(start);
    let e = content.find(end);
    match (s, e) {
        (Some(si), Some(ei)) if ei >= si => {
            let after_end = ei + end.len();
            let before = &content[..si];
            let after = &content[after_end..];
            let mut out = String::new();
            out.push_str(before.trim_end_matches('\n'));
            out.push('\n');
            if !after.trim().is_empty() {
                out.push('\n');
                out.push_str(after.trim_start_matches('\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 = crate::core::editor_registry::claude_state_dir(home);
    let codebuddy_state = crate::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",
            crate::core::home::resolve_codex_dir()
                .unwrap_or_else(|| home.join(".codex"))
                .join("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) {
            tracing::warn!("Failed to remove {name} skill dir: {e}");
        } else {
            println!("{name} skill directory removed");
            removed = true;
        }
    }
    removed
}

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

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

    let mut dirs_to_remove = vec![home.join(".lean-ctx"), home.join(".config/lean-ctx")];

    // Platform data dirs hold daemon logs + PID files (macOS:
    // ~/Library/Application Support/lean-ctx, Windows: %LOCALAPPDATA%\lean-ctx,
    // Linux: ~/.local/share/lean-ctx) — see daemon.rs `data_dir()`.
    for platform_dir in [dirs::data_local_dir(), dirs::data_dir()]
        .into_iter()
        .flatten()
    {
        let p = platform_dir.join("lean-ctx");
        if !dirs_to_remove.contains(&p) {
            dirs_to_remove.push(p);
        }
    }

    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) => tracing::warn!("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"),
        crate::core::editor_registry::claude_state_dir(home),
        home.join(".codebuddy"),
        crate::core::editor_registry::codebuddy_state_dir(home),
        crate::core::editor_registry::zed_config_dir(home),
        home.join(".gemini"),
        home.join(".gemini/antigravity"),
        home.join(".gemini/antigravity-cli"),
        crate::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(".aws/amazonq"),
        home.join(".kiro"),
        home.join(".kiro/settings"),
        home.join(".ampcoder"),
        home.join(".pi"),
        home.join(".pi/agent"),
        home.join(".hermes"),
        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") {
                    if let Ok(bak_content) = fs::read_to_string(entry.path()) {
                        if 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) {
                    if !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)");
    }
}