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
10const 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 "CODEBUDDY",
20 "CODEX_CLI_SESSION",
21 "GEMINI_SESSION",
22];
23
24const AGENT_ALIASES: &[(&str, &str)] = &[
25 ("claude", "claude"),
26 ("codebuddy", "codebuddy"),
27 ("codex", "codex"),
28 ("gemini", "gemini"),
29];
30
31fn source_command_for_shell(shell: &str) -> Option<&'static str> {
36 if shell.contains("zsh") {
37 Some("source ~/.zshrc")
38 } else if shell.contains("fish") {
39 Some("source ~/.config/fish/config.fish")
40 } else if shell.contains("bash") {
41 Some("source ~/.bashrc")
42 } else {
43 None
44 }
45}
46
47pub fn shell_source_command() -> Option<&'static str> {
52 source_command_for_shell(&std::env::var("SHELL").unwrap_or_default())
53}
54
55fn rc_file_for_shell(shell: &str) -> &'static str {
57 if shell.contains("zsh") {
58 "~/.zshrc"
59 } else if shell.contains("fish") {
60 "~/.config/fish/config.fish"
61 } else if shell.contains("bash") {
62 "~/.bashrc"
63 } else {
64 "your shell config"
65 }
66}
67
68pub fn shell_rc_file() -> &'static str {
72 rc_file_for_shell(&std::env::var("SHELL").unwrap_or_default())
73}
74
75pub fn reload_aliases_hint() -> String {
78 match shell_source_command() {
79 Some(cmd) => format!("Run '{cmd}' (or restart terminal) for updated shell aliases."),
80 None => "Restart your terminal to load updated shell aliases.".to_string(),
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
91pub enum Style {
92 Inline,
94 DropIn,
97 #[default]
99 Auto,
100}
101
102#[derive(Debug, Clone, Copy)]
106struct Slot {
107 rc_file: &'static str,
108 dropin_dir: &'static str,
109 dropin_file: &'static str,
110 marker_start: &'static str,
111 marker_end: &'static str,
112}
113
114const SLOT_ZSHENV: Slot = Slot {
115 rc_file: ".zshenv",
116 dropin_dir: ".zshenv.d",
117 dropin_file: DROPIN_ZSH,
118 marker_start: MARKER_START,
119 marker_end: MARKER_END,
120};
121
122const SLOT_BASHENV: Slot = Slot {
123 rc_file: ".bashenv",
124 dropin_dir: ".bashenv.d",
125 dropin_file: DROPIN_SH,
126 marker_start: MARKER_START,
127 marker_end: MARKER_END,
128};
129
130const SLOT_ZSHRC: Slot = Slot {
131 rc_file: ".zshrc",
132 dropin_dir: ".zshrc.d",
133 dropin_file: DROPIN_ZSH,
134 marker_start: ALIAS_START,
135 marker_end: ALIAS_END,
136};
137
138const SLOT_BASHRC: Slot = Slot {
139 rc_file: ".bashrc",
140 dropin_dir: ".bashrc.d",
141 dropin_file: DROPIN_SH,
142 marker_start: ALIAS_START,
143 marker_end: ALIAS_END,
144};
145
146enum InstallTarget {
148 Marked {
149 path: PathBuf,
150 start: &'static str,
151 end: &'static str,
152 },
153 DropIn {
154 dir: PathBuf,
155 filename: &'static str,
156 },
157}
158
159impl InstallTarget {
160 fn upsert(&self, content: &str, quiet: bool, label: &str) {
161 match self {
162 Self::Marked { path, start, end } => {
163 marked_block::upsert(path, start, end, content, quiet, label);
164 }
165 Self::DropIn { dir, filename } => dropin::write(dir, filename, content, quiet, label),
166 }
167 }
168}
169
170fn pick_target(home: &Path, slot: &Slot, style: Style) -> InstallTarget {
172 let inline = InstallTarget::Marked {
173 path: home.join(slot.rc_file),
174 start: slot.marker_start,
175 end: slot.marker_end,
176 };
177 match style {
178 Style::Inline => inline,
179 Style::DropIn | Style::Auto => match dropin::detect(home, slot.rc_file, slot.dropin_dir) {
184 Some(dir) => InstallTarget::DropIn {
185 dir,
186 filename: slot.dropin_file,
187 },
188 None => inline,
189 },
190 }
191}
192
193struct BackupStamp(String);
206
207impl BackupStamp {
208 fn now() -> Self {
211 Self::at(chrono::Utc::now())
212 }
213
214 fn at(stamp: chrono::DateTime<chrono::Utc>) -> Self {
218 Self(stamp.format("%Y%m%dT%H%M%SZ").to_string())
219 }
220
221 fn backup_path_for(&self, path: &Path) -> Option<PathBuf> {
223 let file_name = path.file_name().and_then(|n| n.to_str())?;
224 Some(path.with_file_name(format!("{file_name}.lean-ctx-{}.bak", self.0)))
225 }
226}
227
228fn save_migration_backup(path: &Path, quiet: bool, stamp: &BackupStamp) {
250 if !path.exists() {
251 return;
252 }
253 let Some(bak) = stamp.backup_path_for(path) else {
254 return;
255 };
256 match std::fs::copy(path, &bak) {
257 Ok(_) => {
258 if !quiet {
259 eprintln!(" Backup: {} -> {}", path.display(), bak.display());
260 }
261 }
262 Err(e) => {
263 tracing::warn!("Failed to back up {}: {e}", path.display());
264 }
265 }
266}
267
268fn strip_other_style(
281 home: &Path,
282 slot: &Slot,
283 target: &InstallTarget,
284 quiet: bool,
285 label: &str,
286 stamp: &BackupStamp,
287) {
288 match target {
289 InstallTarget::Marked { .. } => {
290 let dropin_dir = home.join(slot.dropin_dir);
292 let dropin_path = dropin_dir.join(slot.dropin_file);
293 if dropin_path.exists() {
294 save_migration_backup(&dropin_path, quiet, stamp);
298 dropin::remove(&dropin_dir, slot.dropin_file, quiet, label);
299 }
300 }
301 InstallTarget::DropIn { .. } => {
302 let rc_path = home.join(slot.rc_file);
307 if let Ok(existing) = std::fs::read_to_string(&rc_path)
308 && existing.contains(slot.marker_start)
309 {
310 save_migration_backup(&rc_path, quiet, stamp);
311 }
312 marked_block::remove_from_file(
313 &rc_path,
314 slot.marker_start,
315 slot.marker_end,
316 quiet,
317 label,
318 );
319 }
320 }
321}
322
323pub fn install_all(quiet: bool) {
327 install_all_with_style(quiet, Style::Auto);
328}
329
330pub fn install_all_with_style(quiet: bool, style: Style) {
337 let cfg = crate::core::config::Config::load();
338 if cfg.shell_hook_disabled_effective() {
339 if !quiet {
340 eprintln!(
341 "lean-ctx: shell hook disabled (shell_hook_disabled=true or LEAN_CTX_NO_HOOK). Skipping hook installation."
342 );
343 }
344 return;
345 }
346
347 let Some(home) = dirs::home_dir() else {
348 tracing::error!("Cannot resolve home directory");
349 return;
350 };
351
352 let stamp = BackupStamp::now();
353 if shell_available("zsh") {
354 install_zshenv(&home, quiet, style, &stamp);
355 }
356 if shell_available("bash") {
357 install_bashenv(&home, quiet, style, &stamp);
358 }
359 let cfg = crate::core::config::Config::load();
360 if cfg.skip_agent_aliases {
361 remove_agent_aliases(&home, quiet);
362 } else {
363 install_aliases(&home, quiet, style, &stamp);
364 }
365}
366
367#[cfg(unix)]
375fn shell_available(shell: &str) -> bool {
376 if let Ok(forced) = std::env::var("LEAN_CTX_SHELL_HOOK_FORCE") {
377 let forced = forced.trim();
378 if forced == "1"
379 || forced.eq_ignore_ascii_case("true")
380 || forced.eq_ignore_ascii_case("all")
381 {
382 return true;
383 }
384 if forced
385 .split(',')
386 .any(|s| s.trim().eq_ignore_ascii_case(shell))
387 {
388 return true;
389 }
390 }
391
392 let candidates: &[&str] = match shell {
393 "zsh" => &[
394 "/bin/zsh",
395 "/usr/bin/zsh",
396 "/usr/local/bin/zsh",
397 "/opt/homebrew/bin/zsh",
398 ],
399 "bash" => &[
400 "/bin/bash",
401 "/usr/bin/bash",
402 "/usr/local/bin/bash",
403 "/opt/homebrew/bin/bash",
404 ],
405 _ => return false,
406 };
407 candidates.iter().any(|p| Path::new(p).exists())
408}
409
410#[cfg(not(unix))]
411fn shell_available(_shell: &str) -> bool {
412 false
414}
415
416pub fn uninstall_all(quiet: bool) {
417 let Some(home) = dirs::home_dir() else { return };
418
419 let slots: &[(Slot, &str)] = &[
422 (SLOT_ZSHENV, "shell hook for ~/.zshenv"),
423 (SLOT_BASHENV, "shell hook for ~/.bashenv"),
424 (SLOT_ZSHRC, "agent aliases for ~/.zshrc"),
425 (SLOT_BASHRC, "agent aliases for ~/.bashrc"),
426 ];
427
428 for (slot, label) in slots {
429 marked_block::remove_from_file(
430 &home.join(slot.rc_file),
431 slot.marker_start,
432 slot.marker_end,
433 quiet,
434 label,
435 );
436 let dir_path = home.join(slot.dropin_dir);
437 if dir_path.exists() {
438 dropin::remove(&dir_path, slot.dropin_file, quiet, label);
439 }
440 }
441}
442
443const REDIRECT_SKIP_MARKERS: &[&str] = &[
453 "__CURSOR_SANDBOX", "dump_zsh_state", "lean-ctx hook ", ];
457
458fn redirect_block(exec_var: &str, env_check: &str) -> String {
465 let mut lines = vec![format!(
466 "if [[ -z \"$LEAN_CTX_ACTIVE\" && -z \"$LEAN_CTX_DISABLED\" && -z \"$LEAN_CTX_NO_HOOK\" && -n \"${exec_var}\" ]] \\"
467 )];
468 for marker in REDIRECT_SKIP_MARKERS {
469 lines.push(format!(" && [[ \"${exec_var}\" != *\"{marker}\"* ]] \\"));
470 }
471 lines.push(" && command -v lean-ctx &>/dev/null; then".to_string());
472 lines.push(format!(" if {env_check}; then"));
473 lines.push(" export LEAN_CTX_ACTIVE=1".to_string());
474 lines.push(format!(" exec lean-ctx -c \"${exec_var}\""));
475 lines.push(" fi".to_string());
476 lines.push("fi".to_string());
477 lines.join("\n")
478}
479
480fn install_zshenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
481 let redirect = redirect_block("ZSH_EXECUTION_STRING", &build_env_check());
482 let hook = format!(
483 r#"{MARKER_START}
484# Passthrough stubs: ensure the alias targets (lean_ctx_track/_compress,
485# legacy _lc/_lc_compress) exist in ALL zsh contexts
486# (non-interactive subshells, eval, agent harnesses) so aliases that
487# reference them degrade gracefully instead of "command not found".
488# The full shell-hook.zsh overrides these when loaded via .zshrc.
489_lc() {{ command "$@"; }}
490_lc_compress() {{ command "$@"; }}
491lean_ctx_track() {{ command "$@"; }}
492lean_ctx_compress() {{ command "$@"; }}
493{redirect}
494{MARKER_END}"#
495 );
496
497 let label = "shell hook in ~/.zshenv";
498 let target = pick_target(home, &SLOT_ZSHENV, style);
499 strip_other_style(home, &SLOT_ZSHENV, &target, quiet, label, stamp);
500 target.upsert(&hook, quiet, label);
501}
502
503fn install_bashenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
504 let redirect = redirect_block("BASH_EXECUTION_STRING", &build_env_check());
505 let hook = format!(
506 r#"{MARKER_START}
507_lc() {{ command "$@"; }}
508_lc_compress() {{ command "$@"; }}
509lean_ctx_track() {{ command "$@"; }}
510lean_ctx_compress() {{ command "$@"; }}
511{redirect}
512{MARKER_END}"#
513 );
514
515 let label = "shell hook in ~/.bashenv";
516 let target = pick_target(home, &SLOT_BASHENV, style);
517 strip_other_style(home, &SLOT_BASHENV, &target, quiet, label, stamp);
518 target.upsert(&hook, quiet, label);
519}
520
521fn install_aliases(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
522 let mut lines = Vec::new();
523 lines.push(ALIAS_START.to_string());
524 for (alias_name, bin_name) in AGENT_ALIASES {
525 lines.push(format!(
526 "alias {alias_name}='LEAN_CTX_AGENT=1 BASH_ENV=\"$HOME/.bashenv\" {bin_name}'"
527 ));
528 }
529 lines.push(ALIAS_END.to_string());
530 let block = lines.join("\n");
531
532 for slot in &[SLOT_ZSHRC, SLOT_BASHRC] {
533 if !home.join(slot.rc_file).exists() {
536 continue;
537 }
538 let label = format!("agent aliases in ~/{}", slot.rc_file);
539 let target = pick_target(home, slot, style);
540 strip_other_style(home, slot, &target, quiet, &label, stamp);
541 target.upsert(&block, quiet, &label);
542 }
543}
544
545fn remove_agent_aliases(home: &Path, quiet: bool) {
548 for slot in &[SLOT_ZSHRC, SLOT_BASHRC] {
549 let rc = home.join(slot.rc_file);
550 if !rc.exists() {
551 continue;
552 }
553 if let Ok(content) = std::fs::read_to_string(&rc)
554 && content.contains(ALIAS_START)
555 {
556 let filtered: Vec<&str> = content
557 .lines()
558 .scan(false, |inside, line| {
559 if line.trim() == ALIAS_START {
560 *inside = true;
561 return Some(None);
562 }
563 if *inside && line.trim() == ALIAS_END {
564 *inside = false;
565 return Some(None);
566 }
567 if *inside {
568 Some(None)
569 } else {
570 Some(Some(line))
571 }
572 })
573 .flatten()
574 .collect();
575 let _ = std::fs::write(&rc, filtered.join("\n") + "\n");
576 if !quiet {
577 println!(
578 " \x1b[33m⊖\x1b[0m Removed agent aliases from ~/{}",
579 slot.rc_file
580 );
581 }
582 }
583 let dropin = home.join(slot.dropin_dir).join(slot.dropin_file);
585 if dropin.exists() {
586 let _ = std::fs::remove_file(&dropin);
587 if !quiet {
588 println!(
589 " \x1b[33m⊖\x1b[0m Removed drop-in ~/{}/{}",
590 slot.dropin_dir, slot.dropin_file
591 );
592 }
593 }
594 }
595}
596
597fn build_env_check() -> String {
598 let checks: Vec<String> = KNOWN_AGENT_ENV_VARS
599 .iter()
600 .map(|v| format!("-n \"${v}\""))
601 .collect();
602 format!("[[ {} ]]", checks.join(" || "))
603}
604
605#[cfg(test)]
606pub mod test_helpers {
607 use super::*;
608 pub fn redirect_block_for_test(exec_var: &str, env_check: &str) -> String {
609 redirect_block(exec_var, env_check)
610 }
611}
612
613#[cfg(test)]
614mod tests {
615 use super::*;
616
617 fn test_stamp() -> BackupStamp {
621 BackupStamp::at(
622 chrono::DateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
623 .unwrap()
624 .with_timezone(&chrono::Utc),
625 )
626 }
627
628 #[test]
629 fn env_check_format() {
630 let check = build_env_check();
631 assert!(check.contains("LEAN_CTX_AGENT"));
632 assert!(check.contains("CLAUDECODE"));
633 assert!(check.contains("CODEBUDDY"));
634 assert!(check.contains("||"));
635 }
636
637 #[test]
638 fn source_command_matches_login_shell() {
639 assert_eq!(
641 source_command_for_shell("/usr/bin/bash"),
642 Some("source ~/.bashrc")
643 );
644 assert_eq!(
645 source_command_for_shell("/bin/zsh"),
646 Some("source ~/.zshrc")
647 );
648 assert_eq!(
649 source_command_for_shell("/usr/local/bin/fish"),
650 Some("source ~/.config/fish/config.fish")
651 );
652 assert_eq!(source_command_for_shell(""), None);
654 assert_eq!(source_command_for_shell("/bin/false"), None);
655 }
656
657 #[test]
658 fn rc_file_matches_login_shell() {
659 assert_eq!(rc_file_for_shell("/usr/bin/bash"), "~/.bashrc");
661 assert_eq!(rc_file_for_shell("/bin/zsh"), "~/.zshrc");
662 assert_eq!(
663 rc_file_for_shell("/usr/local/bin/fish"),
664 "~/.config/fish/config.fish"
665 );
666 assert_eq!(rc_file_for_shell(""), "your shell config");
667 assert_eq!(rc_file_for_shell("/bin/false"), "your shell config");
668 }
669
670 #[test]
671 fn pick_target_inline_when_forced() {
672 let tmp = tempfile::tempdir().unwrap();
673 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
675 std::fs::write(
676 tmp.path().join(".zshenv"),
677 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
678 )
679 .unwrap();
680 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Inline);
681 assert!(matches!(t, InstallTarget::Marked { .. }));
682 }
683
684 #[test]
685 fn pick_target_dropin_when_detected_under_auto() {
686 let tmp = tempfile::tempdir().unwrap();
687 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
688 std::fs::write(
689 tmp.path().join(".zshenv"),
690 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
691 )
692 .unwrap();
693 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
694 assert!(matches!(t, InstallTarget::DropIn { .. }));
695 }
696
697 #[test]
698 fn pick_target_inline_under_auto_when_no_dropin() {
699 let tmp = tempfile::tempdir().unwrap();
700 std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
701 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
702 assert!(matches!(t, InstallTarget::Marked { .. }));
703 }
704
705 #[test]
706 fn pick_target_dropin_falls_back_to_inline_when_no_directory() {
707 let tmp = tempfile::tempdir().unwrap();
710 std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
711 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::DropIn);
712 assert!(matches!(t, InstallTarget::Marked { .. }));
713 }
714
715 #[test]
716 fn install_zshenv_writes_inline_block() {
717 let tmp = tempfile::tempdir().unwrap();
718 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
719 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
720 assert!(body.contains(MARKER_START));
721 assert!(body.contains(MARKER_END));
722 assert!(body.contains("ZSH_EXECUTION_STRING"));
723 }
724
725 #[test]
726 fn install_zshenv_writes_dropin_when_loop_present() {
727 let tmp = tempfile::tempdir().unwrap();
728 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
729 std::fs::write(
730 tmp.path().join(".zshenv"),
731 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
732 )
733 .unwrap();
734 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
735
736 let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
737 assert!(dropin_file.exists(), "expected drop-in file");
738 let dropin_body = std::fs::read_to_string(&dropin_file).unwrap();
739 assert!(dropin_body.contains("ZSH_EXECUTION_STRING"));
740
741 let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
742 assert!(
743 !zshenv_body.contains(MARKER_START),
744 "drop-in install must not also leave the inline block"
745 );
746 }
747
748 fn find_migration_backups(path: &Path) -> Vec<PathBuf> {
751 let Some(parent) = path.parent() else {
752 return Vec::new();
753 };
754 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
755 return Vec::new();
756 };
757 let prefix = format!("{name}.lean-ctx-");
758 let mut out: Vec<PathBuf> = std::fs::read_dir(parent)
759 .into_iter()
760 .flatten()
761 .flatten()
762 .map(|e| e.path())
763 .filter(|p| {
764 p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
765 n.starts_with(&prefix)
766 && std::path::Path::new(n)
767 .extension()
768 .is_some_and(|ext| ext.eq_ignore_ascii_case("bak"))
769 })
770 })
771 .collect();
772 out.sort();
773 out
774 }
775
776 #[test]
777 fn migration_inline_to_dropin_preserves_hand_edits_via_backup() {
778 let tmp = tempfile::tempdir().unwrap();
779 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
780 let edited_zshenv = format!(
783 "export PATH=/usr/bin\n\
784 \n\
785 {MARKER_START}\n\
786 # USER CUSTOM: bump zsh history size for this workstation\n\
787 export HISTSIZE=99999\n\
788 # original lean-ctx hook content lived here\n\
789 {MARKER_END}\n\
790 \n\
791 for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
792 );
793 std::fs::write(tmp.path().join(".zshenv"), &edited_zshenv).unwrap();
794
795 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
796
797 let baks = find_migration_backups(&tmp.path().join(".zshenv"));
799 assert_eq!(baks.len(), 1, "expected one timestamped backup");
800 let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
801 assert_eq!(bak_body, edited_zshenv);
802 assert!(bak_body.contains("USER CUSTOM"));
803 assert!(bak_body.contains("HISTSIZE=99999"));
804 }
805
806 #[test]
807 fn migration_dropin_to_inline_preserves_hand_edits_via_backup() {
808 let tmp = tempfile::tempdir().unwrap();
809 let dropin_dir = tmp.path().join(".zshenv.d");
810 std::fs::create_dir_all(&dropin_dir).unwrap();
811 let edited_dropin = "# USER CUSTOM addition to lean-ctx drop-in\nexport FAVOURITE_EDITOR=helix\n# canonical lean-ctx content would follow\n";
813 std::fs::write(dropin_dir.join(DROPIN_ZSH), edited_dropin).unwrap();
814 std::fs::write(tmp.path().join(".zshenv"), "# plain zshenv\n").unwrap();
817
818 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
819
820 let baks = find_migration_backups(&dropin_dir.join(DROPIN_ZSH));
821 assert_eq!(baks.len(), 1, "expected one timestamped backup");
822 let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
823 assert_eq!(bak_body, edited_dropin);
824 assert!(bak_body.contains("USER CUSTOM"));
825 assert!(!dropin_dir.join(DROPIN_ZSH).exists());
827 let zshenv = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
828 assert!(zshenv.contains(MARKER_START));
829 }
830
831 #[test]
832 fn migration_skips_backup_when_no_prior_block_exists() {
833 let tmp = tempfile::tempdir().unwrap();
836 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
837 std::fs::write(
838 tmp.path().join(".zshenv"),
839 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
840 )
841 .unwrap();
842
843 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
844
845 assert!(
846 find_migration_backups(&tmp.path().join(".zshenv")).is_empty(),
847 "clean install should not create a .bak file"
848 );
849 }
850
851 #[test]
852 fn idempotent_dropin_reinstall_does_not_create_backup() {
853 let tmp = tempfile::tempdir().unwrap();
858 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
859 std::fs::write(
860 tmp.path().join(".zshenv"),
861 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
862 )
863 .unwrap();
864
865 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
866 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
867
868 {
869 let found = &find_migration_backups(&tmp.path().join(".zshenv"));
870 assert!(found.is_empty(), "{found:?}");
871 }
872 }
873
874 #[test]
875 fn backup_filename_handles_dotfile_correctly() {
876 let tmp = tempfile::tempdir().unwrap();
880 std::fs::write(tmp.path().join(".zshenv"), "content\n").unwrap();
881 save_migration_backup(&tmp.path().join(".zshenv"), true, &test_stamp());
882 let baks = find_migration_backups(&tmp.path().join(".zshenv"));
883 assert_eq!(baks.len(), 1);
884 let name = baks[0].file_name().unwrap().to_str().unwrap();
887 assert!(name.starts_with(".zshenv.lean-ctx-"), "got: {name}");
888 assert!(
889 std::path::Path::new(name)
890 .extension()
891 .is_some_and(|ext| ext.eq_ignore_ascii_case("bak"))
892 );
893 let stamp = name
895 .trim_start_matches(".zshenv.lean-ctx-")
896 .trim_end_matches(".bak");
897 assert_eq!(stamp.len(), 16, "stamp should be YYYYMMDDTHHMMSSZ: {stamp}");
898 assert!(stamp.contains('T'));
899 assert!(stamp.ends_with('Z'));
900 }
901
902 #[test]
903 fn repeated_migrations_never_clobber_prior_backups() {
904 let stamp_first = BackupStamp::at(
909 chrono::DateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
910 .unwrap()
911 .with_timezone(&chrono::Utc),
912 );
913 let stamp_later = BackupStamp::at(
914 chrono::DateTime::parse_from_rfc3339("2026-05-12T09:00:00Z")
915 .unwrap()
916 .with_timezone(&chrono::Utc),
917 );
918 let tmp = tempfile::tempdir().unwrap();
919 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
920
921 let with_block_v1 = format!(
922 "{MARKER_START}\n# first-era custom content\n{MARKER_END}\n\nfor f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
923 );
924 std::fs::write(tmp.path().join(".zshenv"), &with_block_v1).unwrap();
925 install_zshenv(tmp.path(), true, Style::Auto, &stamp_first);
926 let baks_after_first = find_migration_backups(&tmp.path().join(".zshenv"));
927 assert_eq!(baks_after_first.len(), 1);
928
929 let with_block_v2 = format!(
932 "{}{MARKER_START}\n# second-era custom content\n{MARKER_END}\n",
933 std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap(),
934 );
935 std::fs::write(tmp.path().join(".zshenv"), &with_block_v2).unwrap();
936 install_zshenv(tmp.path(), true, Style::Auto, &stamp_later);
937 let baks_after_second = find_migration_backups(&tmp.path().join(".zshenv"));
938
939 assert_eq!(
940 baks_after_second.len(),
941 2,
942 "second migration should leave a second backup, not overwrite"
943 );
944 assert_eq!(baks_after_second[0], baks_after_first[0]);
946 let first_body = std::fs::read_to_string(&baks_after_second[0]).unwrap();
947 let second_body = std::fs::read_to_string(&baks_after_second[1]).unwrap();
948 assert!(first_body.contains("first-era custom"));
949 assert!(second_body.contains("second-era custom"));
950 }
951
952 #[test]
953 fn install_migrates_inline_to_dropin() {
954 let tmp = tempfile::tempdir().unwrap();
955 std::fs::write(
957 tmp.path().join(".zshenv"),
958 format!(
959 "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",
960 ),
961 )
962 .unwrap();
963 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
964
965 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
966
967 let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
968 assert!(
969 !zshenv_body.contains(MARKER_START),
970 "old inline block should be stripped after migration"
971 );
972 assert!(
973 zshenv_body.contains(".zshenv.d"),
974 "source loop must be preserved"
975 );
976 let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
977 assert!(dropin_file.exists(), "new drop-in file should be present");
978 }
979
980 #[test]
981 fn install_migrates_dropin_to_inline() {
982 let tmp = tempfile::tempdir().unwrap();
983 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
986 std::fs::write(
987 tmp.path().join(".zshenv.d").join(DROPIN_ZSH),
988 "# stale lean-ctx drop-in\n",
989 )
990 .unwrap();
991 std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
992
993 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
994
995 assert!(
996 !tmp.path().join(".zshenv.d").join(DROPIN_ZSH).exists(),
997 "drop-in file should be removed when installing inline"
998 );
999 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1000 assert!(body.contains(MARKER_START));
1001 }
1002
1003 #[test]
1004 fn install_is_idempotent_in_dropin_mode() {
1005 let tmp = tempfile::tempdir().unwrap();
1006 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
1007 std::fs::write(
1008 tmp.path().join(".zshenv"),
1009 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
1010 )
1011 .unwrap();
1012
1013 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1014 let after_first = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
1015
1016 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1017 let after_second = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
1018
1019 assert_eq!(after_first, after_second);
1020 }
1021
1022 #[test]
1023 fn install_is_idempotent_in_inline_mode() {
1024 let tmp = tempfile::tempdir().unwrap();
1025 std::fs::write(tmp.path().join(".zshenv"), "# top\n").unwrap();
1026
1027 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1028 let after_first = std::fs::read(tmp.path().join(".zshenv")).unwrap();
1029
1030 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1031 let after_second = std::fs::read(tmp.path().join(".zshenv")).unwrap();
1032
1033 assert_eq!(after_first, after_second);
1034 }
1035
1036 #[test]
1037 fn install_aliases_skips_when_rc_missing() {
1038 let tmp = tempfile::tempdir().unwrap();
1039 install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
1041 assert!(!tmp.path().join(".zshrc").exists());
1042 assert!(!tmp.path().join(".bashrc").exists());
1043 }
1044
1045 #[test]
1046 fn install_aliases_writes_dropin_when_zshrc_d_configured() {
1047 let tmp = tempfile::tempdir().unwrap();
1048 std::fs::create_dir_all(tmp.path().join(".zshrc.d")).unwrap();
1049 std::fs::write(
1050 tmp.path().join(".zshrc"),
1051 "for f in $HOME/.zshrc.d/*.zsh; do source $f; done\n",
1052 )
1053 .unwrap();
1054
1055 install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
1056
1057 let dropin_file = tmp.path().join(".zshrc.d").join(DROPIN_ZSH);
1058 assert!(dropin_file.exists());
1059 let body = std::fs::read_to_string(&dropin_file).unwrap();
1060 assert!(body.contains("LEAN_CTX_AGENT=1"));
1061 }
1062
1063 #[test]
1066 fn zshenv_hook_contains_lc_passthrough_stubs() {
1067 let tmp = tempfile::tempdir().unwrap();
1068 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1069 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1070 assert!(
1071 body.contains(r#"_lc() { command "$@"; }"#),
1072 "zshenv must contain _lc passthrough stub"
1073 );
1074 assert!(
1075 body.contains(r#"_lc_compress() { command "$@"; }"#),
1076 "zshenv must contain _lc_compress passthrough stub"
1077 );
1078 }
1079
1080 #[test]
1081 fn bashenv_hook_contains_lc_passthrough_stubs() {
1082 let tmp = tempfile::tempdir().unwrap();
1083 install_bashenv(tmp.path(), true, Style::Inline, &test_stamp());
1084 let body = std::fs::read_to_string(tmp.path().join(".bashenv")).unwrap();
1085 assert!(
1086 body.contains(r#"_lc() { command "$@"; }"#),
1087 "bashenv must contain _lc passthrough stub"
1088 );
1089 assert!(
1090 body.contains(r#"_lc_compress() { command "$@"; }"#),
1091 "bashenv must contain _lc_compress passthrough stub"
1092 );
1093 }
1094
1095 #[test]
1096 fn stubs_appear_before_exec_guard() {
1097 let tmp = tempfile::tempdir().unwrap();
1098 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1099 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1100 let stub_pos = body.find("_lc()").expect("_lc stub must exist");
1101 let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1102 assert!(
1103 stub_pos < exec_pos,
1104 "stubs must be defined BEFORE the exec guard"
1105 );
1106 }
1107
1108 #[test]
1109 fn bash_stubs_appear_before_exec_guard() {
1110 let tmp = tempfile::tempdir().unwrap();
1116 install_bashenv(tmp.path(), true, Style::Inline, &test_stamp());
1117 let body = std::fs::read_to_string(tmp.path().join(".bashenv")).unwrap();
1118 let stub_pos = body.find("_lc()").expect("_lc stub must exist");
1119 let compress_pos = body
1120 .find("_lc_compress()")
1121 .expect("_lc_compress stub must exist");
1122 let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1123 assert!(
1124 stub_pos < exec_pos && compress_pos < exec_pos,
1125 "bash stubs must be defined BEFORE the exec guard"
1126 );
1127 }
1128
1129 #[test]
1137 fn redirect_block_guards_every_skip_marker() {
1138 let block = redirect_block("ZSH_EXECUTION_STRING", "[[ -n \"$LEAN_CTX_AGENT\" ]]");
1139 let exec_pos = block
1140 .find("exec lean-ctx")
1141 .expect("redirect must exec lean-ctx");
1142 for marker in REDIRECT_SKIP_MARKERS {
1143 let guard = format!("[[ \"$ZSH_EXECUTION_STRING\" != *\"{marker}\"* ]]");
1144 let guard_pos = block
1145 .find(&guard)
1146 .unwrap_or_else(|| panic!("redirect must guard against {marker:?}:\n{block}"));
1147 assert!(
1148 guard_pos < exec_pos,
1149 "guard for {marker:?} must precede the exec redirect"
1150 );
1151 }
1152 }
1153
1154 #[test]
1155 fn zshenv_redirect_skips_ide_sandbox_and_hooks() {
1156 let tmp = tempfile::tempdir().unwrap();
1157 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
1158 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
1159 let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1160 for marker in REDIRECT_SKIP_MARKERS {
1161 let guard = format!("[[ \"$ZSH_EXECUTION_STRING\" != *\"{marker}\"* ]]");
1162 let pos = body
1163 .find(&guard)
1164 .unwrap_or_else(|| panic!(".zshenv must guard against {marker:?}"));
1165 assert!(
1166 pos < exec_pos,
1167 "zshenv guard {marker:?} must precede the exec redirect"
1168 );
1169 }
1170 }
1171
1172 #[test]
1173 fn bashenv_redirect_skips_ide_sandbox_and_hooks() {
1174 let tmp = tempfile::tempdir().unwrap();
1175 install_bashenv(tmp.path(), true, Style::Inline, &test_stamp());
1176 let body = std::fs::read_to_string(tmp.path().join(".bashenv")).unwrap();
1177 let exec_pos = body.find("exec lean-ctx").expect("exec guard must exist");
1178 for marker in REDIRECT_SKIP_MARKERS {
1179 let guard = format!("[[ \"$BASH_EXECUTION_STRING\" != *\"{marker}\"* ]]");
1180 let pos = body
1181 .find(&guard)
1182 .unwrap_or_else(|| panic!(".bashenv must guard against {marker:?}"));
1183 assert!(
1184 pos < exec_pos,
1185 "bashenv guard {marker:?} must precede the exec redirect"
1186 );
1187 }
1188 }
1189
1190 #[test]
1191 fn dropin_zshenv_also_contains_stubs() {
1192 let tmp = tempfile::tempdir().unwrap();
1193 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
1194 std::fs::write(
1195 tmp.path().join(".zshenv"),
1196 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
1197 )
1198 .unwrap();
1199 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
1200
1201 let dropin = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
1202 let body = std::fs::read_to_string(&dropin).unwrap();
1203 assert!(body.contains("_lc()"), "drop-in must also contain stubs");
1204 }
1205
1206 #[cfg(unix)]
1211 static SHELL_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1212
1213 #[cfg(unix)]
1214 #[test]
1215 fn shell_available_rejects_unknown_shell() {
1216 let _env_lock = crate::core::data_dir::test_env_lock();
1217 let _g = SHELL_ENV_LOCK
1218 .lock()
1219 .unwrap_or_else(std::sync::PoisonError::into_inner);
1220 crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1221 assert!(!shell_available("fish"));
1222 assert!(!shell_available("nushell"));
1223 assert!(!shell_available(""));
1224 }
1225
1226 #[cfg(unix)]
1227 #[test]
1228 fn shell_available_finds_installed_shells() {
1229 let _env_lock = crate::core::data_dir::test_env_lock();
1230 let _g = SHELL_ENV_LOCK
1231 .lock()
1232 .unwrap_or_else(std::sync::PoisonError::into_inner);
1233 crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1234 let has_bash = Path::new("/bin/bash").exists() || Path::new("/usr/bin/bash").exists();
1236 let has_zsh = Path::new("/bin/zsh").exists() || Path::new("/usr/bin/zsh").exists();
1237 assert!(
1238 shell_available("bash") == has_bash,
1239 "shell_available(bash) should match filesystem"
1240 );
1241 assert!(
1242 shell_available("zsh") == has_zsh,
1243 "shell_available(zsh) should match filesystem"
1244 );
1245 }
1246
1247 #[cfg(unix)]
1248 #[test]
1249 fn shell_hook_force_overrides_detection() {
1250 let _env_lock = crate::core::data_dir::test_env_lock();
1251 let _g = SHELL_ENV_LOCK
1252 .lock()
1253 .unwrap_or_else(std::sync::PoisonError::into_inner);
1254
1255 crate::test_env::set_var("LEAN_CTX_SHELL_HOOK_FORCE", "all");
1257 assert!(shell_available("zsh"));
1258 assert!(shell_available("bash"));
1259
1260 crate::test_env::set_var("LEAN_CTX_SHELL_HOOK_FORCE", "zsh");
1262 assert!(shell_available("zsh"));
1263 crate::test_env::remove_var("LEAN_CTX_SHELL_HOOK_FORCE");
1267 }
1268}