Skip to main content

lean_ctx_cli/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 lean_ctx::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        &lean_ctx::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 lean_ctx::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 = lean_ctx::core::portable_binary::stable_shell_binary(
138        &lean_ctx::core::portable_binary::resolve_portable_binary(),
139    );
140    // A `cargo test` binary must never become the real account's shell hook,
141    // `env.sh` or `_lc` shim (#2232).
142    if lean_ctx::core::home::resolve_home_dir().is_some_and(|home| {
143        lean_ctx::core::portable_binary::refuses_transient_binary_for_home(&binary, &home)
144    }) {
145        return;
146    }
147    if refresh_shell_hooks_in(&dir, &binary) {
148        let bash_binary = hook_binary_for_shell("bash", &binary);
149        if dir.join("env.sh").exists() {
150            write_env_sh_for_containers(&generate_hook_posix(&bash_binary));
151        }
152        write_lc_path_shims(&bash_binary);
153    }
154}
155
156/// Rewrite each existing `shell-hook.*` in `dir` whose content differs from
157/// what this build generates. Returns whether a bash/zsh hook was rewritten.
158fn refresh_shell_hooks_in(dir: &std::path::Path, binary: &str) -> bool {
159    let mut posix_refreshed = false;
160    for (ext, shell) in [
161        ("bash", "bash"),
162        ("zsh", "zsh"),
163        ("fish", "fish"),
164        ("ps1", "powershell"),
165    ] {
166        let path = dir.join(format!("shell-hook.{ext}"));
167        let Ok(current) = std::fs::read_to_string(&path) else {
168            continue;
169        };
170        let shell_binary = hook_binary_for_shell(shell, binary);
171        let fresh = match shell {
172            "fish" => generate_hook_fish(&shell_binary),
173            "powershell" => generate_hook_powershell(&shell_binary),
174            _ => generate_hook_posix(&shell_binary),
175        };
176        if current == fresh {
177            continue;
178        }
179        match std::fs::write(&path, fresh) {
180            Ok(()) => {
181                tracing::info!("refreshed stale shell hook {}", path.display());
182                posix_refreshed |= matches!(shell, "bash" | "zsh");
183            }
184            Err(e) => tracing::debug!("could not refresh {}: {e}", path.display()),
185        }
186    }
187    posix_refreshed
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn lc_shim_script_is_self_contained_fallback() {
196        let s = shim_script("_lc", "/usr/bin/lean-ctx", "-t");
197        assert!(s.starts_with("#!/bin/sh\n"), "needs a shebang: {s}");
198        assert!(s.contains("'/usr/bin/lean-ctx' -t \"$@\""), "{s}");
199        assert!(s.contains("exec \"$@\""), "{s}");
200        assert!(s.contains("CLAUDECODE"), "{s}");
201        assert!(s.contains("LEAN_CTX_DISABLED"), "{s}");
202    }
203
204    #[test]
205    fn lc_compress_shim_uses_compress_flag() {
206        let s = shim_script("_lc_compress", "/usr/bin/lean-ctx", "-c");
207        assert!(s.contains("'/usr/bin/lean-ctx' -c \"$@\""), "{s}");
208    }
209
210    /// #1959: a hook written by an older build (aliases → `_lc`) is brought up
211    /// to date without `init`; a shell the user never set up gets no hook.
212    #[test]
213    fn stale_installed_hooks_are_refreshed_and_absent_ones_left_alone() {
214        // The generator bakes config values in; keep them stable for both calls.
215        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
216        let tmp = tempfile::tempdir().expect("tempdir");
217        let bin = "/usr/local/bin/lean-ctx";
218        let hook = tmp.path().join("shell-hook.bash");
219        std::fs::write(&hook, "alias grep='_lc grep'\n").expect("write stale hook");
220
221        assert!(refresh_shell_hooks_in(tmp.path(), bin), "stale bash hook");
222        assert_eq!(
223            std::fs::read_to_string(&hook).expect("read hook"),
224            generate_hook_posix(bin)
225        );
226        assert!(!tmp.path().join("shell-hook.zsh").exists());
227        assert!(!tmp.path().join("shell-hook.fish").exists());
228        assert!(
229            !refresh_shell_hooks_in(tmp.path(), bin),
230            "a current hook is not rewritten"
231        );
232    }
233
234    #[test]
235    fn write_lc_path_shims_writes_both_executables() {
236        let tmp = tempfile::tempdir().expect("tempdir");
237        assert!(write_lc_path_shims_in(tmp.path(), "/usr/bin/lean-ctx"));
238        for name in ["_lc", "_lc_compress"] {
239            assert!(tmp.path().join(name).exists(), "missing shim {name}");
240        }
241    }
242
243    #[test]
244    fn write_lc_path_shims_reports_an_unwritable_dir() {
245        let tmp = tempfile::tempdir().expect("tempdir");
246        assert!(!write_lc_path_shims_in(
247            &tmp.path().join("missing"),
248            "/usr/bin/lean-ctx"
249        ));
250    }
251
252    /// #1851: a package manager keeps the binary in a versioned directory off
253    /// PATH and puts a launcher on PATH — the shims belong next to the launcher.
254    #[cfg(unix)]
255    mod lc_shim_dirs_1851 {
256        use super::super::lc_shim_dirs;
257        use std::path::{Path, PathBuf};
258
259        fn launcher_dir(root: &Path, rel: &str) -> PathBuf {
260            let dir = root.join(rel);
261            std::fs::create_dir_all(&dir).unwrap();
262            std::fs::write(dir.join("lean-ctx"), "#!/bin/sh\n").unwrap();
263            dir
264        }
265
266        #[test]
267        fn versioned_install_dir_off_path_is_skipped() {
268            let tmp = tempfile::tempdir().unwrap();
269            let apps = launcher_dir(tmp.path(), "scoop/apps/lean-ctx/3.10.2");
270            let shims = launcher_dir(tmp.path(), "scoop/shims");
271            let dirs = lc_shim_dirs(
272                Some(&apps.join("lean-ctx")),
273                &[tmp.path().join("usr/bin"), shims.clone()],
274                None,
275            );
276            assert_eq!(dirs, vec![shims]);
277        }
278
279        #[test]
280        fn exe_dir_on_path_comes_first_then_launchers_then_user_bin() {
281            let tmp = tempfile::tempdir().unwrap();
282            let home = tmp.path().join("home");
283            let user_bin = home.join(".local/bin");
284            std::fs::create_dir_all(&user_bin).unwrap();
285            let brew = launcher_dir(tmp.path(), "opt/homebrew/bin");
286            let exe_dir = launcher_dir(tmp.path(), "exe");
287            let dirs = lc_shim_dirs(
288                Some(&exe_dir.join("lean-ctx")),
289                &[brew.clone(), user_bin.clone(), exe_dir.clone()],
290                Some(&home),
291            );
292            assert_eq!(dirs, vec![exe_dir, brew, user_bin]);
293        }
294
295        #[test]
296        fn user_bin_off_path_is_not_a_candidate() {
297            let tmp = tempfile::tempdir().unwrap();
298            let home = tmp.path().join("home");
299            std::fs::create_dir_all(home.join(".local/bin")).unwrap();
300            let dirs = lc_shim_dirs(None, &[tmp.path().join("usr/bin")], Some(&home));
301            assert!(dirs.is_empty(), "{dirs:?}");
302        }
303    }
304}