Skip to main content

lean_ctx/
shell_hook.rs

1use std::path::{Path, PathBuf};
2
3use crate::{dropin, marked_block};
4
5const MARKER_START: &str = "# >>> lean-ctx shell hook >>>";
6const MARKER_END: &str = "# <<< lean-ctx shell hook <<<";
7const ALIAS_START: &str = "# >>> lean-ctx agent aliases >>>";
8const ALIAS_END: &str = "# <<< lean-ctx agent aliases <<<";
9
10/// File name we use inside `.d/` directories. Stable so install / migration /
11/// uninstall can find it again without parsing. `00-` prefix sorts it ahead
12/// of other drop-ins so the agent intercept fires before any tool init.
13const DROPIN_ZSH: &str = "00-lean-ctx.zsh";
14const DROPIN_SH: &str = "00-lean-ctx.sh";
15
16const KNOWN_AGENT_ENV_VARS: &[&str] = &[
17    "LEAN_CTX_AGENT",
18    "CLAUDECODE",
19    "CODEX_CLI_SESSION",
20    "GEMINI_SESSION",
21];
22
23const AGENT_ALIASES: &[(&str, &str)] = &[
24    ("claude", "claude"),
25    ("codex", "codex"),
26    ("gemini", "gemini"),
27];
28
29/// Installation style for the shell hook + agent aliases.
30///
31/// `Auto` (default) inspects each rc file to decide: if the file references
32/// an adjacent `.d/` directory from a non-comment line and that directory
33/// exists, install as a drop-in; otherwise fall back to an inline fenced
34/// block in the rc file itself.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Style {
37    /// Force inline marked-block install in the parent rc file.
38    Inline,
39    /// Force drop-in file install in the adjacent `.d/` directory.
40    /// Falls back to `Inline` if no `.d/` source loop is configured.
41    DropIn,
42    /// Auto-detect per file.
43    #[default]
44    Auto,
45}
46
47/// Static description of a single install slot: which rc file, which
48/// adjacent drop-in directory + filename, and the marker pair for the
49/// inline form.
50#[derive(Debug, Clone, Copy)]
51struct Slot {
52    rc_file: &'static str,
53    dropin_dir: &'static str,
54    dropin_file: &'static str,
55    marker_start: &'static str,
56    marker_end: &'static str,
57}
58
59const SLOT_ZSHENV: Slot = Slot {
60    rc_file: ".zshenv",
61    dropin_dir: ".zshenv.d",
62    dropin_file: DROPIN_ZSH,
63    marker_start: MARKER_START,
64    marker_end: MARKER_END,
65};
66
67const SLOT_BASHENV: Slot = Slot {
68    rc_file: ".bashenv",
69    dropin_dir: ".bashenv.d",
70    dropin_file: DROPIN_SH,
71    marker_start: MARKER_START,
72    marker_end: MARKER_END,
73};
74
75const SLOT_ZSHRC: Slot = Slot {
76    rc_file: ".zshrc",
77    dropin_dir: ".zshrc.d",
78    dropin_file: DROPIN_ZSH,
79    marker_start: ALIAS_START,
80    marker_end: ALIAS_END,
81};
82
83const SLOT_BASHRC: Slot = Slot {
84    rc_file: ".bashrc",
85    dropin_dir: ".bashrc.d",
86    dropin_file: DROPIN_SH,
87    marker_start: ALIAS_START,
88    marker_end: ALIAS_END,
89};
90
91/// Resolved destination for a single install slot.
92enum InstallTarget {
93    Marked {
94        path: PathBuf,
95        start: &'static str,
96        end: &'static str,
97    },
98    DropIn {
99        dir: PathBuf,
100        filename: &'static str,
101    },
102}
103
104impl InstallTarget {
105    fn upsert(&self, content: &str, quiet: bool, label: &str) {
106        match self {
107            Self::Marked { path, start, end } => {
108                marked_block::upsert(path, start, end, content, quiet, label);
109            }
110            Self::DropIn { dir, filename } => dropin::write(dir, filename, content, quiet, label),
111        }
112    }
113}
114
115/// Decide where a particular hook should live.
116fn pick_target(home: &Path, slot: &Slot, style: Style) -> InstallTarget {
117    let inline = InstallTarget::Marked {
118        path: home.join(slot.rc_file),
119        start: slot.marker_start,
120        end: slot.marker_end,
121    };
122    match style {
123        Style::Inline => inline,
124        // DropIn and Auto both prefer dropin when available; only difference
125        // is whether we fall back silently (Auto) or could be made to warn
126        // (DropIn). Today they behave identically; the distinction lets
127        // callers express intent in the CLI surface later.
128        Style::DropIn | Style::Auto => match dropin::detect(home, slot.rc_file, slot.dropin_dir) {
129            Some(dir) => InstallTarget::DropIn {
130                dir,
131                filename: slot.dropin_file,
132            },
133            None => inline,
134        },
135    }
136}
137
138/// Pre-formatted timestamp suffix for migration backups.
139///
140/// Created **once per install run** and threaded through every per-slot
141/// install function, so all backups produced by a single
142/// `install_all_with_style` invocation share the same suffix. This
143/// rules out the "two near-simultaneous `Utc::now()` calls drifted by
144/// 1 ms across a second boundary" bug class, and makes the backups
145/// produced by one logical migration trivially groupable for the user
146/// (e.g. `ls ~ | grep lean-ctx-20260511T203845Z`).
147///
148/// Tests construct one via `BackupStamp::at(...)` to get deterministic
149/// filenames without touching the system clock.
150struct BackupStamp(String);
151
152impl BackupStamp {
153    /// Capture the current UTC time. Call this **once** at the top of
154    /// an install run.
155    fn now() -> Self {
156        Self::at(chrono::Utc::now())
157    }
158
159    /// Inject a specific moment in time. Used by tests; can also be
160    /// used in future to align migration backups with a user-supplied
161    /// release marker.
162    fn at(stamp: chrono::DateTime<chrono::Utc>) -> Self {
163        Self(stamp.format("%Y%m%dT%H%M%SZ").to_string())
164    }
165
166    /// Compose the full backup path for a given original file.
167    fn backup_path_for(&self, path: &Path) -> Option<PathBuf> {
168        let file_name = path.file_name().and_then(|n| n.to_str())?;
169        Some(path.with_file_name(format!("{file_name}.lean-ctx-{}.bak", self.0)))
170    }
171}
172
173/// Save a *timestamped* sibling backup of `path` before a destructive
174/// migration step. Filename pattern: `<basename>.lean-ctx-<UTC>.bak`,
175/// e.g. `.zshenv.lean-ctx-20260511T203845Z.bak`.
176///
177/// The block content owned by lean-ctx is normally treated as ours to
178/// rewrite — `marked_block::upsert` already strips and replaces it on
179/// every reinstall. That convention is acceptable for *idempotent
180/// reinstalls* (the canonical content is always the same) but loses
181/// information during a *style migration* if the user has hand-edited
182/// anywhere in the file, including inside our fenced region.
183///
184/// Deliberate divergence from the elsewhere-in-the-codebase convention
185/// (`cli::shell_init::backup_shell_config`, `config_io.rs`), which
186/// writes a single `<file>.lean-ctx.bak` and clobbers it on every
187/// invocation. That single-generation scheme is fine for "I backed
188/// this up moments ago before this exact reinstall" use cases, but
189/// risky for migration backups: a second migration event would
190/// silently overwrite the first, destroying potentially-unrecoverable
191/// user state. Timestamped names are append-only and let us migrate
192/// repeatedly (e.g. across multiple `lean-ctx update` runs over
193/// months) without ever losing a snapshot.
194fn save_migration_backup(path: &Path, quiet: bool, stamp: &BackupStamp) {
195    if !path.exists() {
196        return;
197    }
198    let Some(bak) = stamp.backup_path_for(path) else {
199        return;
200    };
201    match std::fs::copy(path, &bak) {
202        Ok(_) => {
203            if !quiet {
204                eprintln!("  Backup: {} -> {}", path.display(), bak.display());
205            }
206        }
207        Err(e) => {
208            tracing::warn!("Failed to back up {}: {e}", path.display());
209        }
210    }
211}
212
213/// When we install one style, sweep away any prior install of the *other*
214/// style so users transparently migrate (and so re-running setup never
215/// leaves the hook in two places).
216///
217/// Whenever a migration would clobber pre-existing user content (a
218/// fenced block in the rc file, or a hand-tweaked drop-in file), the
219/// affected file is copied to `<filename>.lean-ctx-<stamp>.bak` first
220/// (see `save_migration_backup`). The backup is only created when there
221/// is something to migrate AWAY from, so clean installs and idempotent
222/// reinstalls don't generate noise. `stamp` is taken by reference so
223/// all migrations within one `install_all` invocation share the same
224/// suffix.
225fn strip_other_style(
226    home: &Path,
227    slot: &Slot,
228    target: &InstallTarget,
229    quiet: bool,
230    label: &str,
231    stamp: &BackupStamp,
232) {
233    match target {
234        InstallTarget::Marked { .. } => {
235            // Installing inline: remove any drop-in file we previously wrote.
236            let dropin_dir = home.join(slot.dropin_dir);
237            let dropin_path = dropin_dir.join(slot.dropin_file);
238            if dropin_path.exists() {
239                // Hand-edits to the drop-in file would otherwise be lost.
240                // The backup lands next to the original; the `.bak`
241                // suffix keeps it out of any `*.zsh` source glob.
242                save_migration_backup(&dropin_path, quiet, stamp);
243                dropin::remove(&dropin_dir, slot.dropin_file, quiet, label);
244            }
245        }
246        InstallTarget::DropIn { .. } => {
247            // Installing drop-in: remove any prior inline fenced block.
248            // Back up the whole rc file first so anything between the
249            // markers (and any unrelated user edits to the same file)
250            // is recoverable from `<rc>.lean-ctx-<stamp>.bak`.
251            let rc_path = home.join(slot.rc_file);
252            if let Ok(existing) = std::fs::read_to_string(&rc_path) {
253                if existing.contains(slot.marker_start) {
254                    save_migration_backup(&rc_path, quiet, stamp);
255                }
256            }
257            marked_block::remove_from_file(
258                &rc_path,
259                slot.marker_start,
260                slot.marker_end,
261                quiet,
262                label,
263            );
264        }
265    }
266}
267
268/// Public entrypoint: install with auto-detected style. Preserves the
269/// previous signature so existing callers (setup.rs, cli/shell_init.rs)
270/// don't need to change.
271pub fn install_all(quiet: bool) {
272    install_all_with_style(quiet, Style::Auto);
273}
274
275/// Explicit style entrypoint for callers that want to honour a `--style=`
276/// CLI flag.
277///
278/// Captures a single `BackupStamp` here so every migration backup
279/// produced by this invocation shares one suffix, even if the wall
280/// clock ticks over while we're walking the slots.
281pub fn install_all_with_style(quiet: bool, style: Style) {
282    let Some(home) = dirs::home_dir() else {
283        tracing::error!("Cannot resolve home directory");
284        return;
285    };
286
287    let stamp = BackupStamp::now();
288    install_zshenv(&home, quiet, style, &stamp);
289    install_bashenv(&home, quiet, style, &stamp);
290    install_aliases(&home, quiet, style, &stamp);
291}
292
293pub fn uninstall_all(quiet: bool) {
294    let Some(home) = dirs::home_dir() else { return };
295
296    // Try both styles unconditionally for each slot. marked_block::remove
297    // and dropin::remove are both no-ops when their target is absent.
298    let slots: &[(Slot, &str)] = &[
299        (SLOT_ZSHENV, "shell hook for ~/.zshenv"),
300        (SLOT_BASHENV, "shell hook for ~/.bashenv"),
301        (SLOT_ZSHRC, "agent aliases for ~/.zshrc"),
302        (SLOT_BASHRC, "agent aliases for ~/.bashrc"),
303    ];
304
305    for (slot, label) in slots {
306        marked_block::remove_from_file(
307            &home.join(slot.rc_file),
308            slot.marker_start,
309            slot.marker_end,
310            quiet,
311            label,
312        );
313        let dir_path = home.join(slot.dropin_dir);
314        if dir_path.exists() {
315            dropin::remove(&dir_path, slot.dropin_file, quiet, label);
316        }
317    }
318}
319
320fn install_zshenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
321    let env_check = build_env_check();
322    let hook = format!(
323        r#"{MARKER_START}
324if [[ -z "$LEAN_CTX_ACTIVE" && -n "$ZSH_EXECUTION_STRING" ]] && command -v lean-ctx &>/dev/null; then
325  if {env_check}; then
326    export LEAN_CTX_ACTIVE=1
327    exec lean-ctx -c "$ZSH_EXECUTION_STRING"
328  fi
329fi
330{MARKER_END}"#
331    );
332
333    let label = "shell hook in ~/.zshenv";
334    let target = pick_target(home, &SLOT_ZSHENV, style);
335    strip_other_style(home, &SLOT_ZSHENV, &target, quiet, label, stamp);
336    target.upsert(&hook, quiet, label);
337}
338
339fn install_bashenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
340    let env_check = build_env_check();
341    let hook = format!(
342        r#"{MARKER_START}
343if [[ -z "$LEAN_CTX_ACTIVE" && -n "$BASH_EXECUTION_STRING" ]] && command -v lean-ctx &>/dev/null; then
344  if {env_check}; then
345    export LEAN_CTX_ACTIVE=1
346    exec lean-ctx -c "$BASH_EXECUTION_STRING"
347  fi
348fi
349{MARKER_END}"#
350    );
351
352    let label = "shell hook in ~/.bashenv";
353    let target = pick_target(home, &SLOT_BASHENV, style);
354    strip_other_style(home, &SLOT_BASHENV, &target, quiet, label, stamp);
355    target.upsert(&hook, quiet, label);
356}
357
358fn install_aliases(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
359    let mut lines = Vec::new();
360    lines.push(ALIAS_START.to_string());
361    for (alias_name, bin_name) in AGENT_ALIASES {
362        lines.push(format!(
363            "alias {alias_name}='LEAN_CTX_AGENT=1 BASH_ENV=\"$HOME/.bashenv\" {bin_name}'"
364        ));
365    }
366    lines.push(ALIAS_END.to_string());
367    let block = lines.join("\n");
368
369    for slot in &[SLOT_ZSHRC, SLOT_BASHRC] {
370        // Only act on rc files the user actually has. (Drop-in mode keys off
371        // the parent rc anyway — see `dropin::detect`.)
372        if !home.join(slot.rc_file).exists() {
373            continue;
374        }
375        let label = format!("agent aliases in ~/{}", slot.rc_file);
376        let target = pick_target(home, slot, style);
377        strip_other_style(home, slot, &target, quiet, &label, stamp);
378        target.upsert(&block, quiet, &label);
379    }
380}
381
382fn build_env_check() -> String {
383    let checks: Vec<String> = KNOWN_AGENT_ENV_VARS
384        .iter()
385        .map(|v| format!("-n \"${v}\""))
386        .collect();
387    format!("[[ {} ]]", checks.join(" || "))
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    /// Fixed deterministic stamp for tests that don't care about
395    /// distinguishing migration generations. Tests that *do* care
396    /// (e.g. the no-clobber regression) construct their own.
397    fn test_stamp() -> BackupStamp {
398        BackupStamp::at(
399            chrono::DateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
400                .unwrap()
401                .with_timezone(&chrono::Utc),
402        )
403    }
404
405    #[test]
406    fn env_check_format() {
407        let check = build_env_check();
408        assert!(check.contains("LEAN_CTX_AGENT"));
409        assert!(check.contains("CLAUDECODE"));
410        assert!(check.contains("||"));
411    }
412
413    #[test]
414    fn pick_target_inline_when_forced() {
415        let tmp = tempfile::tempdir().unwrap();
416        // Even with a .d/ loop, Style::Inline must force the marked target.
417        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
418        std::fs::write(
419            tmp.path().join(".zshenv"),
420            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
421        )
422        .unwrap();
423        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Inline);
424        assert!(matches!(t, InstallTarget::Marked { .. }));
425    }
426
427    #[test]
428    fn pick_target_dropin_when_detected_under_auto() {
429        let tmp = tempfile::tempdir().unwrap();
430        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
431        std::fs::write(
432            tmp.path().join(".zshenv"),
433            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
434        )
435        .unwrap();
436        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
437        assert!(matches!(t, InstallTarget::DropIn { .. }));
438    }
439
440    #[test]
441    fn pick_target_inline_under_auto_when_no_dropin() {
442        let tmp = tempfile::tempdir().unwrap();
443        std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
444        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
445        assert!(matches!(t, InstallTarget::Marked { .. }));
446    }
447
448    #[test]
449    fn pick_target_dropin_falls_back_to_inline_when_no_directory() {
450        // User asked for DropIn but the layout isn't set up. Don't error —
451        // fall back to inline so the install still works.
452        let tmp = tempfile::tempdir().unwrap();
453        std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
454        let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::DropIn);
455        assert!(matches!(t, InstallTarget::Marked { .. }));
456    }
457
458    #[test]
459    fn install_zshenv_writes_inline_block() {
460        let tmp = tempfile::tempdir().unwrap();
461        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
462        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
463        assert!(body.contains(MARKER_START));
464        assert!(body.contains(MARKER_END));
465        assert!(body.contains("ZSH_EXECUTION_STRING"));
466    }
467
468    #[test]
469    fn install_zshenv_writes_dropin_when_loop_present() {
470        let tmp = tempfile::tempdir().unwrap();
471        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
472        std::fs::write(
473            tmp.path().join(".zshenv"),
474            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
475        )
476        .unwrap();
477        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
478
479        let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
480        assert!(dropin_file.exists(), "expected drop-in file");
481        let dropin_body = std::fs::read_to_string(&dropin_file).unwrap();
482        assert!(dropin_body.contains("ZSH_EXECUTION_STRING"));
483
484        let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
485        assert!(
486            !zshenv_body.contains(MARKER_START),
487            "drop-in install must not also leave the inline block"
488        );
489    }
490
491    /// List sibling files of `path` whose name matches
492    /// `<basename>.lean-ctx-<timestamp>.bak`.
493    fn find_migration_backups(path: &Path) -> Vec<PathBuf> {
494        let Some(parent) = path.parent() else {
495            return Vec::new();
496        };
497        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
498            return Vec::new();
499        };
500        let prefix = format!("{name}.lean-ctx-");
501        let mut out: Vec<PathBuf> = std::fs::read_dir(parent)
502            .into_iter()
503            .flatten()
504            .flatten()
505            .map(|e| e.path())
506            .filter(|p| {
507                p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
508                    n.starts_with(&prefix)
509                        && std::path::Path::new(n)
510                            .extension()
511                            .is_some_and(|ext| ext.eq_ignore_ascii_case("bak"))
512                })
513            })
514            .collect();
515        out.sort();
516        out
517    }
518
519    #[test]
520    fn migration_inline_to_dropin_preserves_hand_edits_via_backup() {
521        let tmp = tempfile::tempdir().unwrap();
522        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
523        // Existing install with a hand-edit *inside* our fenced region —
524        // the bit a maintainer might worry about losing silently.
525        let edited_zshenv = format!(
526            "export PATH=/usr/bin\n\
527             \n\
528             {MARKER_START}\n\
529             # USER CUSTOM: bump zsh history size for this workstation\n\
530             export HISTSIZE=99999\n\
531             # original lean-ctx hook content lived here\n\
532             {MARKER_END}\n\
533             \n\
534             for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
535        );
536        std::fs::write(tmp.path().join(".zshenv"), &edited_zshenv).unwrap();
537
538        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
539
540        // Backup must exist and contain the user's exact pre-migration file.
541        let baks = find_migration_backups(&tmp.path().join(".zshenv"));
542        assert_eq!(baks.len(), 1, "expected one timestamped backup");
543        let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
544        assert_eq!(bak_body, edited_zshenv);
545        assert!(bak_body.contains("USER CUSTOM"));
546        assert!(bak_body.contains("HISTSIZE=99999"));
547    }
548
549    #[test]
550    fn migration_dropin_to_inline_preserves_hand_edits_via_backup() {
551        let tmp = tempfile::tempdir().unwrap();
552        let dropin_dir = tmp.path().join(".zshenv.d");
553        std::fs::create_dir_all(&dropin_dir).unwrap();
554        // Pre-stage a drop-in file with user customisation.
555        let edited_dropin = "# USER CUSTOM addition to lean-ctx drop-in\nexport FAVOURITE_EDITOR=helix\n# canonical lean-ctx content would follow\n";
556        std::fs::write(dropin_dir.join(DROPIN_ZSH), edited_dropin).unwrap();
557        // No source loop -> Style::Auto resolves to inline (so we migrate
558        // *away* from the drop-in).
559        std::fs::write(tmp.path().join(".zshenv"), "# plain zshenv\n").unwrap();
560
561        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
562
563        let baks = find_migration_backups(&dropin_dir.join(DROPIN_ZSH));
564        assert_eq!(baks.len(), 1, "expected one timestamped backup");
565        let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
566        assert_eq!(bak_body, edited_dropin);
567        assert!(bak_body.contains("USER CUSTOM"));
568        // The original drop-in is gone, replaced by an inline block in .zshenv.
569        assert!(!dropin_dir.join(DROPIN_ZSH).exists());
570        let zshenv = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
571        assert!(zshenv.contains(MARKER_START));
572    }
573
574    #[test]
575    fn migration_skips_backup_when_no_prior_block_exists() {
576        // Clean install (no prior lean-ctx artifacts) should not litter
577        // the home dir with empty `.lean-ctx-<ts>.bak` files.
578        let tmp = tempfile::tempdir().unwrap();
579        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
580        std::fs::write(
581            tmp.path().join(".zshenv"),
582            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
583        )
584        .unwrap();
585
586        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
587
588        assert!(
589            find_migration_backups(&tmp.path().join(".zshenv")).is_empty(),
590            "clean install should not create a .bak file"
591        );
592    }
593
594    #[test]
595    fn idempotent_dropin_reinstall_does_not_create_backup() {
596        // Once installed in drop-in mode, a second `install` (e.g. via
597        // `lean-ctx update` re-wiring) should not start producing backups
598        // every run. The strip-other-style path only fires when there IS
599        // an inline block to remove.
600        let tmp = tempfile::tempdir().unwrap();
601        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
602        std::fs::write(
603            tmp.path().join(".zshenv"),
604            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
605        )
606        .unwrap();
607
608        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
609        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
610
611        assert!(find_migration_backups(&tmp.path().join(".zshenv")).is_empty());
612    }
613
614    #[test]
615    fn backup_filename_handles_dotfile_correctly() {
616        // `.zshenv` has no extension; Path::with_extension would replace
617        // ".zshenv" wholesale. Using with_file_name produces the right
618        // sibling path. Timestamp is appended between basename and `.bak`.
619        let tmp = tempfile::tempdir().unwrap();
620        std::fs::write(tmp.path().join(".zshenv"), "content\n").unwrap();
621        save_migration_backup(&tmp.path().join(".zshenv"), true, &test_stamp());
622        let baks = find_migration_backups(&tmp.path().join(".zshenv"));
623        assert_eq!(baks.len(), 1);
624        // The full filename must start with the original basename so it
625        // sits as a sibling, not at the parent root.
626        let name = baks[0].file_name().unwrap().to_str().unwrap();
627        assert!(name.starts_with(".zshenv.lean-ctx-"), "got: {name}");
628        assert!(std::path::Path::new(name)
629            .extension()
630            .is_some_and(|ext| ext.eq_ignore_ascii_case("bak")));
631        // Sanity-check the timestamp is in the YYYYMMDDTHHMMSSZ slot.
632        let stamp = name
633            .trim_start_matches(".zshenv.lean-ctx-")
634            .trim_end_matches(".bak");
635        assert_eq!(stamp.len(), 16, "stamp should be YYYYMMDDTHHMMSSZ: {stamp}");
636        assert!(stamp.contains('T'));
637        assert!(stamp.ends_with('Z'));
638    }
639
640    #[test]
641    fn repeated_migrations_never_clobber_prior_backups() {
642        // Regression test for the convention upgrade: two migration
643        // events on the same slot must produce two distinct backups,
644        // not silently overwrite each other. We pin two different
645        // stamps directly instead of sleeping past a second boundary.
646        let stamp_first = BackupStamp::at(
647            chrono::DateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
648                .unwrap()
649                .with_timezone(&chrono::Utc),
650        );
651        let stamp_later = BackupStamp::at(
652            chrono::DateTime::parse_from_rfc3339("2026-05-12T09:00:00Z")
653                .unwrap()
654                .with_timezone(&chrono::Utc),
655        );
656        let tmp = tempfile::tempdir().unwrap();
657        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
658
659        let with_block_v1 = format!(
660            "{MARKER_START}\n# first-era custom content\n{MARKER_END}\n\nfor f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
661        );
662        std::fs::write(tmp.path().join(".zshenv"), &with_block_v1).unwrap();
663        install_zshenv(tmp.path(), true, Style::Auto, &stamp_first);
664        let baks_after_first = find_migration_backups(&tmp.path().join(".zshenv"));
665        assert_eq!(baks_after_first.len(), 1);
666
667        // User hand-puts a NEW inline block back (perhaps via a manual
668        // edit or a partial reinstall in a tool we don't know about).
669        let with_block_v2 = format!(
670            "{}{MARKER_START}\n# second-era custom content\n{MARKER_END}\n",
671            std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap(),
672        );
673        std::fs::write(tmp.path().join(".zshenv"), &with_block_v2).unwrap();
674        install_zshenv(tmp.path(), true, Style::Auto, &stamp_later);
675        let baks_after_second = find_migration_backups(&tmp.path().join(".zshenv"));
676
677        assert_eq!(
678            baks_after_second.len(),
679            2,
680            "second migration should leave a second backup, not overwrite"
681        );
682        // First backup unchanged from after the first migration.
683        assert_eq!(baks_after_second[0], baks_after_first[0]);
684        let first_body = std::fs::read_to_string(&baks_after_second[0]).unwrap();
685        let second_body = std::fs::read_to_string(&baks_after_second[1]).unwrap();
686        assert!(first_body.contains("first-era custom"));
687        assert!(second_body.contains("second-era custom"));
688    }
689
690    #[test]
691    fn install_migrates_inline_to_dropin() {
692        let tmp = tempfile::tempdir().unwrap();
693        // Simulate an existing install: .zshenv with the old fenced block.
694        std::fs::write(
695            tmp.path().join(".zshenv"),
696            format!(
697                "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",
698            ),
699        )
700        .unwrap();
701        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
702
703        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
704
705        let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
706        assert!(
707            !zshenv_body.contains(MARKER_START),
708            "old inline block should be stripped after migration"
709        );
710        assert!(
711            zshenv_body.contains(".zshenv.d"),
712            "source loop must be preserved"
713        );
714        let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
715        assert!(dropin_file.exists(), "new drop-in file should be present");
716    }
717
718    #[test]
719    fn install_migrates_dropin_to_inline() {
720        let tmp = tempfile::tempdir().unwrap();
721        // No source loop → Style::Inline forces inline. Pre-stage a
722        // leftover drop-in file as if the user previously had the layout.
723        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
724        std::fs::write(
725            tmp.path().join(".zshenv.d").join(DROPIN_ZSH),
726            "# stale lean-ctx drop-in\n",
727        )
728        .unwrap();
729        std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
730
731        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
732
733        assert!(
734            !tmp.path().join(".zshenv.d").join(DROPIN_ZSH).exists(),
735            "drop-in file should be removed when installing inline"
736        );
737        let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
738        assert!(body.contains(MARKER_START));
739    }
740
741    #[test]
742    fn install_is_idempotent_in_dropin_mode() {
743        let tmp = tempfile::tempdir().unwrap();
744        std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
745        std::fs::write(
746            tmp.path().join(".zshenv"),
747            "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
748        )
749        .unwrap();
750
751        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
752        let after_first = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
753
754        install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
755        let after_second = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
756
757        assert_eq!(after_first, after_second);
758    }
759
760    #[test]
761    fn install_is_idempotent_in_inline_mode() {
762        let tmp = tempfile::tempdir().unwrap();
763        std::fs::write(tmp.path().join(".zshenv"), "# top\n").unwrap();
764
765        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
766        let after_first = std::fs::read(tmp.path().join(".zshenv")).unwrap();
767
768        install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
769        let after_second = std::fs::read(tmp.path().join(".zshenv")).unwrap();
770
771        assert_eq!(after_first, after_second);
772    }
773
774    #[test]
775    fn install_aliases_skips_when_rc_missing() {
776        let tmp = tempfile::tempdir().unwrap();
777        // No .zshrc, no .bashrc — nothing should be created.
778        install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
779        assert!(!tmp.path().join(".zshrc").exists());
780        assert!(!tmp.path().join(".bashrc").exists());
781    }
782
783    #[test]
784    fn install_aliases_writes_dropin_when_zshrc_d_configured() {
785        let tmp = tempfile::tempdir().unwrap();
786        std::fs::create_dir_all(tmp.path().join(".zshrc.d")).unwrap();
787        std::fs::write(
788            tmp.path().join(".zshrc"),
789            "for f in $HOME/.zshrc.d/*.zsh; do source $f; done\n",
790        )
791        .unwrap();
792
793        install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
794
795        let dropin_file = tmp.path().join(".zshrc.d").join(DROPIN_ZSH);
796        assert!(dropin_file.exists());
797        let body = std::fs::read_to_string(&dropin_file).unwrap();
798        assert!(body.contains("LEAN_CTX_AGENT=1"));
799    }
800}