lean-ctx 3.12.5

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
// SPDX-License-Identifier: Apache-2.0
//! Process teardown + binary removal for `lean-ctx uninstall`.
//!
//! A "proper" uninstall must (1) stop every lean-ctx process so nothing respawns or
//! holds the data dir we are about to delete, and (2) remove the installed binary itself
//! — not merely print a `rm` hint. Both steps are best-effort and never abort the rest of
//! the uninstall.

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

use super::shorten;

/// Stops the daemon, proxy and Cockpit this instance recorded (mirrors `lean-ctx stop`,
/// but never exits the process — the uninstall must keep going). Only lean-ctx
/// background services recorded by this instance are stopped
/// (`daemon::stop_owned_services`): the current process,
/// IDE-owned MCP servers, hooks and command runners are never selected (#2176).
pub(super) fn stop_processes(dry_run: bool) {
    if dry_run {
        println!("  Would stop the daemon, proxy, and any running lean-ctx services");
        return;
    }

    println!("  Stopping lean-ctx services…");

    lean_ctx::proxy_autostart::stop();
    lean_ctx::daemon_autostart::stop();
    let _ = lean_ctx::daemon::stop_daemon();

    let report = lean_ctx::daemon::stop_owned_services(lean_ctx::ipc::process::ServiceSweep::All);
    if let Some(line) = report.stopped_line() {
        println!("  {line}");
    }
    if let Some(line) = report.survivors_line() {
        eprintln!("  Warning: {line}");
    }

    lean_ctx::daemon::cleanup_daemon_files();
    // Services without a record of this instance keep running (owner
    // decision 02.11.: only recorded services are stopped); say so.
    if let Some((what, how)) = lean_ctx::daemon::unrecorded_services_warning() {
        eprintln!("  ⚠ {what}");
        eprintln!("    {how}");
        println!("  ✓ This instance's services stopped");
    } else {
        println!("  ✓ Services stopped");
    }
}

/// How a candidate binary path should be handled.
enum Disposition {
    /// Safe to delete (a managed copy or a PATH symlink we created).
    Remove,
    /// A dev build inside a cargo `target/` dir — never touch the user's repo build.
    DevBuild,
    /// Installed by a package manager that tracks it — defer to that manager.
    Cargo,
    Homebrew,
}

/// A dev build is recognised by the default path shape (also for a path that
/// is not on disk) or by cargo's bookkeeping next to it (`CARGO_TARGET_DIR`,
/// `--target <triple>`, a named profile). A wrong "dev build" only makes
/// uninstall leave a file in place; a wrong "install" deletes a developer's
/// build.
fn classify(path: &Path) -> Disposition {
    let p = path.to_string_lossy().replace('\\', "/");
    let default_layout = p.contains("/target/release/") || p.contains("/target/debug/");
    if default_layout || lean_ctx::core::portable_binary::in_cargo_output_dir(path) {
        Disposition::DevBuild
    } else if p.contains("/.cargo/") {
        Disposition::Cargo
    } else if p.contains("/Cellar/") || p.contains("homebrew") {
        Disposition::Homebrew
    } else {
        Disposition::Remove
    }
}

/// Standard locations the binary may live in, plus the currently running executable.
fn candidate_paths(home: &Path) -> Vec<PathBuf> {
    let install_dir = std::env::var_os("LEAN_CTX_INSTALL_DIR")
        .map_or_else(|| home.join(".local/bin"), PathBuf::from);

    let mut out = vec![
        install_dir.join("lean-ctx"),
        PathBuf::from("/usr/local/bin/lean-ctx"),
        PathBuf::from("/opt/homebrew/bin/lean-ctx"),
    ];
    if let Ok(exe) = std::env::current_exe() {
        out.push(exe);
    }

    // De-duplicate by string while preserving order.
    let mut seen = std::collections::HashSet::new();
    out.retain(|p| seen.insert(p.to_string_lossy().to_string()));
    out
}

/// Removes the installed binary (and PATH symlinks) where it is safe to do so. Returns
/// `true` if anything was removed or would be removed in a dry run.
///
/// `keep_binary` short-circuits the whole step (e.g. when reinstalling in place).
pub(super) fn remove_binaries(home: &Path, dry_run: bool, keep_binary: bool) -> bool {
    if keep_binary {
        println!("  · Skipped: binary (--keep-binary)");
        return false;
    }

    // Remove our PATH-fallback shims (_lc/_lc_compress) alongside the binary —
    // they are lean-ctx artifacts and would otherwise linger on PATH pointing at
    // a now-deleted binary (the shim then just falls back to running raw).
    let mut removed = remove_path_shims(home, dry_run);
    let mut cargo_hint = false;
    let mut brew_hint = false;

    for path in candidate_paths(home) {
        // `symlink_metadata` does not follow symlinks, so a PATH symlink is detected (and
        // later removed) as the link itself, never its target.
        let Ok(meta) = fs::symlink_metadata(&path) else {
            continue;
        };

        match classify(&path) {
            Disposition::DevBuild => {} // leave the user's repo build alone
            Disposition::Cargo => cargo_hint = true,
            Disposition::Homebrew => brew_hint = true,
            Disposition::Remove => {
                let short = shorten(&path, home);
                if dry_run {
                    println!("  Would remove binary ({short})");
                    removed = true;
                    continue;
                }
                let res = if meta.is_dir() {
                    fs::remove_dir_all(&path)
                } else {
                    // Unlinking a running executable is allowed on Unix (the inode lives
                    // until the process exits); removes a symlink without touching target.
                    fs::remove_file(&path)
                };
                match res {
                    Ok(()) => {
                        println!("  ✓ Binary removed ({short})");
                        removed = true;
                    }
                    Err(e) => {
                        // Windows refuses to delete a running .exe; tell the user.
                        if cfg!(windows) {
                            println!(
                                "  · Could not remove the running binary ({short}). \
                                 Delete it after this process exits."
                            );
                        } else {
                            tracing::warn!("Failed to remove binary {}: {e}", path.display());
                        }
                    }
                }
            }
        }
    }

    if cargo_hint {
        println!("  · Installed via cargo — finish with: cargo uninstall lean-ctx");
    }
    if brew_hint {
        println!("  · Installed via Homebrew — finish with: brew uninstall lean-ctx");
    }
    if !removed && !cargo_hint && !brew_hint {
        println!("  · No managed binary found on standard paths");
    }
    removed
}

/// PATH-fallback shims `init_posix` installs next to the binary (see
/// `cli::shell_init::write_lc_path_shims`): `_lc` and `_lc_compress`.
const PATH_SHIMS: [&str; 2] = ["_lc", "_lc_compress"];

/// Marker every shim body carries (`cli::shell_init::shim_script`). Checked
/// before deletion so uninstall only ever removes a file lean-ctx wrote, never
/// an unrelated `_lc` a user happens to keep on PATH.
const SHIM_MARKER: &str = "lean-ctx PATH fallback";

/// Directories that may hold our shims: the parent of every managed binary
/// candidate, then every `PATH` directory — `init` writes the shims to the
/// `PATH` directory holding the `lean-ctx` launcher (#1851), and the binary may
/// already be gone by the time the shims are removed. Safe because only marked
/// shims are deleted. Dev-build (`target/`) dirs we must never touch are
/// skipped in both. De-duped, order preserved.
fn shim_dirs(home: &Path) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = Vec::new();
    let binary_dirs = candidate_paths(home)
        .into_iter()
        .filter_map(|path| path.parent().map(Path::to_path_buf));
    let path_dirs = lean_ctx::core::portable_binary::path_dirs();
    for dir in binary_dirs.chain(path_dirs) {
        if matches!(classify(&dir.join("lean-ctx")), Disposition::DevBuild) {
            continue;
        }
        if !dirs.contains(&dir) {
            dirs.push(dir);
        }
    }
    dirs
}

/// Removes the marked `_lc`/`_lc_compress` shims from `dirs`. Split out from
/// [`remove_path_shims`] so tests can target an explicit dir without env wiring.
fn remove_shims_in_dirs(dirs: &[PathBuf], home: &Path, dry_run: bool) -> bool {
    let mut removed = false;
    for dir in dirs {
        for name in PATH_SHIMS {
            let shim = dir.join(name);
            // Only delete a file we recognize as our own shim (marker present);
            // a binary `_lc` or foreign script is read as non-matching and kept.
            if !matches!(fs::read_to_string(&shim), Ok(body) if body.contains(SHIM_MARKER)) {
                continue;
            }
            let short = shorten(&shim, home);
            if dry_run {
                println!("  Would remove shim ({short})");
                removed = true;
                continue;
            }
            match fs::remove_file(&shim) {
                Ok(()) => {
                    println!("  ✓ Shim removed ({short})");
                    removed = true;
                }
                Err(e) => tracing::warn!("Failed to remove shim {}: {e}", shim.display()),
            }
        }
    }
    removed
}

/// Removes the `_lc`/`_lc_compress` PATH shims that pair with a managed binary.
fn remove_path_shims(home: &Path, dry_run: bool) -> bool {
    remove_shims_in_dirs(&shim_dirs(home), home, dry_run)
}

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

    fn marked_shim() -> &'static str {
        "#!/bin/sh\n# lean-ctx PATH fallback for the `_lc` shell function\nexit 0\n"
    }

    #[test]
    fn path_shims_removed_when_marked() {
        let dir = tempfile::tempdir().expect("tempdir");
        for name in PATH_SHIMS {
            std::fs::write(dir.path().join(name), marked_shim()).unwrap();
        }
        let dirs = vec![dir.path().to_path_buf()];
        assert!(remove_shims_in_dirs(&dirs, dir.path(), false));
        for name in PATH_SHIMS {
            assert!(
                !dir.path().join(name).exists(),
                "shim {name} should be gone"
            );
        }
    }

    #[test]
    fn foreign_lc_file_is_left_untouched() {
        let dir = tempfile::tempdir().expect("tempdir");
        let foreign = dir.path().join("_lc");
        std::fs::write(&foreign, "#!/bin/sh\necho not ours\n").unwrap();
        let dirs = vec![dir.path().to_path_buf()];
        assert!(!remove_shims_in_dirs(&dirs, dir.path(), false));
        assert!(foreign.exists(), "a foreign _lc must never be deleted");
    }

    #[test]
    fn dry_run_keeps_shims() {
        let dir = tempfile::tempdir().expect("tempdir");
        let shim = dir.path().join("_lc");
        std::fs::write(&shim, marked_shim()).unwrap();
        let dirs = vec![dir.path().to_path_buf()];
        assert!(remove_shims_in_dirs(&dirs, dir.path(), true));
        assert!(shim.exists(), "dry-run must not delete");
    }

    #[test]
    fn shim_dirs_skip_dev_build() {
        let target = std::env::temp_dir()
            .join("lean-ctx-shim-path")
            .join("target");
        let debug = target.join("debug");
        let release = target.join("release");
        let cargo_bin = target.join("ci-cargo-home/bin");
        let path = std::env::join_paths([&debug, &release, &cargo_bin]).unwrap();
        if lean_ctx::test_env::run_in_own_process(
            "uninstall::binary::tests::shim_dirs_skip_dev_build",
            &[("PATH", path.to_str().unwrap())],
        ) {
            return;
        }
        let dirs = shim_dirs(&PathBuf::from("/home/tester"));
        assert!(!dirs.contains(&debug), "debug build dir leaked: {dirs:?}");
        assert!(
            !dirs.contains(&release),
            "release build dir leaked: {dirs:?}"
        );
        assert!(
            dirs.contains(&cargo_bin),
            "Cargo install bin omitted: {dirs:?}"
        );
        // The same wherever cargo put this binary (`CARGO_TARGET_DIR`, a
        // directory not named `target`): its own directory is never a shim dir.
        let exe = std::env::current_exe().expect("test binary path");
        let exe_dir = exe.parent().expect("test binary directory");
        assert!(
            !dirs.iter().any(|d| d == exe_dir),
            "the test binary's directory leaked into shim dirs: {dirs:?}"
        );
    }

    /// Regression: a build under `CARGO_TARGET_DIR`, `--target <triple>` or a
    /// named profile has no `/target/debug/` in its path and was classified as
    /// a removable install.
    #[test]
    fn dev_builds_in_a_custom_target_dir_are_never_removed() {
        let root = tempfile::tempdir().expect("tempdir");
        let profile = root.path().join("build-cache/aarch64-apple-darwin/dist");
        std::fs::create_dir_all(profile.join(".fingerprint")).unwrap();
        std::fs::create_dir_all(profile.join("deps")).unwrap();
        for artifact in ["lean-ctx", "deps/lean_ctx-test"] {
            assert!(
                matches!(classify(&profile.join(artifact)), Disposition::DevBuild),
                "{artifact}"
            );
        }
        // Control: a directory without cargo's bookkeeping is not a dev build,
        // also when it is called `deps`.
        let install = root.path().join("opt/deps");
        std::fs::create_dir_all(&install).unwrap();
        assert!(!matches!(
            classify(&install.join("lean-ctx")),
            Disposition::DevBuild
        ));
    }

    #[test]
    fn dev_builds_are_never_removed() {
        assert!(matches!(
            classify(Path::new("/home/u/lean-ctx/rust/target/release/lean-ctx")),
            Disposition::DevBuild
        ));
        assert!(matches!(
            classify(Path::new("/home/u/proj/target/debug/lean-ctx")),
            Disposition::DevBuild
        ));
        assert!(matches!(
            classify(Path::new(r"C:\work\lean-ctx\target\debug\lean-ctx.exe")),
            Disposition::DevBuild
        ));
    }

    #[test]
    fn package_managers_are_deferred() {
        assert!(matches!(
            classify(Path::new("/home/u/.cargo/bin/lean-ctx")),
            Disposition::Cargo
        ));
        assert!(matches!(
            classify(Path::new("/opt/homebrew/bin/lean-ctx")),
            Disposition::Homebrew
        ));
        assert!(matches!(
            classify(Path::new("/usr/local/Cellar/lean-ctx/3.7.0/bin/lean-ctx")),
            Disposition::Homebrew
        ));
    }

    #[test]
    fn managed_install_dirs_are_removable() {
        assert!(matches!(
            classify(Path::new("/home/u/.local/bin/lean-ctx")),
            Disposition::Remove
        ));
        assert!(matches!(
            classify(Path::new("/usr/local/bin/lean-ctx")),
            Disposition::Remove
        ));
    }

    #[test]
    fn keep_binary_skips_removal() {
        let home = std::env::temp_dir();
        assert!(!remove_binaries(&home, true, true));
    }

    #[test]
    fn candidate_paths_include_install_dir_and_dedup() {
        let home = PathBuf::from("/home/tester");
        let paths = candidate_paths(&home);
        // No duplicates.
        let mut seen = std::collections::HashSet::new();
        for p in &paths {
            assert!(
                seen.insert(p.clone()),
                "duplicate candidate: {}",
                p.display()
            );
        }
    }
}