Skip to main content

lean_ctx/cli/shell_init/
hook_refresh.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `_lc`/`_lc_compress` PATH shims and the refresh of installed shell hooks.
3//!
4//! Both keep aliases working where the hook's shell function is missing: the
5//! shims cover shells that never load it (#1898), the refresh keeps the hook
6//! file itself current across package-manager upgrades (#1959).
7
8use super::{
9    config_artifact_dir, generate_hook_fish, generate_hook_posix, generate_hook_powershell,
10    hook_binary_for_shell, write_env_sh_for_containers,
11};
12
13/// Directories for the `_lc`/`_lc_compress` PATH shims, best first. A shim
14/// only works in a directory that is on `PATH`, and `current_exe`'s directory
15/// often is not (#1851): package managers keep the binary in a versioned
16/// directory (scoop `apps/<ver>`, Homebrew `Cellar`, npm `node_modules`, mise
17/// `installs`) and put a symlink or launcher on `PATH`. So, in order: the
18/// running binary's directory when it is on `PATH`, every `PATH` directory
19/// holding a `lean-ctx` launcher, then `~/.local/bin` when it is on `PATH`.
20fn lc_shim_dirs(
21    current_exe: Option<&std::path::Path>,
22    path_dirs: &[std::path::PathBuf],
23    home: Option<&std::path::Path>,
24) -> Vec<std::path::PathBuf> {
25    use crate::core::portable_binary::{dir_on_path, launchers_on_path};
26
27    let exe_dir = current_exe
28        .and_then(std::path::Path::parent)
29        .filter(|d| dir_on_path(d, path_dirs))
30        .map(std::path::Path::to_path_buf);
31    let launcher_dirs = launchers_on_path(path_dirs)
32        .into_iter()
33        .filter_map(|p| p.parent().map(std::path::Path::to_path_buf));
34    let user_bin = home
35        .map(|h| h.join(".local").join("bin"))
36        .filter(|d| dir_on_path(d, path_dirs));
37
38    let mut dirs: Vec<std::path::PathBuf> = Vec::new();
39    for dir in exe_dir.into_iter().chain(launcher_dirs).chain(user_bin) {
40        if !dirs.contains(&dir) {
41            dirs.push(dir);
42        }
43    }
44    dirs
45}
46
47/// Body of a `_lc`/`_lc_compress` PATH shim. Mirrors the hook's shell function
48/// of the same name: honor the disable switches, pass through raw for a
49/// non-TTY non-agent shell, otherwise route through the binary and fall back to
50/// running the command directly if the binary itself cannot exec (126/127).
51fn shim_script(name: &str, binary: &str, flag: &str) -> String {
52    format!(
53        "#!/bin/sh\n\
54         # lean-ctx PATH fallback for the `{name}` shell function -- DO NOT EDIT.\n\
55         # Shell resolves alias -> function -> PATH, so the hook's shell function\n\
56         # shadows this whenever it is loaded (identical behavior there). This runs\n\
57         # only where the function is absent: non-interactive subshells, scripts,\n\
58         # xargs/find -exec, a pipeline's outer shell, and agent harnesses that\n\
59         # snapshot+replay the shell and drop the function but keep the aliases\n\
60         # that call it. Without it those contexts fail `{name}: command not found`.\n\
61         if [ -n \"${{LEAN_CTX_DISABLED:-}}\" ] || [ -n \"${{LEAN_CTX_NO_HOOK:-}}\" ]; then\n\
62         \texec \"$@\"\n\
63         fi\n\
64         if [ ! -t 1 ] && [ -z \"${{LEAN_CTX_AGENT:-}}\" ] && [ -z \"${{CURSOR_AGENT:-}}\" ] && [ -z \"${{CODEX_CLI_SESSION:-}}\" ] \\\n\
65         \t&& [ -z \"${{CLAUDECODE:-}}\" ] && [ -z \"${{CODEBUDDY:-}}\" ] && [ -z \"${{GEMINI_SESSION:-}}\" ]; then\n\
66         \texec \"$@\"\n\
67         fi\n\
68         '{binary}' {flag} \"$@\"\n\
69         _lc_rc=$?\n\
70         if [ \"$_lc_rc\" -eq 127 ] || [ \"$_lc_rc\" -eq 126 ]; then\n\
71         \texec \"$@\"\n\
72         fi\n\
73         exit \"$_lc_rc\"\n"
74    )
75}
76
77/// Write the `_lc`/`_lc_compress` PATH shims into `dir` (executable on Unix).
78/// True when both were written.
79fn write_lc_path_shims_in(dir: &std::path::Path, binary: &str) -> bool {
80    let mut ok = true;
81    for (name, flag) in [("_lc", "-t"), ("_lc_compress", "-c")] {
82        let path = dir.join(name);
83        let written = std::fs::write(&path, shim_script(name, binary, flag));
84        if let Err(e) = &written {
85            tracing::debug!("could not write shim {}: {e}", path.display());
86            ok = false;
87        }
88        #[cfg(unix)]
89        if written.is_ok() {
90            use std::os::unix::fs::PermissionsExt;
91            let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755));
92        }
93    }
94    ok
95}
96
97/// Install `_lc`/`_lc_compress` fallback executables on `PATH` so aliases never
98/// break when the shell function is unavailable (see [`shim_script`]).
99/// Self-contained: depends on no env wiring (BASH_ENV/env.sh) or snapshot
100/// fidelity, and the same-named function shadows it where the hook is loaded.
101/// Written to the first writable directory of [`lc_shim_dirs`].
102pub(super) fn write_lc_path_shims(binary: &str) {
103    let current_exe = std::env::current_exe().ok();
104    let candidates = lc_shim_dirs(
105        current_exe.as_deref(),
106        &crate::core::portable_binary::path_dirs(),
107        dirs::home_dir().as_deref(),
108    );
109    if candidates
110        .iter()
111        .any(|dir| write_lc_path_shims_in(dir, binary))
112    {
113        return;
114    }
115    tracing::warn!(
116        "could not write the _lc/_lc_compress shims to a PATH directory; \
117         aliases fail where the shell function is unavailable"
118    );
119}
120
121/// Bring already-installed shell hooks up to this binary (#1959).
122///
123/// Only `init`, `setup`, `update` and `doctor --fix` write the hook files, so a
124/// package-manager upgrade (FreeBSD ports, AUR, Homebrew, `cargo install`)
125/// kept the hook an older build wrote — with aliases calling `_lc`, which
126/// agent shells that drop `_`-prefixed functions fail on (#1898). Called on
127/// MCP server start, next to the agent-hook refresh. Rewrites only hook files
128/// that exist and are stale, never an rc file, and does nothing when the shell
129/// hook is disabled.
130pub fn refresh_installed_shell_hooks() {
131    if crate::core::config::Config::load().shell_hook_disabled_effective() {
132        return;
133    }
134    let Some(dir) = config_artifact_dir() else {
135        return;
136    };
137    let binary = crate::core::portable_binary::stable_shell_binary(
138        &crate::core::portable_binary::resolve_portable_binary(),
139    );
140    if refresh_shell_hooks_in(&dir, &binary) {
141        let bash_binary = hook_binary_for_shell("bash", &binary);
142        if dir.join("env.sh").exists() {
143            write_env_sh_for_containers(&generate_hook_posix(&bash_binary));
144        }
145        write_lc_path_shims(&bash_binary);
146    }
147}
148
149/// Rewrite each existing `shell-hook.*` in `dir` whose content differs from
150/// what this build generates. Returns whether a bash/zsh hook was rewritten.
151fn refresh_shell_hooks_in(dir: &std::path::Path, binary: &str) -> bool {
152    let mut posix_refreshed = false;
153    for (ext, shell) in [
154        ("bash", "bash"),
155        ("zsh", "zsh"),
156        ("fish", "fish"),
157        ("ps1", "powershell"),
158    ] {
159        let path = dir.join(format!("shell-hook.{ext}"));
160        let Ok(current) = std::fs::read_to_string(&path) else {
161            continue;
162        };
163        let shell_binary = hook_binary_for_shell(shell, binary);
164        let fresh = match shell {
165            "fish" => generate_hook_fish(&shell_binary),
166            "powershell" => generate_hook_powershell(&shell_binary),
167            _ => generate_hook_posix(&shell_binary),
168        };
169        if current == fresh {
170            continue;
171        }
172        match std::fs::write(&path, fresh) {
173            Ok(()) => {
174                tracing::info!("refreshed stale shell hook {}", path.display());
175                posix_refreshed |= matches!(shell, "bash" | "zsh");
176            }
177            Err(e) => tracing::debug!("could not refresh {}: {e}", path.display()),
178        }
179    }
180    posix_refreshed
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn lc_shim_script_is_self_contained_fallback() {
189        let s = shim_script("_lc", "/usr/bin/lean-ctx", "-t");
190        assert!(s.starts_with("#!/bin/sh\n"), "needs a shebang: {s}");
191        assert!(s.contains("'/usr/bin/lean-ctx' -t \"$@\""), "{s}");
192        assert!(s.contains("exec \"$@\""), "{s}");
193        assert!(s.contains("CLAUDECODE"), "{s}");
194        assert!(s.contains("LEAN_CTX_DISABLED"), "{s}");
195    }
196
197    #[test]
198    fn lc_compress_shim_uses_compress_flag() {
199        let s = shim_script("_lc_compress", "/usr/bin/lean-ctx", "-c");
200        assert!(s.contains("'/usr/bin/lean-ctx' -c \"$@\""), "{s}");
201    }
202
203    /// #1959: a hook written by an older build (aliases → `_lc`) is brought up
204    /// to date without `init`; a shell the user never set up gets no hook.
205    #[test]
206    fn stale_installed_hooks_are_refreshed_and_absent_ones_left_alone() {
207        // The generator bakes config values in; keep them stable for both calls.
208        let _iso = crate::core::data_dir::isolated_data_dir();
209        let tmp = tempfile::tempdir().expect("tempdir");
210        let bin = "/usr/local/bin/lean-ctx";
211        let hook = tmp.path().join("shell-hook.bash");
212        std::fs::write(&hook, "alias grep='_lc grep'\n").expect("write stale hook");
213
214        assert!(refresh_shell_hooks_in(tmp.path(), bin), "stale bash hook");
215        assert_eq!(
216            std::fs::read_to_string(&hook).expect("read hook"),
217            generate_hook_posix(bin)
218        );
219        assert!(!tmp.path().join("shell-hook.zsh").exists());
220        assert!(!tmp.path().join("shell-hook.fish").exists());
221        assert!(
222            !refresh_shell_hooks_in(tmp.path(), bin),
223            "a current hook is not rewritten"
224        );
225    }
226
227    #[test]
228    fn write_lc_path_shims_writes_both_executables() {
229        let tmp = tempfile::tempdir().expect("tempdir");
230        assert!(write_lc_path_shims_in(tmp.path(), "/usr/bin/lean-ctx"));
231        for name in ["_lc", "_lc_compress"] {
232            assert!(tmp.path().join(name).exists(), "missing shim {name}");
233        }
234    }
235
236    #[test]
237    fn write_lc_path_shims_reports_an_unwritable_dir() {
238        let tmp = tempfile::tempdir().expect("tempdir");
239        assert!(!write_lc_path_shims_in(
240            &tmp.path().join("missing"),
241            "/usr/bin/lean-ctx"
242        ));
243    }
244
245    /// #1851: a package manager keeps the binary in a versioned directory off
246    /// PATH and puts a launcher on PATH — the shims belong next to the launcher.
247    #[cfg(unix)]
248    mod lc_shim_dirs_1851 {
249        use super::super::lc_shim_dirs;
250        use std::path::{Path, PathBuf};
251
252        fn launcher_dir(root: &Path, rel: &str) -> PathBuf {
253            let dir = root.join(rel);
254            std::fs::create_dir_all(&dir).unwrap();
255            std::fs::write(dir.join("lean-ctx"), "#!/bin/sh\n").unwrap();
256            dir
257        }
258
259        #[test]
260        fn versioned_install_dir_off_path_is_skipped() {
261            let tmp = tempfile::tempdir().unwrap();
262            let apps = launcher_dir(tmp.path(), "scoop/apps/lean-ctx/3.10.2");
263            let shims = launcher_dir(tmp.path(), "scoop/shims");
264            let dirs = lc_shim_dirs(
265                Some(&apps.join("lean-ctx")),
266                &[tmp.path().join("usr/bin"), shims.clone()],
267                None,
268            );
269            assert_eq!(dirs, vec![shims]);
270        }
271
272        #[test]
273        fn exe_dir_on_path_comes_first_then_launchers_then_user_bin() {
274            let tmp = tempfile::tempdir().unwrap();
275            let home = tmp.path().join("home");
276            let user_bin = home.join(".local/bin");
277            std::fs::create_dir_all(&user_bin).unwrap();
278            let brew = launcher_dir(tmp.path(), "opt/homebrew/bin");
279            let exe_dir = launcher_dir(tmp.path(), "exe");
280            let dirs = lc_shim_dirs(
281                Some(&exe_dir.join("lean-ctx")),
282                &[brew.clone(), user_bin.clone(), exe_dir.clone()],
283                Some(&home),
284            );
285            assert_eq!(dirs, vec![exe_dir, brew, user_bin]);
286        }
287
288        #[test]
289        fn user_bin_off_path_is_not_a_candidate() {
290            let tmp = tempfile::tempdir().unwrap();
291            let home = tmp.path().join("home");
292            std::fs::create_dir_all(home.join(".local/bin")).unwrap();
293            let dirs = lc_shim_dirs(None, &[tmp.path().join("usr/bin")], Some(&home));
294            assert!(dirs.is_empty(), "{dirs:?}");
295        }
296    }
297}