Skip to main content

lean_ctx/
shell_hook.rs

1use std::path::{Path, PathBuf};
2use std::sync::OnceLock;
3
4use crate::{dropin, marked_block};
5
6/// Refresh of already-installed shell-hook files (#1959). The hook generator
7/// belongs to the CLI layer, which registers it at start-up; the MCP server
8/// runs it on start. Without a registration (library use, tests) there is
9/// nothing to refresh against, so the call does nothing.
10static INSTALLED_HOOK_REFRESH: OnceLock<fn()> = OnceLock::new();
11
12/// Register the installed shell-hook refresh. The first registration wins.
13pub fn register_installed_hook_refresh(refresh: fn()) {
14    let _ = INSTALLED_HOOK_REFRESH.set(refresh);
15}
16
17/// Bring installed shell hooks up to this binary, if a refresh is registered.
18pub fn refresh_installed_shell_hooks() {
19    if let Some(refresh) = INSTALLED_HOOK_REFRESH.get() {
20        refresh();
21    }
22}
23
24const MARKER_START: &str = "# >>> lean-ctx shell hook >>>";
25const MARKER_END: &str = "# <<< lean-ctx shell hook <<<";
26const ALIAS_START: &str = "# >>> lean-ctx agent aliases >>>";
27const ALIAS_END: &str = "# <<< lean-ctx agent aliases <<<";
28
29/// File name we use inside `.d/` directories. Stable so install / migration /
30/// uninstall can find it again without parsing. `00-` prefix sorts it ahead
31/// of other drop-ins so the agent intercept fires before any tool init.
32const DROPIN_ZSH: &str = "00-lean-ctx.zsh";
33const DROPIN_SH: &str = "00-lean-ctx.sh";
34
35/// Variables an agent host sets in its agent's shell; the shell hook
36/// redirects through lean-ctx when one is set.
37pub const KNOWN_AGENT_ENV_VARS: &[&str] = &[
38    "LEAN_CTX_AGENT",
39    "CLAUDECODE",
40    "CODEBUDDY",
41    "CODEX_CLI_SESSION",
42    "GEMINI_SESSION",
43];
44
45/// Further variables only an agent's process carries, beyond
46/// [`KNOWN_AGENT_ENV_VARS`]. Together they are the one list of agent
47/// markers ([`agent_env_marker`]) for commands an agent must not run.
48pub const MORE_AGENT_ENV_VARS: &[&str] = &[
49    "CURSOR_AGENT",
50    "CURSOR_TASK_ID",
51    "CODEX_SANDBOX",
52    "CODEX_THREAD_ID",
53    "LEAN_CTX_AGENT_ID",
54    "LCTX_AGENT_ID",
55    "AI_AGENT",
56];
57
58/// Every agent marker: [`KNOWN_AGENT_ENV_VARS`], then [`MORE_AGENT_ENV_VARS`].
59pub fn agent_env_markers() -> impl Iterator<Item = &'static str> {
60    KNOWN_AGENT_ENV_VARS
61        .iter()
62        .chain(MORE_AGENT_ENV_VARS)
63        .copied()
64}
65
66/// The first agent marker `is_set` reports.
67pub fn agent_env_marker(is_set: impl Fn(&str) -> bool) -> Option<&'static str> {
68    agent_env_markers().find(|name| is_set(name))
69}
70
71/// The first agent marker set (non-empty) in this process's environment.
72pub fn env_agent_marker() -> Option<&'static str> {
73    agent_env_marker(|name| std::env::var_os(name).is_some_and(|v| !v.is_empty()))
74}
75
76const AGENT_ALIASES: &[(&str, &str)] = &[
77    ("claude", "claude"),
78    ("codebuddy", "codebuddy"),
79    ("codex", "codex"),
80    ("gemini", "gemini"),
81];
82
83/// The `source <rc>` command for a given login-shell path, or `None` when the
84/// shell is unknown/unsupported (callers should fall back to "restart your
85/// shell"). Kept pure so it is deterministic to unit-test without mutating the
86/// process environment.
87fn source_command_for_shell(shell: &str) -> Option<&'static str> {
88    if shell.contains("zsh") {
89        Some("source ~/.zshrc")
90    } else if shell.contains("fish") {
91        Some("source ~/.config/fish/config.fish")
92    } else if shell.contains("bash") {
93        Some("source ~/.bashrc")
94    } else {
95        None
96    }
97}
98
99/// The `source <rc>` command for the user's current login shell (`$SHELL`), or
100/// `None` when it cannot be determined. Single source of truth so post-`setup`
101/// and post-`update` hints stay in sync and never advise sourcing a shell the
102/// user does not have (e.g. `~/.zshrc` on a bash-only system — see #321).
103pub fn shell_source_command() -> Option<&'static str> {
104    source_command_for_shell(&std::env::var("SHELL").unwrap_or_default())
105}
106
107/// The rc file path for a given login-shell path (pure, testable).
108fn rc_file_for_shell(shell: &str) -> &'static str {
109    if shell.contains("zsh") {
110        "~/.zshrc"
111    } else if shell.contains("fish") {
112        "~/.config/fish/config.fish"
113    } else if shell.contains("bash") {
114        "~/.bashrc"
115    } else {
116        "your shell config"
117    }
118}
119
120/// The rc file path for the user's current login shell (`$SHELL`), or a
121/// generic fallback when it cannot be determined. Used in help text and
122/// troubleshooting hints so they never hardcode a single shell's rc file.
123pub fn shell_rc_file() -> &'static str {
124    rc_file_for_shell(&std::env::var("SHELL").unwrap_or_default())
125}
126
127/// Human-facing one-liner telling the user how to load the refreshed aliases,
128/// tailored to their login shell. Used after `lean-ctx update`.
129pub fn reload_aliases_hint() -> String {
130    match shell_source_command() {
131        Some(cmd) => format!("Run '{cmd}' (or restart terminal) for updated shell aliases."),
132        None => "Restart your terminal to load updated shell aliases.".to_string(),
133    }
134}
135
136/// Installation style for the shell hook + agent aliases.
137///
138/// `Auto` (default) inspects each rc file to decide: if the file references
139/// an adjacent `.d/` directory from a non-comment line and that directory
140/// exists, install as a drop-in; otherwise fall back to an inline fenced
141/// block in the rc file itself.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143pub enum Style {
144    /// Force inline marked-block install in the parent rc file.
145    Inline,
146    /// Force drop-in file install in the adjacent `.d/` directory.
147    /// Falls back to `Inline` if no `.d/` source loop is configured.
148    DropIn,
149    /// Auto-detect per file.
150    #[default]
151    Auto,
152}
153
154/// Static description of a single install slot: which rc file, which
155/// adjacent drop-in directory + filename, and the marker pair for the
156/// inline form.
157#[derive(Debug, Clone, Copy)]
158struct Slot {
159    rc_file: &'static str,
160    dropin_dir: &'static str,
161    dropin_file: &'static str,
162    marker_start: &'static str,
163    marker_end: &'static str,
164}
165
166const SLOT_ZSHENV: Slot = Slot {
167    rc_file: ".zshenv",
168    dropin_dir: ".zshenv.d",
169    dropin_file: DROPIN_ZSH,
170    marker_start: MARKER_START,
171    marker_end: MARKER_END,
172};
173
174const SLOT_BASHENV: Slot = Slot {
175    rc_file: ".bashenv",
176    dropin_dir: ".bashenv.d",
177    dropin_file: DROPIN_SH,
178    marker_start: MARKER_START,
179    marker_end: MARKER_END,
180};
181
182const SLOT_ZSHRC: Slot = Slot {
183    rc_file: ".zshrc",
184    dropin_dir: ".zshrc.d",
185    dropin_file: DROPIN_ZSH,
186    marker_start: ALIAS_START,
187    marker_end: ALIAS_END,
188};
189
190const SLOT_BASHRC: Slot = Slot {
191    rc_file: ".bashrc",
192    dropin_dir: ".bashrc.d",
193    dropin_file: DROPIN_SH,
194    marker_start: ALIAS_START,
195    marker_end: ALIAS_END,
196};
197
198/// Resolved destination for a single install slot.
199enum InstallTarget {
200    Marked {
201        path: PathBuf,
202        start: &'static str,
203        end: &'static str,
204    },
205    DropIn {
206        dir: PathBuf,
207        filename: &'static str,
208    },
209}
210
211impl InstallTarget {
212    fn upsert(&self, content: &str, quiet: bool, label: &str) {
213        match self {
214            Self::Marked { path, start, end } => {
215                marked_block::upsert(path, start, end, content, quiet, label);
216            }
217            Self::DropIn { dir, filename } => dropin::write(dir, filename, content, quiet, label),
218        }
219    }
220}
221
222/// Decide where a particular hook should live.
223fn pick_target(home: &Path, slot: &Slot, style: Style) -> InstallTarget {
224    let inline = InstallTarget::Marked {
225        path: home.join(slot.rc_file),
226        start: slot.marker_start,
227        end: slot.marker_end,
228    };
229    match style {
230        Style::Inline => inline,
231        // DropIn and Auto both prefer dropin when available; only difference
232        // is whether we fall back silently (Auto) or could be made to warn
233        // (DropIn). Today they behave identically; the distinction lets
234        // callers express intent in the CLI surface later.
235        Style::DropIn | Style::Auto => match dropin::detect(home, slot.rc_file, slot.dropin_dir) {
236            Some(dir) => InstallTarget::DropIn {
237                dir,
238                filename: slot.dropin_file,
239            },
240            None => inline,
241        },
242    }
243}
244
245/// Pre-formatted timestamp suffix for migration backups.
246///
247/// Created **once per install run** and threaded through every per-slot
248/// install function, so all backups produced by a single
249/// `install_all_with_style` invocation share the same suffix. This
250/// rules out the "two near-simultaneous `Utc::now()` calls drifted by
251/// 1 ms across a second boundary" bug class, and makes the backups
252/// produced by one logical migration trivially groupable for the user
253/// (e.g. `ls ~ | grep lean-ctx-20260511T203845Z`).
254///
255/// Tests construct one via `BackupStamp::at(...)` to get deterministic
256/// filenames without touching the system clock.
257struct BackupStamp(String);
258
259impl BackupStamp {
260    /// Capture the current UTC time. Call this **once** at the top of
261    /// an install run.
262    fn now() -> Self {
263        Self::at(lean_ctx_time::UtcDateTime::now())
264    }
265
266    /// Inject a specific moment in time. Used by tests; can also be
267    /// used in future to align migration backups with a user-supplied
268    /// release marker.
269    fn at(stamp: lean_ctx_time::UtcDateTime) -> Self {
270        Self(stamp.format("%Y%m%dT%H%M%SZ").to_string())
271    }
272
273    /// Compose the full backup path for a given original file.
274    fn backup_path_for(&self, path: &Path) -> Option<PathBuf> {
275        let file_name = path.file_name().and_then(|n| n.to_str())?;
276        Some(path.with_file_name(format!("{file_name}.lean-ctx-{}.bak", self.0)))
277    }
278}
279
280/// Save a *timestamped* sibling backup of `path` before a destructive
281/// migration step. Filename pattern: `<basename>.lean-ctx-<UTC>.bak`,
282/// e.g. `.zshenv.lean-ctx-20260511T203845Z.bak`.
283///
284/// The block content owned by lean-ctx is normally treated as ours to
285/// rewrite — `marked_block::upsert` already strips and replaces it on
286/// every reinstall. That convention is acceptable for *idempotent
287/// reinstalls* (the canonical content is always the same) but loses
288/// information during a *style migration* if the user has hand-edited
289/// anywhere in the file, including inside our fenced region.
290///
291/// Deliberate divergence from the elsewhere-in-the-codebase convention
292/// (`cli::shell_init::backup_shell_config`, `config_io.rs`), which
293/// writes a single `<file>.lean-ctx.bak` and clobbers it on every
294/// invocation. That single-generation scheme is fine for "I backed
295/// this up moments ago before this exact reinstall" use cases, but
296/// risky for migration backups: a second migration event would
297/// silently overwrite the first, destroying potentially-unrecoverable
298/// user state. Timestamped names are append-only and let us migrate
299/// repeatedly (e.g. across multiple `lean-ctx update` runs over
300/// months) without ever losing a snapshot.
301fn save_migration_backup(path: &Path, quiet: bool, stamp: &BackupStamp) {
302    if !path.exists() {
303        return;
304    }
305    let Some(bak) = stamp.backup_path_for(path) else {
306        return;
307    };
308    match std::fs::copy(path, &bak) {
309        Ok(_) => {
310            if !quiet {
311                eprintln!("  Backup: {} -> {}", path.display(), bak.display());
312            }
313        }
314        Err(e) => {
315            tracing::warn!("Failed to back up {}: {e}", path.display());
316        }
317    }
318}
319
320/// When we install one style, sweep away any prior install of the *other*
321/// style so users transparently migrate (and so re-running setup never
322/// leaves the hook in two places).
323///
324/// Whenever a migration would clobber pre-existing user content (a
325/// fenced block in the rc file, or a hand-tweaked drop-in file), the
326/// affected file is copied to `<filename>.lean-ctx-<stamp>.bak` first
327/// (see `save_migration_backup`). The backup is only created when there
328/// is something to migrate AWAY from, so clean installs and idempotent
329/// reinstalls don't generate noise. `stamp` is taken by reference so
330/// all migrations within one `install_all` invocation share the same
331/// suffix.
332fn strip_other_style(
333    home: &Path,
334    slot: &Slot,
335    target: &InstallTarget,
336    quiet: bool,
337    label: &str,
338    stamp: &BackupStamp,
339) {
340    match target {
341        InstallTarget::Marked { .. } => {
342            // Installing inline: remove any drop-in file we previously wrote.
343            let dropin_dir = home.join(slot.dropin_dir);
344            let dropin_path = dropin_dir.join(slot.dropin_file);
345            if dropin_path.exists() {
346                // Hand-edits to the drop-in file would otherwise be lost.
347                // The backup lands next to the original; the `.bak`
348                // suffix keeps it out of any `*.zsh` source glob.
349                save_migration_backup(&dropin_path, quiet, stamp);
350                dropin::remove(&dropin_dir, slot.dropin_file, quiet, label);
351            }
352        }
353        InstallTarget::DropIn { .. } => {
354            // Installing drop-in: remove any prior inline fenced block.
355            // Back up the whole rc file first so anything between the
356            // markers (and any unrelated user edits to the same file)
357            // is recoverable from `<rc>.lean-ctx-<stamp>.bak`.
358            let rc_path = home.join(slot.rc_file);
359            if let Ok(existing) = std::fs::read_to_string(&rc_path)
360                && existing.contains(slot.marker_start)
361            {
362                save_migration_backup(&rc_path, quiet, stamp);
363            }
364            marked_block::remove_from_file(
365                &rc_path,
366                slot.marker_start,
367                slot.marker_end,
368                quiet,
369                label,
370            );
371        }
372    }
373}
374
375/// Public entrypoint: install with auto-detected style. Preserves the
376/// previous signature so existing callers (setup.rs, cli/shell_init.rs)
377/// don't need to change.
378pub fn install_all(quiet: bool) {
379    install_all_with_style(quiet, Style::Auto);
380}
381
382/// Explicit style entrypoint for callers that want to honour a `--style=`
383/// CLI flag.
384///
385/// Captures a single `BackupStamp` here so every migration backup
386/// produced by this invocation shares one suffix, even if the wall
387/// clock ticks over while we're walking the slots.
388pub fn install_all_with_style(quiet: bool, style: Style) {
389    let cfg = crate::core::config::Config::load();
390    if cfg.shell_hook_disabled_effective() {
391        if !quiet {
392            eprintln!(
393                "lean-ctx: shell hook disabled (shell_hook_disabled=true or LEAN_CTX_NO_HOOK).                  Skipping hook installation."
394            );
395        }
396        return;
397    }
398
399    let Some(home) = dirs::home_dir() else {
400        tracing::error!("Cannot resolve home directory");
401        return;
402    };
403
404    let stamp = BackupStamp::now();
405    if shell_available("zsh") {
406        install_zshenv(&home, quiet, style, &stamp);
407    }
408    if shell_available("bash") {
409        install_bashenv(&home, quiet, style, &stamp);
410    }
411    let cfg = crate::core::config::Config::load();
412    if cfg.skip_agent_aliases {
413        remove_agent_aliases(&home, quiet);
414    } else {
415        install_aliases(&home, quiet, style, &stamp);
416    }
417}
418
419/// Returns `true` if the given shell binary is installed on the system.
420/// Checks common installation paths without spawning a subprocess.
421///
422/// `LEAN_CTX_SHELL_HOOK_FORCE` overrides detection for environments where the
423/// shell lives in a non-standard path or is provisioned after install (minimal
424/// containers, custom images): set it to `1`/`true`/`all` to force every shell,
425/// or to a comma-separated list (e.g. `zsh,bash`) to force specific ones.
426#[cfg(unix)]
427fn shell_available(shell: &str) -> bool {
428    if let Ok(forced) = std::env::var("LEAN_CTX_SHELL_HOOK_FORCE") {
429        let forced = forced.trim();
430        if forced == "1"
431            || forced.eq_ignore_ascii_case("true")
432            || forced.eq_ignore_ascii_case("all")
433        {
434            return true;
435        }
436        if forced
437            .split(',')
438            .any(|s| s.trim().eq_ignore_ascii_case(shell))
439        {
440            return true;
441        }
442    }
443
444    let candidates: &[&str] = match shell {
445        "zsh" => &[
446            "/bin/zsh",
447            "/usr/bin/zsh",
448            "/usr/local/bin/zsh",
449            "/opt/homebrew/bin/zsh",
450        ],
451        "bash" => &[
452            "/bin/bash",
453            "/usr/bin/bash",
454            "/usr/local/bin/bash",
455            "/opt/homebrew/bin/bash",
456        ],
457        _ => return false,
458    };
459    candidates.iter().any(|p| Path::new(p).exists())
460}
461
462#[cfg(not(unix))]
463fn shell_available(_shell: &str) -> bool {
464    // On non-Unix platforms (Windows), shell hooks are not applicable.
465    false
466}
467
468pub fn uninstall_all(quiet: bool) {
469    let Some(home) = dirs::home_dir() else { return };
470
471    // Try both styles unconditionally for each slot. marked_block::remove
472    // and dropin::remove are both no-ops when their target is absent.
473    let slots: &[(Slot, &str)] = &[
474        (SLOT_ZSHENV, "shell hook for ~/.zshenv"),
475        (SLOT_BASHENV, "shell hook for ~/.bashenv"),
476        (SLOT_ZSHRC, "agent aliases for ~/.zshrc"),
477        (SLOT_BASHRC, "agent aliases for ~/.bashrc"),
478    ];
479
480    for (slot, label) in slots {
481        marked_block::remove_from_file(
482            &home.join(slot.rc_file),
483            slot.marker_start,
484            slot.marker_end,
485            quiet,
486            label,
487        );
488        let dir_path = home.join(slot.dropin_dir);
489        if dir_path.exists() {
490            dropin::remove(&dir_path, slot.dropin_file, quiet, label);
491        }
492    }
493}
494
495/// Substrings that flag a host's agent-exec *sandbox wrapper* — which reports
496/// the real command's exit status over a dedicated fd (e.g. Cursor's
497/// `dump_zsh_state >&4; builtin exit $?`) and passes the command as a positional
498/// arg — or lean-ctx's *own* hook invocations. The non-interactive
499/// `.zshenv`/`.bashenv` redirect must never `exec lean-ctx -c` over these:
500/// doing so discards the wrapper's fd handshake and positional command, so the
501/// IDE reports "no exit status" for every command (and lean-ctx's 120s/8MB cap
502/// truncates long output). Inside such hosts the lean-ctx editor extension +
503/// hooks already provide integration, so the redirect is moot there anyway.
504const REDIRECT_SKIP_MARKERS: &[&str] = &[
505    "__CURSOR_SANDBOX", // Cursor/VSCode agent-exec sandbox wrapper (shell-agnostic)
506    "dump_zsh_state",   // Cursor zsh exit-code fd handshake
507    "lean-ctx hook ",   // lean-ctx's own preToolUse hook commands
508];
509
510/// Render the guarded non-interactive redirect shared by the zsh and bash
511/// installers. `exec_var` is the host's command variable
512/// (`ZSH_EXECUTION_STRING` / `BASH_EXECUTION_STRING`) and `env_check` is the
513/// agent-detection clause from [`build_env_check`]. The emitted `if` fires only
514/// for genuine agent commands — never for sandbox wrappers or lean-ctx hooks
515/// (see [`REDIRECT_SKIP_MARKERS`]).
516fn redirect_block(exec_var: &str, env_check: &str) -> String {
517    let mut lines = vec![format!(
518        "if [[ -z \"$LEAN_CTX_ACTIVE\" && -z \"$LEAN_CTX_DISABLED\" && -z \"$LEAN_CTX_NO_HOOK\" && -n \"${exec_var}\" ]] \\"
519    )];
520    for marker in REDIRECT_SKIP_MARKERS {
521        lines.push(format!("  && [[ \"${exec_var}\" != *\"{marker}\"* ]] \\"));
522    }
523    lines.push("  && command -v lean-ctx &>/dev/null; then".to_string());
524    lines.push(format!("  if {env_check}; then"));
525    lines.push("    export LEAN_CTX_ACTIVE=1".to_string());
526    lines.push(format!("    exec lean-ctx -c \"${exec_var}\""));
527    lines.push("  fi".to_string());
528    lines.push("fi".to_string());
529    lines.join("\n")
530}
531
532fn install_zshenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
533    let redirect = redirect_block("ZSH_EXECUTION_STRING", &build_env_check());
534    let hook = format!(
535        r#"{MARKER_START}
536# Passthrough stubs: ensure the alias targets (lean_ctx_track/_compress,
537# legacy _lc/_lc_compress) exist in ALL zsh contexts
538# (non-interactive subshells, eval, agent harnesses) so aliases that
539# reference them degrade gracefully instead of "command not found".
540# The full shell-hook.zsh overrides these when loaded via .zshrc.
541_lc()          {{ command "$@"; }}
542_lc_compress() {{ command "$@"; }}
543lean_ctx_track()    {{ command "$@"; }}
544lean_ctx_compress() {{ command "$@"; }}
545{redirect}
546{MARKER_END}"#
547    );
548
549    let label = "shell hook in ~/.zshenv";
550    let target = pick_target(home, &SLOT_ZSHENV, style);
551    strip_other_style(home, &SLOT_ZSHENV, &target, quiet, label, stamp);
552    target.upsert(&hook, quiet, label);
553}
554
555fn install_bashenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
556    let redirect = redirect_block("BASH_EXECUTION_STRING", &build_env_check());
557    let hook = format!(
558        r#"{MARKER_START}
559_lc()          {{ command "$@"; }}
560_lc_compress() {{ command "$@"; }}
561lean_ctx_track()    {{ command "$@"; }}
562lean_ctx_compress() {{ command "$@"; }}
563{redirect}
564{MARKER_END}"#
565    );
566
567    let label = "shell hook in ~/.bashenv";
568    let target = pick_target(home, &SLOT_BASHENV, style);
569    strip_other_style(home, &SLOT_BASHENV, &target, quiet, label, stamp);
570    target.upsert(&hook, quiet, label);
571}
572
573fn install_aliases(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
574    let mut lines = Vec::new();
575    lines.push(ALIAS_START.to_string());
576    for (alias_name, bin_name) in AGENT_ALIASES {
577        lines.push(format!(
578            "alias {alias_name}='LEAN_CTX_AGENT=1 BASH_ENV=\"$HOME/.bashenv\" {bin_name}'"
579        ));
580    }
581    lines.push(ALIAS_END.to_string());
582    let block = lines.join("\n");
583
584    for slot in &[SLOT_ZSHRC, SLOT_BASHRC] {
585        // Only act on rc files the user actually has. (Drop-in mode keys off
586        // the parent rc anyway — see `dropin::detect`.)
587        if !home.join(slot.rc_file).exists() {
588            continue;
589        }
590        let label = format!("agent aliases in ~/{}", slot.rc_file);
591        let target = pick_target(home, slot, style);
592        strip_other_style(home, slot, &target, quiet, &label, stamp);
593        target.upsert(&block, quiet, &label);
594    }
595}
596
597/// Remove agent alias blocks from rc files without touching the env hook.
598/// Called when `skip_agent_aliases = true` to clean up previously installed blocks.
599fn remove_agent_aliases(home: &Path, quiet: bool) {
600    for slot in &[SLOT_ZSHRC, SLOT_BASHRC] {
601        let rc = home.join(slot.rc_file);
602        if !rc.exists() {
603            continue;
604        }
605        if let Ok(content) = std::fs::read_to_string(&rc)
606            && content.contains(ALIAS_START)
607        {
608            let filtered: Vec<&str> = content
609                .lines()
610                .scan(false, |inside, line| {
611                    if line.trim() == ALIAS_START {
612                        *inside = true;
613                        return Some(None);
614                    }
615                    if *inside && line.trim() == ALIAS_END {
616                        *inside = false;
617                        return Some(None);
618                    }
619                    if *inside {
620                        Some(None)
621                    } else {
622                        Some(Some(line))
623                    }
624                })
625                .flatten()
626                .collect();
627            let _ = std::fs::write(&rc, filtered.join("\n") + "\n");
628            if !quiet {
629                println!(
630                    "  \x1b[33m⊖\x1b[0m Removed agent aliases from ~/{}",
631                    slot.rc_file
632                );
633            }
634        }
635        // Remove drop-in file
636        let dropin = home.join(slot.dropin_dir).join(slot.dropin_file);
637        if dropin.exists() {
638            let _ = std::fs::remove_file(&dropin);
639            if !quiet {
640                println!(
641                    "  \x1b[33m⊖\x1b[0m Removed drop-in ~/{}/{}",
642                    slot.dropin_dir, slot.dropin_file
643                );
644            }
645        }
646    }
647}
648
649fn build_env_check() -> String {
650    let checks: Vec<String> = KNOWN_AGENT_ENV_VARS
651        .iter()
652        .map(|v| format!("-n \"${v}\""))
653        .collect();
654    format!("[[ {} ]]", checks.join(" || "))
655}
656
657#[cfg(any(test, feature = "test-support"))]
658#[doc(hidden)]
659pub mod test_helpers {
660    use super::redirect_block;
661    pub fn redirect_block_for_test(exec_var: &str, env_check: &str) -> String {
662        redirect_block(exec_var, env_check)
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    /// Fixed deterministic stamp for tests that don't care about
671    /// distinguishing migration generations. Tests that *do* care
672    /// (e.g. the no-clobber regression) construct their own.
673    fn test_stamp() -> BackupStamp {
674        BackupStamp::at(
675            lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
676                .unwrap()
677                .to_utc(),
678        )
679    }
680
681    #[test]
682    fn env_check_format() {
683        let check = build_env_check();
684        assert!(check.contains("LEAN_CTX_AGENT"));
685        assert!(check.contains("CLAUDECODE"));
686        assert!(check.contains("CODEBUDDY"));
687        assert!(check.contains("||"));
688    }
689
690    #[test]
691    fn source_command_matches_login_shell() {
692        // Bash-only users must never be told to source ~/.zshrc (#321).
693        assert_eq!(
694            source_command_for_shell("/usr/bin/bash"),
695            Some("source ~/.bashrc")
696        );
697        assert_eq!(
698            source_command_for_shell("/bin/zsh"),
699            Some("source ~/.zshrc")
700        );
701        assert_eq!(
702            source_command_for_shell("/usr/local/bin/fish"),
703            Some("source ~/.config/fish/config.fish")
704        );
705        // Unknown / unset shell → no rc suggestion (caller falls back).
706        assert_eq!(source_command_for_shell(""), None);
707        assert_eq!(source_command_for_shell("/bin/false"), None);
708    }
709
710    #[test]
711    fn rc_file_matches_login_shell() {
712        // #321: hints must name the right rc file for the user's shell.
713        assert_eq!(rc_file_for_shell("/usr/bin/bash"), "~/.bashrc");
714        assert_eq!(rc_file_for_shell("/bin/zsh"), "~/.zshrc");
715        assert_eq!(
716            rc_file_for_shell("/usr/local/bin/fish"),
717            "~/.config/fish/config.fish"
718        );
719        assert_eq!(rc_file_for_shell(""), "your shell config");
720        assert_eq!(rc_file_for_shell("/bin/false"), "your shell config");
721    }
722
723    #[test]
724    fn pick_target_inline_when_forced() {
725        let tmp = tempfile::tempdir().unwrap();
726        // Even with a .d/ loop, Style::Inline must force the marked target.
727        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
728        std::fs::write(
729            tmp.path().join(".zshenv"),
730            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
731        )
732        .unwrap();
733        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Inline);
734        assert!(matches!(t, InstallTarget::Marked { .. }));
735    }
736
737    #[test]
738    fn pick_target_dropin_when_detected_under_auto() {
739        let tmp = tempfile::tempdir().unwrap();
740        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
741        std::fs::write(
742            tmp.path().join(".zshenv"),
743            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
744        )
745        .unwrap();
746        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
747        assert!(matches!(t, InstallTarget::DropIn { .. }));
748    }
749
750    #[test]
751    fn pick_target_inline_under_auto_when_no_dropin() {
752        let tmp = tempfile::tempdir().unwrap();
753        std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
754        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
755        assert!(matches!(t, InstallTarget::Marked { .. }));
756    }
757
758    #[test]
759    fn pick_target_dropin_falls_back_to_inline_when_no_directory() {
760        // User asked for DropIn but the layout isn't set up. Don't error —
761        // fall back to inline so the install still works.
762        let tmp = tempfile::tempdir().unwrap();
763        std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
764        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::DropIn);
765        assert!(matches!(t, InstallTarget::Marked { .. }));
766    }
767
768    #[test]
769    fn install_zshenv_writes_inline_block() {
770        let tmp = tempfile::tempdir().unwrap();
771        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
772        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
773        assert!(body.contains(MARKER_START));
774        assert!(body.contains(MARKER_END));
775        assert!(body.contains("ZSH_EXECUTION_STRING"));
776    }
777
778    #[test]
779    fn install_zshenv_writes_dropin_when_loop_present() {
780        let tmp = tempfile::tempdir().unwrap();
781        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
782        std::fs::write(
783            tmp.path().join(".zshenv"),
784            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
785        )
786        .unwrap();
787        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
788
789        let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
790        assert!(dropin_file.exists(), "expected drop-in file");
791        let dropin_body = std::fs::read_to_string(&dropin_file).unwrap();
792        assert!(dropin_body.contains("ZSH_EXECUTION_STRING"));
793
794        let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
795        assert!(
796            !zshenv_body.contains(MARKER_START),
797            "drop-in install must not also leave the inline block"
798        );
799    }
800
801    /// List sibling files of `path` whose name matches
802    /// `<basename>.lean-ctx-<timestamp>.bak`.
803    fn find_migration_backups(path: &Path) -> Vec<PathBuf> {
804        let Some(parent) = path.parent() else {
805            return Vec::new();
806        };
807        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
808            return Vec::new();
809        };
810        let prefix = format!("{name}.lean-ctx-");
811        let mut out: Vec<PathBuf> = std::fs::read_dir(parent)
812            .into_iter()
813            .flatten()
814            .flatten()
815            .map(|e| e.path())
816            .filter(|p| {
817                p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
818                    n.starts_with(&prefix)
819                        && std::path::Path::new(n)
820                            .extension()
821                            .is_some_and(|ext| ext.eq_ignore_ascii_case("bak"))
822                })
823            })
824            .collect();
825        out.sort();
826        out
827    }
828
829    #[test]
830    fn migration_inline_to_dropin_preserves_hand_edits_via_backup() {
831        let tmp = tempfile::tempdir().unwrap();
832        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
833        // Existing install with a hand-edit *inside* our fenced region —
834        // the bit a maintainer might worry about losing silently.
835        let edited_zshenv = format!(
836            "export PATH=/usr/bin\n\
837             \n\
838             {MARKER_START}\n\
839             # USER CUSTOM: bump zsh history size for this workstation\n\
840             export HISTSIZE=99999\n\
841             # original lean-ctx hook content lived here\n\
842             {MARKER_END}\n\
843             \n\
844             for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
845        );
846        std::fs::write(tmp.path().join(".zshenv"), &edited_zshenv).unwrap();
847
848        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
849
850        // Backup must exist and contain the user's exact pre-migration file.
851        let baks = find_migration_backups(&tmp.path().join(".zshenv"));
852        assert_eq!(baks.len(), 1, "expected one timestamped backup");
853        let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
854        assert_eq!(bak_body, edited_zshenv);
855        assert!(bak_body.contains("USER CUSTOM"));
856        assert!(bak_body.contains("HISTSIZE=99999"));
857    }
858
859    #[test]
860    fn migration_dropin_to_inline_preserves_hand_edits_via_backup() {
861        let tmp = tempfile::tempdir().unwrap();
862        let dropin_dir = tmp.path().join(".zshenv.d");
863        std::fs::create_dir_all(&dropin_dir).unwrap();
864        // Pre-stage a drop-in file with user customisation.
865        let edited_dropin = "# USER CUSTOM addition to lean-ctx drop-in\nexport FAVOURITE_EDITOR=helix\n# canonical lean-ctx content would follow\n";
866        std::fs::write(dropin_dir.join(DROPIN_ZSH), edited_dropin).unwrap();
867        // No source loop -> Style::Auto resolves to inline (so we migrate
868        // *away* from the drop-in).
869        std::fs::write(tmp.path().join(".zshenv"), "# plain zshenv\n").unwrap();
870
871        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
872
873        let baks = find_migration_backups(&dropin_dir.join(DROPIN_ZSH));
874        assert_eq!(baks.len(), 1, "expected one timestamped backup");
875        let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
876        assert_eq!(bak_body, edited_dropin);
877        assert!(bak_body.contains("USER CUSTOM"));
878        // The original drop-in is gone, replaced by an inline block in .zshenv.
879        assert!(!dropin_dir.join(DROPIN_ZSH).exists());
880        let zshenv = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
881        assert!(zshenv.contains(MARKER_START));
882    }
883
884    #[test]
885    fn migration_skips_backup_when_no_prior_block_exists() {
886        // Clean install (no prior lean-ctx artifacts) should not litter
887        // the home dir with empty `.lean-ctx-<ts>.bak` files.
888        let tmp = tempfile::tempdir().unwrap();
889        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
890        std::fs::write(
891            tmp.path().join(".zshenv"),
892            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
893        )
894        .unwrap();
895
896        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
897
898        assert!(
899            find_migration_backups(&tmp.path().join(".zshenv")).is_empty(),
900            "clean install should not create a .bak file"
901        );
902    }
903
904    #[test]
905    fn idempotent_dropin_reinstall_does_not_create_backup() {
906        // Once installed in drop-in mode, a second `install` (e.g. via
907        // `lean-ctx update` re-wiring) should not start producing backups
908        // every run. The strip-other-style path only fires when there IS
909        // an inline block to remove.
910        let tmp = tempfile::tempdir().unwrap();
911        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
912        std::fs::write(
913            tmp.path().join(".zshenv"),
914            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
915        )
916        .unwrap();
917
918        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
919        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
920
921        {
922            let found = &find_migration_backups(&tmp.path().join(".zshenv"));
923            assert!(found.is_empty(), "{found:?}");
924        }
925    }
926
927    #[test]
928    fn backup_filename_handles_dotfile_correctly() {
929        // `.zshenv` has no extension; Path::with_extension would replace
930        // ".zshenv" wholesale. Using with_file_name produces the right
931        // sibling path. Timestamp is appended between basename and `.bak`.
932        let tmp = tempfile::tempdir().unwrap();
933        std::fs::write(tmp.path().join(".zshenv"), "content\n").unwrap();
934        save_migration_backup(&tmp.path().join(".zshenv"), true, &test_stamp());
935        let baks = find_migration_backups(&tmp.path().join(".zshenv"));
936        assert_eq!(baks.len(), 1);
937        // The full filename must start with the original basename so it
938        // sits as a sibling, not at the parent root.
939        let name = baks[0].file_name().unwrap().to_str().unwrap();
940        assert!(name.starts_with(".zshenv.lean-ctx-"), "got: {name}");
941        assert!(
942            std::path::Path::new(name)
943                .extension()
944                .is_some_and(|ext| ext.eq_ignore_ascii_case("bak"))
945        );
946        // Sanity-check the timestamp is in the YYYYMMDDTHHMMSSZ slot.
947        let stamp = name
948            .trim_start_matches(".zshenv.lean-ctx-")
949            .trim_end_matches(".bak");
950        assert_eq!(stamp.len(), 16, "stamp should be YYYYMMDDTHHMMSSZ: {stamp}");
951        assert!(stamp.contains('T'));
952        assert!(stamp.ends_with('Z'));
953    }
954
955    #[test]
956    fn repeated_migrations_never_clobber_prior_backups() {
957        // Regression test for the convention upgrade: two migration
958        // events on the same slot must produce two distinct backups,
959        // not silently overwrite each other. We pin two different
960        // stamps directly instead of sleeping past a second boundary.
961        let stamp_first = BackupStamp::at(
962            lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
963                .unwrap()
964                .to_utc(),
965        );
966        let stamp_later = BackupStamp::at(
967            lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-05-12T09:00:00Z")
968                .unwrap()
969                .to_utc(),
970        );
971        let tmp = tempfile::tempdir().unwrap();
972        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
973
974        let with_block_v1 = format!(
975            "{MARKER_START}\n# first-era custom content\n{MARKER_END}\n\nfor f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
976        );
977        std::fs::write(tmp.path().join(".zshenv"), &with_block_v1).unwrap();
978        install_zshenv(tmp.path(), true, Style::Auto, &stamp_first);
979        let baks_after_first = find_migration_backups(&tmp.path().join(".zshenv"));
980        assert_eq!(baks_after_first.len(), 1);
981
982        // User hand-puts a NEW inline block back (perhaps via a manual
983        // edit or a partial reinstall in a tool we don't know about).
984        let with_block_v2 = format!(
985            "{}{MARKER_START}\n# second-era custom content\n{MARKER_END}\n",
986            std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap(),
987        );
988        std::fs::write(tmp.path().join(".zshenv"), &with_block_v2).unwrap();
989        install_zshenv(tmp.path(), true, Style::Auto, &stamp_later);
990        let baks_after_second = find_migration_backups(&tmp.path().join(".zshenv"));
991
992        assert_eq!(
993            baks_after_second.len(),
994            2,
995            "second migration should leave a second backup, not overwrite"
996        );
997        // First backup unchanged from after the first migration.
998        assert_eq!(baks_after_second[0], baks_after_first[0]);
999        let first_body = std::fs::read_to_string(&baks_after_second[0]).unwrap();
1000        let second_body = std::fs::read_to_string(&baks_after_second[1]).unwrap();
1001        assert!(first_body.contains("first-era custom"));
1002        assert!(second_body.contains("second-era custom"));
1003    }
1004
1005    #[test]
1006    fn install_migrates_inline_to_dropin() {
1007        let tmp = tempfile::tempdir().unwrap();
1008        // Simulate an existing install: .zshenv with the old fenced block.
1009        std::fs::write(
1010            tmp.path().join(".zshenv"),
1011            format!(
1012                "export PATH=/usr/bin\n\n{MARKER_START}\n# old hook\n{MARKER_END}\n\nfor f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
1013            ),
1014        )
1015        .unwrap();
1016        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
1017
1018        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1019
1020        let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1021        assert!(
1022            !zshenv_body.contains(MARKER_START),
1023            "old inline block should be stripped after migration"
1024        );
1025        assert!(
1026            zshenv_body.contains(".zshenv.d"),
1027            "source loop must be preserved"
1028        );
1029        let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
1030        assert!(dropin_file.exists(), "new drop-in file should be present");
1031    }
1032
1033    #[test]
1034    fn install_migrates_dropin_to_inline() {
1035        let tmp = tempfile::tempdir().unwrap();
1036        // No source loop → Style::Inline forces inline. Pre-stage a
1037        // leftover drop-in file as if the user previously had the layout.
1038        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
1039        std::fs::write(
1040            tmp.path().join(".zshenv.d").join(DROPIN_ZSH),
1041            "# stale lean-ctx drop-in\n",
1042        )
1043        .unwrap();
1044        std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
1045
1046        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1047
1048        assert!(
1049            !tmp.path().join(".zshenv.d").join(DROPIN_ZSH).exists(),
1050            "drop-in file should be removed when installing inline"
1051        );
1052        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1053        assert!(body.contains(MARKER_START));
1054    }
1055
1056    #[test]
1057    fn install_is_idempotent_in_dropin_mode() {
1058        let tmp = tempfile::tempdir().unwrap();
1059        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
1060        std::fs::write(
1061            tmp.path().join(".zshenv"),
1062            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
1063        )
1064        .unwrap();
1065
1066        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1067        let after_first = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
1068
1069        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1070        let after_second = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
1071
1072        assert_eq!(after_first, after_second);
1073    }
1074
1075    #[test]
1076    fn install_is_idempotent_in_inline_mode() {
1077        let tmp = tempfile::tempdir().unwrap();
1078        std::fs::write(tmp.path().join(".zshenv"), "# top\n").unwrap();
1079
1080        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1081        let after_first = std::fs::read(tmp.path().join(".zshenv")).unwrap();
1082
1083        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1084        let after_second = std::fs::read(tmp.path().join(".zshenv")).unwrap();
1085
1086        assert_eq!(after_first, after_second);
1087    }
1088
1089    #[test]
1090    fn install_aliases_skips_when_rc_missing() {
1091        let tmp = tempfile::tempdir().unwrap();
1092        // No .zshrc, no .bashrc — nothing should be created.
1093        install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
1094        assert!(!tmp.path().join(".zshrc").exists());
1095        assert!(!tmp.path().join(".bashrc").exists());
1096    }
1097
1098    #[test]
1099    fn install_aliases_writes_dropin_when_zshrc_d_configured() {
1100        let tmp = tempfile::tempdir().unwrap();
1101        std::fs::create_dir_all(tmp.path().join(".zshrc.d")).unwrap();
1102        std::fs::write(
1103            tmp.path().join(".zshrc"),
1104            "for f in $HOME/.zshrc.d/*.zsh; do source $f; done\n",
1105        )
1106        .unwrap();
1107
1108        install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
1109
1110        let dropin_file = tmp.path().join(".zshrc.d").join(DROPIN_ZSH);
1111        assert!(dropin_file.exists());
1112        let body = std::fs::read_to_string(&dropin_file).unwrap();
1113        assert!(body.contains("LEAN_CTX_AGENT=1"));
1114    }
1115
1116    // --- #255: Passthrough stubs for non-interactive subshells ---
1117
1118    #[test]
1119    fn zshenv_hook_contains_lc_passthrough_stubs() {
1120        let tmp = tempfile::tempdir().unwrap();
1121        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1122        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1123        assert!(
1124            body.contains(r#"_lc()          { command "$@"; }"#),
1125            "zshenv must contain _lc passthrough stub"
1126        );
1127        assert!(
1128            body.contains(r#"_lc_compress() { command "$@"; }"#),
1129            "zshenv must contain _lc_compress passthrough stub"
1130        );
1131    }
1132
1133    #[test]
1134    fn bashenv_hook_contains_lc_passthrough_stubs() {
1135        let tmp = tempfile::tempdir().unwrap();
1136        install_bashenv(tmp.path(), true, Style::Inline, &test_stamp());
1137        let body = std::fs::read_to_string(tmp.path().join(".bashenv")).unwrap();
1138        assert!(
1139            body.contains(r#"_lc()          { command "$@"; }"#),
1140            "bashenv must contain _lc passthrough stub"
1141        );
1142        assert!(
1143            body.contains(r#"_lc_compress() { command "$@"; }"#),
1144            "bashenv must contain _lc_compress passthrough stub"
1145        );
1146    }
1147
1148    #[test]
1149    fn stubs_appear_before_exec_guard() {
1150        let tmp = tempfile::tempdir().unwrap();
1151        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1152        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1153        let stub_pos = body.find("_lc()").expect("_lc stub must exist");
1154        let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1155        assert!(
1156            stub_pos < exec_pos,
1157            "stubs must be defined BEFORE the exec guard"
1158        );
1159    }
1160
1161    #[test]
1162    fn bash_stubs_appear_before_exec_guard() {
1163        // git-bash on Windows runs the agent's commands non-interactively, where
1164        // `.bashenv` is the only startup file bash sources (and only when BASH_ENV
1165        // points at it). The `_lc`/`_lc_compress` stubs must therefore be defined
1166        // BEFORE the exec guard so a residual aliased token never breaks with
1167        // `_lc: command not found` even if the guard's env-check bails (#589).
1168        let tmp = tempfile::tempdir().unwrap();
1169        install_bashenv(tmp.path(), true, Style::Inline, &test_stamp());
1170        let body = std::fs::read_to_string(tmp.path().join(".bashenv")).unwrap();
1171        let stub_pos = body.find("_lc()").expect("_lc stub must exist");
1172        let compress_pos = body
1173            .find("_lc_compress()")
1174            .expect("_lc_compress stub must exist");
1175        let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1176        assert!(
1177            stub_pos < exec_pos && compress_pos < exec_pos,
1178            "bash stubs must be defined BEFORE the exec guard"
1179        );
1180    }
1181
1182    // --- IDE agent-exec sandbox + lean-ctx hook guard ---
1183    // The non-interactive redirect must never `exec lean-ctx -c` over a host's
1184    // agent-exec sandbox wrapper (which reports the exit code via a dedicated fd:
1185    // `dump_zsh_state >&4; builtin exit $?`) or lean-ctx's own hooks: doing so
1186    // breaks the fd handshake so the IDE reports "no exit status" for every
1187    // command (and the 120s/8MB cap truncates output). See REDIRECT_SKIP_MARKERS.
1188
1189    #[test]
1190    fn redirect_block_guards_every_skip_marker() {
1191        let block = redirect_block("ZSH_EXECUTION_STRING", "[[ -n \"$LEAN_CTX_AGENT\" ]]");
1192        let exec_pos = block
1193            .find("exec lean-ctx")
1194            .expect("redirect must exec lean-ctx");
1195        for marker in REDIRECT_SKIP_MARKERS {
1196            let guard = format!("[[ \"$ZSH_EXECUTION_STRING\" != *\"{marker}\"* ]]");
1197            let guard_pos = block
1198                .find(&guard)
1199                .unwrap_or_else(|| panic!("redirect must guard against {marker:?}:\n{block}"));
1200            assert!(
1201                guard_pos < exec_pos,
1202                "guard for {marker:?} must precede the exec redirect"
1203            );
1204        }
1205    }
1206
1207    #[test]
1208    fn zshenv_redirect_skips_ide_sandbox_and_hooks() {
1209        let tmp = tempfile::tempdir().unwrap();
1210        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1211        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1212        let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1213        for marker in REDIRECT_SKIP_MARKERS {
1214            let guard = format!("[[ \"$ZSH_EXECUTION_STRING\" != *\"{marker}\"* ]]");
1215            let pos = body
1216                .find(&guard)
1217                .unwrap_or_else(|| panic!(".zshenv must guard against {marker:?}"));
1218            assert!(
1219                pos < exec_pos,
1220                "zshenv guard {marker:?} must precede the exec redirect"
1221            );
1222        }
1223    }
1224
1225    #[test]
1226    fn bashenv_redirect_skips_ide_sandbox_and_hooks() {
1227        let tmp = tempfile::tempdir().unwrap();
1228        install_bashenv(tmp.path(), true, Style::Inline, &test_stamp());
1229        let body = std::fs::read_to_string(tmp.path().join(".bashenv")).unwrap();
1230        let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1231        for marker in REDIRECT_SKIP_MARKERS {
1232            let guard = format!("[[ \"$BASH_EXECUTION_STRING\" != *\"{marker}\"* ]]");
1233            let pos = body
1234                .find(&guard)
1235                .unwrap_or_else(|| panic!(".bashenv must guard against {marker:?}"));
1236            assert!(
1237                pos < exec_pos,
1238                "bashenv guard {marker:?} must precede the exec redirect"
1239            );
1240        }
1241    }
1242
1243    #[test]
1244    fn dropin_zshenv_also_contains_stubs() {
1245        let tmp = tempfile::tempdir().unwrap();
1246        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
1247        std::fs::write(
1248            tmp.path().join(".zshenv"),
1249            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
1250        )
1251        .unwrap();
1252        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1253
1254        let dropin = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
1255        let body = std::fs::read_to_string(&dropin).unwrap();
1256        assert!(body.contains("_lc()"), "drop-in must also contain stubs");
1257    }
1258
1259    // --- #309: shell_available guards ---
1260
1261    /// Serialises the env-sensitive `shell_available` tests so one setting
1262    /// `LEAN_CTX_SHELL_HOOK_FORCE` can't race the filesystem-match assertions.
1263    #[cfg(unix)]
1264    static SHELL_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1265
1266    #[cfg(unix)]
1267    #[test]
1268    fn shell_available_rejects_unknown_shell() {
1269        let _env_lock = crate::core::data_dir::test_env_lock();
1270        let _g = SHELL_ENV_LOCK
1271            .lock()
1272            .unwrap_or_else(std::sync::PoisonError::into_inner);
1273        crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1274        assert!(!shell_available("fish"));
1275        assert!(!shell_available("nushell"));
1276        assert!(!shell_available(""));
1277    }
1278
1279    #[cfg(unix)]
1280    #[test]
1281    fn shell_available_finds_installed_shells() {
1282        let _env_lock = crate::core::data_dir::test_env_lock();
1283        let _g = SHELL_ENV_LOCK
1284            .lock()
1285            .unwrap_or_else(std::sync::PoisonError::into_inner);
1286        crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1287        // On any Unix CI/dev machine at least one of bash/zsh should exist.
1288        let has_bash = Path::new("/bin/bash").exists() || Path::new("/usr/bin/bash").exists();
1289        let has_zsh = Path::new("/bin/zsh").exists() || Path::new("/usr/bin/zsh").exists();
1290        assert!(
1291            shell_available("bash") == has_bash,
1292            "shell_available(bash) should match filesystem"
1293        );
1294        assert!(
1295            shell_available("zsh") == has_zsh,
1296            "shell_available(zsh) should match filesystem"
1297        );
1298    }
1299
1300    #[cfg(unix)]
1301    #[test]
1302    fn shell_hook_force_overrides_detection() {
1303        let _env_lock = crate::core::data_dir::test_env_lock();
1304        let _g = SHELL_ENV_LOCK
1305            .lock()
1306            .unwrap_or_else(std::sync::PoisonError::into_inner);
1307
1308        // `all` forces every shell, even ones not on disk.
1309        crate::test_env::set_var("LEAN_CTX_SHELL_HOOK_FORCE", "all");
1310        assert!(shell_available("zsh"));
1311        assert!(shell_available("bash"));
1312
1313        // A comma list forces only the named shells.
1314        crate::test_env::set_var("LEAN_CTX_SHELL_HOOK_FORCE", "zsh");
1315        assert!(shell_available("zsh"));
1316        // `bash` falls back to filesystem detection here; assert only the
1317        // forced-on guarantee to stay host-independent.
1318
1319        crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1320    }
1321}