1use std::path::{Path, PathBuf};
2use std::sync::OnceLock;
3
4use crate::{dropin, marked_block};
5
6static INSTALLED_HOOK_REFRESH: OnceLock<fn()> = OnceLock::new();
11
12pub fn register_installed_hook_refresh(refresh: fn()) {
14 let _ = INSTALLED_HOOK_REFRESH.set(refresh);
15}
16
17pub 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
29const DROPIN_ZSH: &str = "00-lean-ctx.zsh";
33const DROPIN_SH: &str = "00-lean-ctx.sh";
34
35pub const KNOWN_AGENT_ENV_VARS: &[&str] = &[
38 "LEAN_CTX_AGENT",
39 "CLAUDECODE",
40 "CODEBUDDY",
41 "CODEX_CLI_SESSION",
42 "GEMINI_SESSION",
43];
44
45pub 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
58pub 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
66pub fn agent_env_marker(is_set: impl Fn(&str) -> bool) -> Option<&'static str> {
68 agent_env_markers().find(|name| is_set(name))
69}
70
71pub 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
83fn 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
99pub fn shell_source_command() -> Option<&'static str> {
104 source_command_for_shell(&std::env::var("SHELL").unwrap_or_default())
105}
106
107fn 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
120pub fn shell_rc_file() -> &'static str {
124 rc_file_for_shell(&std::env::var("SHELL").unwrap_or_default())
125}
126
127pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143pub enum Style {
144 Inline,
146 DropIn,
149 #[default]
151 Auto,
152}
153
154#[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
198enum 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
222fn 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 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
245struct BackupStamp(String);
258
259impl BackupStamp {
260 fn now() -> Self {
263 Self::at(lean_ctx_time::UtcDateTime::now())
264 }
265
266 fn at(stamp: lean_ctx_time::UtcDateTime) -> Self {
270 Self(stamp.format("%Y%m%dT%H%M%SZ").to_string())
271 }
272
273 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
280fn 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
320fn 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 let dropin_dir = home.join(slot.dropin_dir);
344 let dropin_path = dropin_dir.join(slot.dropin_file);
345 if dropin_path.exists() {
346 save_migration_backup(&dropin_path, quiet, stamp);
350 dropin::remove(&dropin_dir, slot.dropin_file, quiet, label);
351 }
352 }
353 InstallTarget::DropIn { .. } => {
354 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
375pub fn install_all(quiet: bool) {
379 install_all_with_style(quiet, Style::Auto);
380}
381
382pub 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#[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 false
466}
467
468pub fn uninstall_all(quiet: bool) {
469 let Some(home) = dirs::home_dir() else { return };
470
471 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
495const REDIRECT_SKIP_MARKERS: &[&str] = &[
505 "__CURSOR_SANDBOX", "dump_zsh_state", "lean-ctx hook ", ];
509
510fn 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 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
597fn 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 #[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 #[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 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 crate::test_env::set_var("LEAN_CTX_SHELL_HOOK_FORCE", "all");
1310 assert!(shell_available("zsh"));
1311 assert!(shell_available("bash"));
1312
1313 crate::test_env::set_var("LEAN_CTX_SHELL_HOOK_FORCE", "zsh");
1315 assert!(shell_available("zsh"));
1316 crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1320 }
1321}