Skip to main content

lean_ctx/cli/
shell_init.rs

1macro_rules! qprintln {
2    ($($t:tt)*) => {
3        if !super::quiet_enabled() {
4            println!($($t)*);
5        }
6    };
7}
8
9mod hook_refresh;
10pub use hook_refresh::refresh_installed_shell_hooks;
11use hook_refresh::write_lc_path_shims;
12
13pub fn print_hook_stdout(shell: &str) {
14    let binary = crate::core::portable_binary::stable_shell_binary(
15        &crate::core::portable_binary::resolve_portable_binary(),
16    );
17    let binary = hook_binary_for_shell(shell, &binary);
18
19    let code = match shell {
20        "bash" | "zsh" => generate_hook_posix(&binary),
21        "fish" => generate_hook_fish(&binary),
22        "powershell" | "pwsh" => generate_hook_powershell(&binary),
23        _ => {
24            tracing::error!("lean-ctx: unsupported shell '{shell}'");
25            eprintln!("Supported: bash, zsh, fish, powershell");
26            std::process::exit(1);
27        }
28    };
29    print!("{code}");
30}
31
32/// Pick the executable-path form to embed in a generated shell hook.
33///
34/// bash/zsh/fish (incl. Git Bash / MSYS on Windows) source the hook and invoke
35/// the binary from a POSIX shell, so on Windows they need the MSYS `/c/...`
36/// form. PowerShell and `pwsh` execute the path via the `&` call operator and
37/// cannot run an MSYS `/c/...` path (#518); they get the native path unchanged.
38/// On Unix `to_bash_compatible_path` is a no-op, so all shells are unaffected.
39fn hook_binary_for_shell(shell: &str, binary: &str) -> String {
40    match shell {
41        "powershell" | "pwsh" => binary.to_string(),
42        _ => crate::hooks::to_bash_compatible_path(binary),
43    }
44}
45
46pub(super) fn backup_shell_config(path: &std::path::Path) {
47    if !path.exists() {
48        return;
49    }
50    let bak = path.with_extension("lean-ctx.bak");
51    if std::fs::copy(path, &bak).is_ok() {
52        qprintln!(
53            "  Backup: {}",
54            bak.file_name().map_or_else(
55                || bak.display().to_string(),
56                |n| format!("~/{}", n.to_string_lossy())
57            )
58        );
59    }
60}
61
62/// Directory for config artifacts written by `init`/`setup` — shell hooks and
63/// `env.sh`. These are config files (RO-safe), so they live in [`config_dir`]
64/// (GH #408). For legacy/mixed installs `config_dir()` collapses onto the same
65/// single directory as before, so this is a no-op there.
66pub(super) fn config_artifact_dir() -> Option<std::path::PathBuf> {
67    crate::core::paths::config_dir().ok()
68}
69
70pub(super) fn write_hook_file(filename: &str, content: &str) -> Option<std::path::PathBuf> {
71    let dir = config_artifact_dir()?;
72    let _ = std::fs::create_dir_all(&dir);
73    let path = dir.join(filename);
74    match std::fs::write(&path, content) {
75        Ok(()) => {
76            #[cfg(unix)]
77            {
78                use std::os::unix::fs::PermissionsExt;
79                let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644));
80            }
81            Some(path)
82        }
83        Err(e) => {
84            tracing::error!("Error writing {}: {e}", path.display());
85            None
86        }
87    }
88}
89
90pub(super) fn resolved_hook_dir_display() -> String {
91    config_artifact_dir().map_or_else(
92        || "$HOME/.config/lean-ctx".to_string(),
93        |p| p.to_string_lossy().to_string(),
94    )
95}
96
97fn source_line_posix(shell_ext: &str) -> String {
98    let mut dir = resolved_hook_dir_display();
99    // Git Bash / MSYS expects /c/... style paths in bashrc/zshrc.
100    if cfg!(windows) {
101        dir = crate::hooks::to_bash_compatible_path(&dir);
102    }
103    format!(
104        "# lean-ctx shell hook — begin\n\
105         if [ -f \"{dir}/shell-hook.{shell_ext}\" ]; then\n\
106           . \"{dir}/shell-hook.{shell_ext}\"\n\
107         fi\n\
108         # lean-ctx shell hook — end\n"
109    )
110}
111
112fn source_line_fish() -> String {
113    let mut dir = resolved_hook_dir_display();
114    // Fish on Windows (MSYS) also expects /c/... style paths.
115    if cfg!(windows) {
116        dir = crate::hooks::to_bash_compatible_path(&dir);
117    }
118    format!(
119        "# lean-ctx shell hook — begin\n\
120         if test -f \"{dir}/shell-hook.fish\"\n\
121           source \"{dir}/shell-hook.fish\"\n\
122         end\n\
123         # lean-ctx shell hook — end\n"
124    )
125}
126
127fn source_line_powershell() -> String {
128    let dir = resolved_hook_dir_display();
129    let dir_ps = dir.replace('/', "\\");
130    format!(
131        "# lean-ctx shell hook — begin\n\
132         $leanCtxHook = \"{dir_ps}\\shell-hook.ps1\"\n\
133         if ((Test-Path $leanCtxHook) -and -not [Console]::IsOutputRedirected) {{ . $leanCtxHook }}\n"
134    )
135}
136
137fn upsert_source_line(rc_path: &std::path::Path, source_line: &str) {
138    backup_shell_config(rc_path);
139
140    if let Ok(existing) = std::fs::read_to_string(rc_path) {
141        if existing.contains(source_line.trim()) {
142            return;
143        }
144
145        // Remove any legacy blocks and one-liner source lines, then append our canonical block.
146        let cleaned = remove_lean_ctx_block(&existing);
147        let cleaned = cleaned
148            .lines()
149            .filter(|line| {
150                !line.contains("lean-ctx/shell-hook.")
151                    && !line.contains("lean-ctx\\shell-hook.")
152                    && line.trim() != "lean-ctx shell hook"
153            })
154            .collect::<Vec<_>>()
155            .join("\n");
156        let cleaned = if cleaned.ends_with('\n') {
157            cleaned
158        } else {
159            format!("{cleaned}\n")
160        };
161
162        match std::fs::write(rc_path, format!("{cleaned}{source_line}")) {
163            Ok(()) => {
164                qprintln!("Updated lean-ctx hook in {}", rc_path.display());
165            }
166            Err(e) => {
167                tracing::error!("Error updating {}: {e}", rc_path.display());
168                print_shell_write_error(rc_path, source_line, &e);
169            }
170        }
171        return;
172    }
173
174    match std::fs::OpenOptions::new()
175        .append(true)
176        .create(true)
177        .open(rc_path)
178    {
179        Ok(mut f) => {
180            use std::io::Write;
181            let _ = f.write_all(source_line.as_bytes());
182            qprintln!("Added lean-ctx hook to {}", rc_path.display());
183        }
184        Err(e) => {
185            tracing::error!("Error writing {}: {e}", rc_path.display());
186            print_shell_write_error(rc_path, source_line, &e);
187        }
188    }
189}
190
191fn print_shell_write_error(rc_path: &std::path::Path, source_line: &str, err: &std::io::Error) {
192    eprintln!();
193    eprintln!("  \x1B[33m⚠ Cannot write to {}\x1B[0m", rc_path.display());
194    eprintln!("    Error: {err}");
195    if err.kind() == std::io::ErrorKind::PermissionDenied {
196        eprintln!();
197        eprintln!("    Your shell config is read-only (nix-darwin, Home Manager, or similar).");
198        eprintln!("    Add the following to a writable shell config file manually:");
199    } else {
200        eprintln!();
201        eprintln!("    Add the following to your shell config manually:");
202    }
203    eprintln!();
204    for line in source_line.lines() {
205        eprintln!("      {line}");
206    }
207    eprintln!();
208    eprintln!("    Or source it from a writable file (e.g. ~/.zshrc.local):");
209    eprintln!("      echo 'source ~/.zshrc.local' # (add to nix config)");
210    eprintln!("      Then add the hook lines to ~/.zshrc.local");
211    eprintln!();
212}
213
214pub fn generate_hook_powershell(binary: &str) -> String {
215    let config = crate::core::config::Config::load();
216    let activation = config.shell_activation_effective();
217    let baked_default = match activation {
218        crate::core::config::ShellActivation::Always => "always",
219        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
220        crate::core::config::ShellActivation::Off => "off",
221    };
222    let binary_escaped = binary.replace('\\', "\\\\");
223    format!(
224        r#"# lean-ctx shell hook — transparent CLI compression (95+ patterns)
225$_leanCtxActivation = if ($env:LEAN_CTX_SHELL_ACTIVATION) {{ $env:LEAN_CTX_SHELL_ACTIVATION }} else {{ "{baked_default}" }}
226$_leanCtxShouldActivate = $false
227if (-not $env:LEAN_CTX_ACTIVE -and -not $env:LEAN_CTX_DISABLED -and -not $env:LEAN_CTX_NO_HOOK) {{
228  switch ($_leanCtxActivation) {{
229    {{ $_ -in 'off','none','manual' }} {{ $_leanCtxShouldActivate = $false }}
230    {{ $_ -in 'agents-only','agents_only','agentsonly' }} {{
231      $_leanCtxShouldActivate = $env:LEAN_CTX_AGENT -or $env:CURSOR_AGENT -or $env:CLAUDECODE -or $env:CODEBUDDY -or $env:CODEX_CLI_SESSION -or $env:GEMINI_SESSION
232    }}
233    default {{ $_leanCtxShouldActivate = $true }}
234  }}
235}}
236if ($_leanCtxShouldActivate) {{
237  $LeanCtxBin = "{binary_escaped}"
238  function _lc {{
239    $nativeCmd = Get-Command $args[0] -CommandType Application -ErrorAction SilentlyContinue
240    if ($env:LEAN_CTX_DISABLED -or $env:LEAN_CTX_NO_HOOK -or [Console]::IsOutputRedirected) {{
241      if ($nativeCmd) {{ & $nativeCmd.Source $args[1..$args.Length] }} else {{ Write-Error "Command not found: $($args[0])" }}
242      return
243    }}
244    & $LeanCtxBin -c @args
245    if ($LASTEXITCODE -eq 127 -or $LASTEXITCODE -eq 126) {{
246      if ($nativeCmd) {{ & $nativeCmd.Source $args[1..$args.Length] }} else {{ Write-Error "Command not found: $($args[0])" }}
247    }}
248  }}
249  function lean-ctx-raw {{ $env:LEAN_CTX_RAW = '1'; & @args; Remove-Item Env:LEAN_CTX_RAW -ErrorAction SilentlyContinue }}
250  if (Get-Command lean-ctx -ErrorAction SilentlyContinue) {{
251    function git {{ _lc git @args }}
252    function cargo {{ _lc cargo @args }}
253    function docker {{ _lc docker @args }}
254    function kubectl {{ _lc kubectl @args }}
255    function gh {{ _lc gh @args }}
256    function pip {{ _lc pip @args }}
257    function pip3 {{ _lc pip3 @args }}
258    function ruff {{ _lc ruff @args }}
259    function go {{ _lc go @args }}
260    function curl {{ _lc curl @args }}
261    function wget {{ _lc wget @args }}
262    foreach ($c in @('npm','pnpm','yarn','eslint','prettier','tsc')) {{
263      if (Get-Command $c -CommandType Application -ErrorAction SilentlyContinue) {{
264        $body = "_lc $c `@args"
265        New-Item -Path "function:$c" -Value ([scriptblock]::Create($body)) -Force | Out-Null
266      }}
267    }}
268  }}
269}}
270"#
271    )
272}
273
274pub fn init_powershell(binary: &str) {
275    // OS-aware profile path: ~/.config/powershell on macOS/Linux (never ~/Documents,
276    // which triggers a macOS TCC prompt, #356). On Windows resolve the live $PROFILE
277    // so OneDrive-redirected Documents folders are honored (#558).
278    let profile_path = if let Some(home) = dirs::home_dir() {
279        let path = crate::shell::platform::resolve_powershell_profile_path(&home);
280        if let Some(dir) = path.parent() {
281            let _ = std::fs::create_dir_all(dir);
282        }
283        path
284    } else {
285        tracing::error!("Could not resolve PowerShell profile directory");
286        return;
287    };
288
289    let hook_content = generate_hook_powershell(binary);
290
291    if write_hook_file("shell-hook.ps1", &hook_content).is_some() {
292        upsert_source_line(&profile_path, &source_line_powershell());
293        qprintln!("  Binary: {binary}");
294    }
295}
296
297pub fn remove_lean_ctx_block_ps(content: &str) -> String {
298    let mut result = String::new();
299    let mut in_block = false;
300    let mut brace_depth = 0i32;
301
302    for line in content.lines() {
303        if line.contains("lean-ctx shell hook") {
304            in_block = true;
305            continue;
306        }
307        if in_block {
308            brace_depth += line.matches('{').count() as i32;
309            brace_depth -= line.matches('}').count() as i32;
310            if brace_depth <= 0 && (line.trim() == "}" || line.trim().is_empty()) {
311                if line.trim() == "}" {
312                    in_block = false;
313                    brace_depth = 0;
314                }
315                continue;
316            }
317            continue;
318        }
319        result.push_str(line);
320        result.push('\n');
321    }
322    result
323}
324
325pub fn generate_hook_fish(binary: &str) -> String {
326    let config = crate::core::config::Config::load();
327    let activation = config.shell_activation_effective();
328    let baked_default = match activation {
329        crate::core::config::ShellActivation::Always => "always",
330        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
331        crate::core::config::ShellActivation::Off => "off",
332    };
333    let alias_list = crate::rewrite_registry::shell_alias_list();
334    format!(
335        "# lean-ctx shell hook — smart shell mode (track-by-default)\n\
336        set -g _lean_ctx_cmds {alias_list}\n\
337        \n\
338        function _lc_is_agent\n\
339        \tset -q LEAN_CTX_AGENT; or set -q CURSOR_AGENT; or set -q CODEX_CLI_SESSION; or set -q CLAUDECODE; or set -q CODEBUDDY; or set -q GEMINI_SESSION\n\
340        end\n\
341        \n\
342        function _lean_ctx_notice\n\
343        \tif isatty stdout; and set -q LEAN_CTX_DEBUG\n\
344        \t\techo $argv\n\
345        \tend\n\
346        end\n\
347        \n\
348        function _lc\n\
349        \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK\n\
350        \t\tcommand $argv\n\
351        \t\treturn\n\
352        \tend\n\
353        \tif not isatty stdout; and not _lc_is_agent\n\
354        \t\tcommand $argv\n\
355        \t\treturn\n\
356        \tend\n\
357        \t'{binary}' -t $argv\n\
358        \tset -l _lc_rc $status\n\
359        \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
360        \t\tcommand $argv\n\
361        \telse\n\
362        \t\treturn $_lc_rc\n\
363        \tend\n\
364        end\n\
365        \n\
366        function _lc_compress\n\
367        \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK\n\
368        \t\tcommand $argv\n\
369        \t\treturn\n\
370        \tend\n\
371        \tif not isatty stdout; and not _lc_is_agent\n\
372        \t\tcommand $argv\n\
373        \t\treturn\n\
374        \tend\n\
375        \t'{binary}' -c $argv\n\
376        \tset -l _lc_rc $status\n\
377        \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
378        \t\tcommand $argv\n\
379        \telse\n\
380        \t\treturn $_lc_rc\n\
381        \tend\n\
382        end\n\
383        \n\
384        function lean-ctx-on\n\
385        \tfor _lc_cmd in $_lean_ctx_cmds\n\
386        \t\talias $_lc_cmd '_lc '$_lc_cmd\n\
387        \tend\n\
388        \talias k '_lc kubectl'\n\
389        \tset -gx LEAN_CTX_ENABLED 1\n\
390        \t_lean_ctx_notice 'lean-ctx: ON (track mode — output unchanged, token savings recorded)'\n\
391        end\n\
392        \n\
393        function lean-ctx-off\n\
394        \tfor _lc_cmd in $_lean_ctx_cmds\n\
395        \t\tfunctions --erase $_lc_cmd 2>/dev/null; true\n\
396        \tend\n\
397        \tfunctions --erase k 2>/dev/null; true\n\
398        \tset -gx LEAN_CTX_ENABLED 0\n\
399        \t_lean_ctx_notice 'lean-ctx: OFF'\n\
400        end\n\
401        \n\
402        function lean-ctx-mode\n\
403        \tswitch $argv[1]\n\
404        \t\tcase compress\n\
405        \t\t\tfor _lc_cmd in $_lean_ctx_cmds\n\
406        \t\t\t\talias $_lc_cmd '_lc_compress '$_lc_cmd\n\
407        \t\t\t\tend\n\
408        \t\t\talias k '_lc_compress kubectl'\n\
409        \t\t\tset -gx LEAN_CTX_ENABLED 1\n\
410        \t\t\t_lean_ctx_notice 'lean-ctx: COMPRESS mode (all output compressed)'\n\
411        \t\tcase track\n\
412        \t\t\tlean-ctx-on\n\
413        \t\tcase off\n\
414        \t\t\tlean-ctx-off\n\
415        \t\tcase '*'\n\
416        \t\t\techo 'Usage: lean-ctx-mode <track|compress|off>'\n\
417        \t\t\techo '  track    — Full output, stats recorded (default)'\n\
418        \t\t\techo '  compress — Compressed output for all commands'\n\
419        \t\t\techo '  off      — No aliases, raw shell'\n\
420        \tend\n\
421        end\n\
422        \n\
423        function lean-ctx-raw\n\
424        \tset -lx LEAN_CTX_RAW 1\n\
425        \tcommand $argv\n\
426        end\n\
427        \n\
428        # Exit status 0 = ON, 1 = OFF/DISABLED; LEAN_CTX_ENABLED=0 is OFF (#1971).\n\
429        function lean-ctx-status\n\
430        \tif set -q LEAN_CTX_DISABLED\n\
431        \t\tisatty stdout; and echo 'lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)'\n\
432        \t\treturn 1\n\
433        \telse if set -q LEAN_CTX_ENABLED; and test \"$LEAN_CTX_ENABLED\" != 0\n\
434        \t\tisatty stdout; and echo 'lean-ctx: ON'\n\
435        \t\treturn 0\n\
436        \telse\n\
437        \t\tisatty stdout; and echo 'lean-ctx: OFF'\n\
438        \t\treturn 1\n\
439        \tend\n\
440        end\n\
441        \n\
442        function _lean_ctx_should_activate\n\
443        \tif set -q LEAN_CTX_ACTIVE; or set -q LEAN_CTX_DISABLED; or test (set -q LEAN_CTX_ENABLED; and echo $LEAN_CTX_ENABLED; or echo 1) = '0'\n\
444        \t\treturn 1\n\
445        \tend\n\
446        \tset -l _lc_mode (set -q LEAN_CTX_SHELL_ACTIVATION; and echo $LEAN_CTX_SHELL_ACTIVATION; or echo '{baked_default}')\n\
447        \tswitch $_lc_mode\n\
448        \t\tcase off none manual\n\
449        \t\t\treturn 1\n\
450        \t\tcase 'agents-only' agents_only agentsonly\n\
451        \t\t\tif _lc_is_agent\n\
452        \t\t\t\treturn 0\n\
453        \t\t\tend\n\
454        \t\t\treturn 1\n\
455        \t\tcase '*'\n\
456        \t\t\treturn 0\n\
457        \tend\n\
458        end\n\
459        \n\
460        if _lean_ctx_should_activate\n\
461        \tif command -q lean-ctx\n\
462        \t\tlean-ctx-on\n\
463        \tend\n\
464        end\n"
465    )
466}
467
468pub fn init_fish(binary: &str) {
469    let config = dirs::home_dir()
470        .map(|h| h.join(".config/fish/config.fish"))
471        .unwrap_or_default();
472
473    let hook_content = generate_hook_fish(binary);
474
475    if write_hook_file("shell-hook.fish", &hook_content).is_some() {
476        upsert_source_line(&config, &source_line_fish());
477        qprintln!("  Binary: {binary}");
478    }
479}
480
481pub fn generate_hook_posix(binary: &str) -> String {
482    let config = crate::core::config::Config::load();
483    let activation = config.shell_activation_effective();
484    let baked_default = match activation {
485        crate::core::config::ShellActivation::Always => "always",
486        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
487        crate::core::config::ShellActivation::Off => "off",
488    };
489    let alias_list = crate::rewrite_registry::shell_alias_list();
490    format!(
491        r#"# lean-ctx shell hook — smart shell mode (track-by-default)
492_lean_ctx_cmds=({alias_list})
493
494# Everything an alias or a user command reaches is named without a leading
495# underscore: agent harnesses that snapshot + replay the shell (Claude Code's
496# Bash tool) drop `_`-prefixed functions but keep the aliases calling them,
497# which failed every aliased command with `_lc: command not found` (#1898).
498lean_ctx_is_agent() {{
499    [ -n "${{LEAN_CTX_AGENT:-}}" ] || [ -n "${{CURSOR_AGENT:-}}" ] || [ -n "${{CODEX_CLI_SESSION:-}}" ] || [ -n "${{CLAUDECODE:-}}" ] || [ -n "${{CODEBUDDY:-}}" ] || [ -n "${{GEMINI_SESSION:-}}" ]
500}}
501
502lean_ctx_notice() {{
503    [ -n "${{LEAN_CTX_DEBUG:-}}" ] && [ -t 1 ] && echo "$@"
504}}
505
506lean_ctx_track() {{
507    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ]; then
508        command "$@"
509        return
510    fi
511    if [ ! -t 1 ] && ! lean_ctx_is_agent; then
512        command "$@"
513        return
514    fi
515    '{binary}' -t "$@"
516    local _lc_rc=$?
517    if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
518        command "$@"
519    else
520        return "$_lc_rc"
521    fi
522}}
523
524lean_ctx_compress() {{
525    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ]; then
526        command "$@"
527        return
528    fi
529    if [ ! -t 1 ] && ! lean_ctx_is_agent; then
530        command "$@"
531        return
532    fi
533    '{binary}' -c "$@"
534    local _lc_rc=$?
535    if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
536        command "$@"
537    else
538        return "$_lc_rc"
539    fi
540}}
541
542# Pre-#1898 names, kept for aliases defined by an older hook in a live shell.
543_lc_is_agent() {{ lean_ctx_is_agent; }}
544_lc() {{ lean_ctx_track "$@"; }}
545_lc_compress() {{ lean_ctx_compress "$@"; }}
546
547lean-ctx-on() {{
548    for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
549        # shellcheck disable=SC2139
550        alias "$_lc_cmd"='lean_ctx_track '"$_lc_cmd"
551    done
552    alias k='lean_ctx_track kubectl'
553    export LEAN_CTX_ENABLED=1
554    lean_ctx_notice "lean-ctx: ON (track mode — output unchanged, token savings recorded)"
555}}
556
557lean-ctx-off() {{
558    for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
559        unalias "$_lc_cmd" 2>/dev/null || true
560    done
561    unalias k 2>/dev/null || true
562    export LEAN_CTX_ENABLED=0
563    lean_ctx_notice "lean-ctx: OFF"
564}}
565
566lean-ctx-mode() {{
567    case "${{1:-}}" in
568        compress)
569            for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
570                # shellcheck disable=SC2139
571                alias "$_lc_cmd"='lean_ctx_compress '"$_lc_cmd"
572            done
573            alias k='lean_ctx_compress kubectl'
574            export LEAN_CTX_ENABLED=1
575            lean_ctx_notice "lean-ctx: COMPRESS mode (all output compressed)"
576            ;;
577        track)
578            lean-ctx-on
579            ;;
580        off)
581            lean-ctx-off
582            ;;
583        *)
584            echo "Usage: lean-ctx-mode <track|compress|off>"
585            echo "  track    — Full output, stats recorded (default)"
586            echo "  compress — Compressed output for all commands"
587            echo "  off      — No aliases, raw shell"
588            ;;
589    esac
590}}
591
592lean-ctx-raw() {{
593    LEAN_CTX_RAW=1 command "$@"
594}}
595
596# Exit status 0 = ON, 1 = OFF/DISABLED. lean-ctx-off exports
597# LEAN_CTX_ENABLED=0, so a set-but-zero value is OFF, not ON (#1971).
598lean-ctx-status() {{
599    if [ -n "${{LEAN_CTX_DISABLED:-}}" ]; then
600        [ -t 1 ] && echo "lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)"
601        return 1
602    elif [ "${{LEAN_CTX_ENABLED:-0}}" != "0" ]; then
603        [ -t 1 ] && echo "lean-ctx: ON"
604        return 0
605    else
606        [ -t 1 ] && echo "lean-ctx: OFF"
607        return 1
608    fi
609}}
610
611if [ -n "${{ZSH_VERSION:-}}" ]; then
612    _lean-ctx() {{
613        local -a completions
614        local IFS=$'\n'
615        completions=(${{(f)$(lean-ctx __complete zsh -- "${{words[@]:1}}")}})
616        if (( ${{#completions}} )); then
617            _describe -t commands 'lean-ctx' completions
618        fi
619    }}
620    _lean_ctx_passthrough() {{
621        shift words
622        (( CURRENT-- ))
623        _normal
624    }}
625    compdef _lean-ctx lean-ctx 2>/dev/null
626    compdef _lean-ctx lctx 2>/dev/null
627    compdef _lean_ctx_passthrough lean_ctx_track 2>/dev/null
628    compdef _lean_ctx_passthrough lean_ctx_compress 2>/dev/null
629    compdef _lean_ctx_passthrough _lc 2>/dev/null
630    compdef _lean_ctx_passthrough _lc_compress 2>/dev/null
631fi
632
633_lean_ctx_should_activate() {{
634    [ -z "${{LEAN_CTX_ACTIVE:-}}" ] && [ -z "${{LEAN_CTX_DISABLED:-}}" ] && [ "${{LEAN_CTX_ENABLED:-1}}" != "0" ] || return 1
635    case "${{LEAN_CTX_SHELL_ACTIVATION:-{baked_default}}}" in
636        off|none|manual) return 1 ;;
637        agents-only|agents_only|agentsonly)
638            lean_ctx_is_agent ;;
639        *) return 0 ;;
640    esac
641}}
642
643if _lean_ctx_should_activate; then
644    command -v lean-ctx >/dev/null 2>&1 && lean-ctx-on
645fi
646"#
647    )
648}
649
650pub fn init_posix(is_zsh: bool, binary: &str) {
651    let rc_file = if is_zsh {
652        dirs::home_dir()
653            .map(|h| h.join(".zshrc"))
654            .unwrap_or_default()
655    } else {
656        dirs::home_dir()
657            .map(|h| h.join(".bashrc"))
658            .unwrap_or_default()
659    };
660
661    let shell_ext = if is_zsh { "zsh" } else { "bash" };
662    let hook_content = generate_hook_posix(binary);
663
664    if let Some(hook_path) = write_hook_file(&format!("shell-hook.{shell_ext}"), &hook_content) {
665        upsert_source_line(&rc_file, &source_line_posix(shell_ext));
666
667        // Bash login shells don't read ~/.bashrc — make sure they pick it up so the hook
668        // (and the installer's PATH export) take effect in Terminal.app / IDE login shells.
669        if !is_zsh {
670            ensure_bash_login_sources_bashrc();
671        }
672
673        qprintln!("  Binary: {binary}");
674
675        write_env_sh_for_containers(&hook_content);
676        write_lc_path_shims(binary);
677        print_docker_env_hints(is_zsh);
678
679        let _ = hook_path;
680    }
681}
682
683/// Bash login shells (macOS Terminal.app, many IDE terminals, `bash -l`) read
684/// `~/.bash_profile` (or `~/.bash_login` / `~/.profile`) and never `~/.bashrc`. Because we
685/// install the hook — and the installer adds `~/.local/bin` to PATH — into `~/.bashrc`, a login
686/// shell would otherwise see neither. Ensure the login profile sources `~/.bashrc`, exactly as
687/// the Debian/Ubuntu default `.profile` does. Idempotent; zsh is unaffected (it always reads
688/// `~/.zshrc`), so this is only wired in for bash.
689fn ensure_bash_login_sources_bashrc() {
690    let Some(home) = dirs::home_dir() else {
691        return;
692    };
693
694    // Bash reads only the FIRST existing of these on login; target that one, else create
695    // ~/.bash_profile. (~/.bashrc is never a login file, so it's not a candidate.)
696    let target = [".bash_profile", ".bash_login", ".profile"]
697        .iter()
698        .map(|f| home.join(f))
699        .find(|p| p.exists())
700        .unwrap_or_else(|| home.join(".bash_profile"));
701
702    // Already sourcing ~/.bashrc (our snippet or the user's own)? Nothing to do.
703    if let Ok(existing) = std::fs::read_to_string(&target) {
704        let sources_bashrc = existing
705            .lines()
706            .any(|l| !l.trim_start().starts_with('#') && l.contains(".bashrc"));
707        if sources_bashrc {
708            return;
709        }
710    }
711
712    let snippet = "\n# lean-ctx: load ~/.bashrc in login shells (e.g. macOS Terminal) — begin\n\
713         if [ -f \"$HOME/.bashrc\" ]; then . \"$HOME/.bashrc\"; fi\n\
714         # lean-ctx: load ~/.bashrc in login shells (e.g. macOS Terminal) — end\n";
715
716    backup_shell_config(&target);
717    match std::fs::OpenOptions::new()
718        .append(true)
719        .create(true)
720        .open(&target)
721    {
722        Ok(mut f) => {
723            use std::io::Write;
724            if f.write_all(snippet.as_bytes()).is_ok() {
725                qprintln!("  Login shell: {} now sources ~/.bashrc", target.display());
726            }
727        }
728        Err(e) => {
729            tracing::warn!("could not update {}: {e}", target.display());
730        }
731    }
732}
733
734pub fn write_env_sh_for_containers(aliases: &str) {
735    // env.sh is a config artifact (sourced via BASH_ENV/CLAUDE_ENV_FILE) → config_dir (#408).
736    let env_sh = match crate::core::paths::config_dir() {
737        Ok(d) => d.join("env.sh"),
738        Err(_) => return,
739    };
740    if let Some(parent) = env_sh.parent() {
741        let _ = std::fs::create_dir_all(parent);
742    }
743    let sanitized_aliases = crate::core::sanitize::neutralize_shell_content(aliases);
744    let mut content = String::from(
745        r#"# lean-ctx: passthrough stubs for non-interactive subshells (fixes #255).
746# These ensure _lc/_lc_compress exist so inherited aliases don't break.
747# The full hook definitions override these when the interactive shell loads.
748_lc()          { command "$@"; }
749_lc_compress() { command "$@"; }
750
751"#,
752    );
753    content.push_str(&sanitized_aliases);
754    content.push_str(
755        r#"
756
757# lean-ctx docker self-heal: re-inject Claude MCP config if Claude overwrote ~/.claude.json
758# Guards: container-only + no recursion + no re-entry via BASH_ENV + 60s cooldown + PID-lock
759if [ -f /.dockerenv ] || grep -qsE '/docker/|/lxc/' /proc/1/cgroup 2>/dev/null; then
760  if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ -z "${_LEAN_CTX_HEAL:-}" ]; then
761    # XDG-only paths (GL #623): never touch ~/.lean-ctx, which would re-collapse
762    # a committed XDG layout. heal_ts is STATE, locks live in the DATA dir
763    # (matches process_guard::lock_dir defaults).
764    _LEAN_CTX_STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/lean-ctx"
765    _LEAN_CTX_HEAL_TS="${_LEAN_CTX_STATE_DIR}/.heal_ts"
766    _LEAN_CTX_HEAL_COOLDOWN=60
767    _lean_ctx_heal_needed=1
768    if [ -f "$_LEAN_CTX_HEAL_TS" ]; then
769      _last_heal=$(cat "$_LEAN_CTX_HEAL_TS" 2>/dev/null || echo 0)
770      _now=$(date +%s 2>/dev/null || echo 0)
771      if [ $(( _now - _last_heal )) -lt $_LEAN_CTX_HEAL_COOLDOWN ]; then
772        _lean_ctx_heal_needed=0
773      fi
774    fi
775    _lean_ctx_lock_count=0
776    for _lf in "${XDG_DATA_HOME:-$HOME/.local/share}/lean-ctx/locks"/slot-*.lock; do
777      [ -f "$_lf" ] && _lean_ctx_lock_count=$(( _lean_ctx_lock_count + 1 ))
778    done
779    if [ "$_lean_ctx_heal_needed" = "1" ] && [ "$_lean_ctx_lock_count" -lt 4 ]; then
780      export _LEAN_CTX_HEAL=1
781      if command -v claude >/dev/null 2>&1 && command -v lean-ctx >/dev/null 2>&1; then
782        if ! claude mcp list 2>/dev/null | grep -q "lean-ctx"; then
783          LEAN_CTX_ACTIVE=1 LEAN_CTX_QUIET=1 lean-ctx init --agent claude >/dev/null 2>&1
784          mkdir -p "$_LEAN_CTX_STATE_DIR" 2>/dev/null
785          date +%s > "$_LEAN_CTX_HEAL_TS" 2>/dev/null
786        fi
787      fi
788    fi
789  fi
790fi
791"#,
792    );
793    match std::fs::write(&env_sh, content) {
794        Ok(()) => {
795            // Keep JSON-mode stdout clean; non-quiet hints go to stderr.
796            if !super::quiet_enabled() {
797                eprintln!("  env.sh: {}", env_sh.display());
798            }
799        }
800        Err(e) => tracing::warn!("could not write {}: {e}", env_sh.display()),
801    }
802}
803
804fn print_docker_env_hints(is_zsh: bool) {
805    if is_zsh || !crate::shell::is_container() {
806        return;
807    }
808    let env_sh = crate::core::paths::config_dir().map_or_else(
809        |_| "/root/.config/lean-ctx/env.sh".to_string(),
810        |d| d.join("env.sh").to_string_lossy().to_string(),
811    );
812
813    let has_bash_env = std::env::var("BASH_ENV").is_ok();
814    let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
815
816    if has_bash_env && has_claude_env {
817        return;
818    }
819
820    eprintln!();
821    eprintln!("  \x1b[33m⚠  Docker detected — environment hints:\x1b[0m");
822
823    if !has_bash_env {
824        eprintln!("  For generic bash -c usage (non-interactive shells):");
825        eprintln!("    \x1b[1mENV BASH_ENV=\"{env_sh}\"\x1b[0m");
826    }
827    if !has_claude_env {
828        eprintln!("  For Claude Code (sources before each command):");
829        eprintln!("    \x1b[1mENV CLAUDE_ENV_FILE=\"{env_sh}\"\x1b[0m");
830    }
831    eprintln!();
832}
833
834pub fn remove_lean_ctx_block(content: &str) -> String {
835    if content.contains("# lean-ctx shell hook — end") {
836        return remove_lean_ctx_block_by_marker(content);
837    }
838    remove_lean_ctx_block_legacy(content)
839}
840
841fn remove_lean_ctx_block_by_marker(content: &str) -> String {
842    let mut result = String::new();
843    let mut in_block = false;
844
845    for line in content.lines() {
846        if !in_block && line.contains("lean-ctx shell hook") && !line.contains("end") {
847            in_block = true;
848            continue;
849        }
850        if in_block {
851            if line.trim() == "# lean-ctx shell hook — end" {
852                in_block = false;
853            }
854            continue;
855        }
856        result.push_str(line);
857        result.push('\n');
858    }
859    result
860}
861
862fn remove_lean_ctx_block_legacy(content: &str) -> String {
863    let mut result = String::new();
864    let mut in_block = false;
865
866    for line in content.lines() {
867        if line.contains("lean-ctx shell hook") {
868            in_block = true;
869            continue;
870        }
871        if in_block {
872            if line.trim() == "fi" || line.trim() == "end" || line.trim().is_empty() {
873                if line.trim() == "fi" || line.trim() == "end" {
874                    in_block = false;
875                }
876                continue;
877            }
878            if !line.starts_with("alias ") && !line.starts_with('\t') && !line.starts_with("if ") {
879                in_block = false;
880                result.push_str(line);
881                result.push('\n');
882            }
883            continue;
884        }
885        result.push_str(line);
886        result.push('\n');
887    }
888    result
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    #[test]
896    fn test_remove_lean_ctx_block_posix() {
897        let input = r#"# existing config
898export PATH="$HOME/bin:$PATH"
899
900# lean-ctx shell hook — transparent CLI compression (95+ patterns)
901if [ -z "$LEAN_CTX_ACTIVE" ]; then
902alias git='lean-ctx -c git'
903alias npm='lean-ctx -c npm'
904fi
905
906# other stuff
907export EDITOR=vim
908"#;
909        let result = remove_lean_ctx_block(input);
910        assert!(!result.contains("lean-ctx"), "block should be removed");
911        assert!(result.contains("export PATH"), "other content preserved");
912        assert!(
913            result.contains("export EDITOR"),
914            "trailing content preserved"
915        );
916    }
917
918    #[test]
919    fn test_remove_lean_ctx_block_fish() {
920        let input = "# other fish config\nset -x FOO bar\n\n# lean-ctx shell hook — transparent CLI compression (95+ patterns)\nif not set -q LEAN_CTX_ACTIVE\n\talias git 'lean-ctx -c git'\n\talias npm 'lean-ctx -c npm'\nend\n\n# more config\nset -x BAZ qux\n";
921        let result = remove_lean_ctx_block(input);
922        assert!(!result.contains("lean-ctx"), "block should be removed");
923        assert!(result.contains("set -x FOO"), "other content preserved");
924        assert!(result.contains("set -x BAZ"), "trailing content preserved");
925    }
926
927    #[test]
928    fn test_remove_lean_ctx_block_ps() {
929        let input = "# PowerShell profile\n$env:FOO = 'bar'\n\n# lean-ctx shell hook — transparent CLI compression (95+ patterns)\nif (-not $env:LEAN_CTX_ACTIVE) {\n  $LeanCtxBin = \"C:\\\\bin\\\\lean-ctx.exe\"\n  function git { & $LeanCtxBin -c \"git $($args -join ' ')\" }\n}\n\n# other stuff\n$env:EDITOR = 'vim'\n";
930        let result = remove_lean_ctx_block_ps(input);
931        assert!(
932            !result.contains("lean-ctx shell hook"),
933            "block should be removed"
934        );
935        assert!(result.contains("$env:FOO"), "other content preserved");
936        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
937    }
938
939    #[test]
940    fn test_remove_lean_ctx_block_ps_nested() {
941        let input = "# PowerShell profile\n$env:FOO = 'bar'\n\n# lean-ctx shell hook — transparent CLI compression (95+ patterns)\nif (-not $env:LEAN_CTX_ACTIVE) {\n  $LeanCtxBin = \"lean-ctx\"\n  function _lc {\n    & $LeanCtxBin -c \"$($args -join ' ')\"\n  }\n  if (Get-Command lean-ctx -ErrorAction SilentlyContinue) {\n    function git { _lc git @args }\n    foreach ($c in @('npm','pnpm')) {\n      if ($a) {\n        Set-Variable -Name \"_lc_$c\" -Value $a.Source -Scope Script\n      }\n    }\n  }\n}\n\n# other stuff\n$env:EDITOR = 'vim'\n";
942        let result = remove_lean_ctx_block_ps(input);
943        assert!(
944            !result.contains("lean-ctx shell hook"),
945            "block should be removed"
946        );
947        assert!(!result.contains("_lc"), "function should be removed");
948        assert!(result.contains("$env:FOO"), "other content preserved");
949        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
950    }
951
952    #[test]
953    fn test_remove_block_no_lean_ctx() {
954        let input = "# normal bashrc\nexport PATH=\"$HOME/bin:$PATH\"\n";
955        let result = remove_lean_ctx_block(input);
956        assert!(result.contains("export PATH"), "content unchanged");
957    }
958
959    #[test]
960    fn test_bash_hook_contains_pipe_guard_and_agent_bypass() {
961        let output = generate_hook_posix("/usr/local/bin/lean-ctx");
962        assert!(
963            output.contains("! -t 1"),
964            "bash/zsh hook must contain pipe guard [ ! -t 1 ]"
965        );
966        assert!(
967            output.contains("lean_ctx_is_agent"),
968            "bash/zsh hook must have agent-aware bypass"
969        );
970        assert!(
971            output.contains("CODEX_CLI_SESSION"),
972            "agent check must include CODEX_CLI_SESSION"
973        );
974    }
975
976    #[test]
977    fn test_lc_uses_track_mode_by_default() {
978        let output = generate_hook_posix("/usr/local/bin/lean-ctx");
979        assert!(
980            output.contains("'/usr/local/bin/lean-ctx' -t \"$@\""),
981            "lean_ctx_track must use -t (track mode)"
982        );
983        assert!(
984            output.contains("'/usr/local/bin/lean-ctx' -c \"$@\""),
985            "lean_ctx_compress must use -c (compress mode)"
986        );
987        assert!(output.contains("alias \"$_lc_cmd\"='lean_ctx_track '\"$_lc_cmd\""));
988        assert!(output.contains("alias \"$_lc_cmd\"='lean_ctx_compress '\"$_lc_cmd\""));
989    }
990
991    /// #1898: agent harnesses (Claude Code's Bash tool) snapshot the shell and
992    /// replay aliases plus only the functions whose names do not start with `_`.
993    /// Every alias target — and every function those call — must survive that.
994    #[test]
995    fn posix_hook_alias_targets_survive_underscore_function_stripping() {
996        let output = generate_hook_posix("/usr/local/bin/lean-ctx");
997        for line in output.lines().map(str::trim) {
998            if let Some(rest) = line.strip_prefix("alias ") {
999                let target = rest.split_once('=').map_or("", |(_, t)| t);
1000                let target = target.trim_start_matches(['\'', '"']);
1001                assert!(
1002                    !target.starts_with('_'),
1003                    "alias must not target an underscore function: {line}"
1004                );
1005            }
1006        }
1007        for kept in ["lean_ctx_track", "lean_ctx_compress", "lean-ctx-on"] {
1008            let start = output
1009                .find(&format!("\n{kept}() {{"))
1010                .unwrap_or_else(|| panic!("{kept} must be defined"));
1011            let body = &output[start..start + output[start..].find("\n}\n").unwrap()];
1012            for called in ["_lc ", "_lc_is_agent", "_lean_ctx_notice", "_lc_compress "] {
1013                assert!(
1014                    !body.contains(called),
1015                    "{kept} must not call stripped function {called}"
1016                );
1017            }
1018        }
1019    }
1020
1021    /// End-to-end replay of #1898 in a real bash: source the hook, drop every
1022    /// `_`-prefixed function exactly like a Claude Code shell snapshot does,
1023    /// then run an aliased command. Before the fix this printed
1024    /// `_lc: command not found`.
1025    #[cfg(unix)]
1026    #[test]
1027    fn posix_hook_aliases_work_after_snapshot_style_replay() {
1028        use std::os::unix::fs::PermissionsExt;
1029        if std::process::Command::new("bash")
1030            .arg("--version")
1031            .output()
1032            .is_err()
1033        {
1034            return;
1035        }
1036        let dir = tempfile::tempdir().unwrap();
1037        let bin = dir.path().join("lean-ctx");
1038        std::fs::write(&bin, "#!/bin/sh\necho \"lean-ctx:$*\"\n").unwrap();
1039        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
1040        let hook = dir.path().join("hook.sh");
1041        std::fs::write(&hook, generate_hook_posix(&bin.to_string_lossy())).unwrap();
1042        let script = dir.path().join("replay.sh");
1043        std::fs::write(
1044            &script,
1045            format!(
1046                "shopt -s expand_aliases\n\
1047                 . '{hook}'\n\
1048                 lean-ctx-on\n\
1049                 for f in $(compgen -A function); do\n\
1050                 case \"$f\" in _*) unset -f \"$f\" ;; esac\n\
1051                 done\n\
1052                 git status --short\n",
1053                hook = hook.display()
1054            ),
1055        )
1056        .unwrap();
1057        let out = std::process::Command::new("bash")
1058            .arg(&script)
1059            .env("LEAN_CTX_AGENT", "1")
1060            .env_remove("LEAN_CTX_DISABLED")
1061            .env_remove("LEAN_CTX_ACTIVE")
1062            .env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
1063            .output()
1064            .unwrap();
1065        let stdout = String::from_utf8_lossy(&out.stdout);
1066        let stderr = String::from_utf8_lossy(&out.stderr);
1067        assert!(
1068            !stderr.contains("command not found"),
1069            "aliased command broke after snapshot replay: {stderr}"
1070        );
1071        assert!(
1072            stdout.contains("lean-ctx:-t git status --short"),
1073            "alias must route through lean-ctx: stdout={stdout} stderr={stderr}"
1074        );
1075    }
1076
1077    /// #1971: after `lean-ctx-off`, `lean-ctx-status` still said ON, because
1078    /// it only checked that `LEAN_CTX_ENABLED` was set — and off sets it to 0.
1079    #[cfg(unix)]
1080    #[test]
1081    fn posix_status_reports_off_after_lean_ctx_off() {
1082        if std::process::Command::new("bash")
1083            .arg("--version")
1084            .output()
1085            .is_err()
1086        {
1087            return;
1088        }
1089        let dir = tempfile::tempdir().unwrap();
1090        let hook = dir.path().join("hook.sh");
1091        std::fs::write(&hook, generate_hook_posix("lean-ctx")).unwrap();
1092        let out = std::process::Command::new("bash")
1093            .arg("-c")
1094            .arg(format!(
1095                ". '{}'\n\
1096                 lean-ctx-on; lean-ctx-status; echo \"on=$?\"\n\
1097                 lean-ctx-off; lean-ctx-status; echo \"off=$?\"\n",
1098                hook.display()
1099            ))
1100            .env_remove("LEAN_CTX_DISABLED")
1101            .output()
1102            .unwrap();
1103        let stdout = String::from_utf8_lossy(&out.stdout);
1104        assert!(stdout.contains("on=0"), "status after on: {stdout}");
1105        assert!(stdout.contains("off=1"), "status after off: {stdout}");
1106    }
1107
1108    #[test]
1109    fn test_posix_shell_has_lean_ctx_mode() {
1110        let alias_list = crate::rewrite_registry::shell_alias_list();
1111        let aliases = r#"
1112lean-ctx-mode() {{
1113    case "${{1:-}}" in
1114        compress) echo compress ;;
1115        track) echo track ;;
1116        off) echo off ;;
1117    esac
1118}}
1119"#
1120        .to_string();
1121        assert!(
1122            aliases.contains("lean-ctx-mode()"),
1123            "lean-ctx-mode function must exist"
1124        );
1125        assert!(
1126            aliases.contains("compress"),
1127            "compress mode must be available"
1128        );
1129        assert!(aliases.contains("track"), "track mode must be available");
1130        let _ = alias_list;
1131    }
1132
1133    #[test]
1134    fn test_fish_hook_contains_pipe_guard_and_agent_bypass() {
1135        let output = generate_hook_fish("/usr/local/bin/lean-ctx");
1136        assert!(
1137            output.contains("isatty stdout"),
1138            "fish hook must contain pipe guard (isatty stdout)"
1139        );
1140        assert!(
1141            output.contains("_lc_is_agent"),
1142            "fish hook must have agent-aware bypass"
1143        );
1144    }
1145
1146    #[test]
1147    fn test_powershell_hook_contains_pipe_guard() {
1148        let hook = "function _lc { if ($env:LEAN_CTX_DISABLED -or [Console]::IsOutputRedirected) { & @args; return } }";
1149        assert!(
1150            hook.contains("IsOutputRedirected"),
1151            "PowerShell hook must contain pipe guard ([Console]::IsOutputRedirected)"
1152        );
1153    }
1154
1155    #[test]
1156    fn powershell_hook_binary_is_native_not_msys() {
1157        // #518: PowerShell/pwsh execute the path via the `&` call operator and
1158        // cannot run an MSYS `/c/...` path — they must get the native binary.
1159        let win = "C:/Users/Dawid/.cargo/bin/lean-ctx.exe";
1160        assert_eq!(hook_binary_for_shell("powershell", win), win);
1161        assert_eq!(hook_binary_for_shell("pwsh", win), win);
1162        assert!(!hook_binary_for_shell("powershell", win).contains("/c/"));
1163    }
1164
1165    #[test]
1166    fn posix_hook_binary_keeps_msys_form_on_windows_drive() {
1167        // bash/zsh/fish source the hook from a POSIX shell, so a Windows drive
1168        // path is converted to the MSYS `/c/...` form for them.
1169        let win = "C:/Users/Dawid/.cargo/bin/lean-ctx.exe";
1170        let msys = "/c/Users/Dawid/.cargo/bin/lean-ctx.exe";
1171        assert_eq!(hook_binary_for_shell("bash", win), msys);
1172        assert_eq!(hook_binary_for_shell("zsh", win), msys);
1173        assert_eq!(hook_binary_for_shell("fish", win), msys);
1174    }
1175
1176    #[test]
1177    fn test_remove_lean_ctx_block_new_format_with_end_marker() {
1178        let input = r#"# existing config
1179export PATH="$HOME/bin:$PATH"
1180
1181# lean-ctx shell hook — transparent CLI compression (95+ patterns)
1182_lean_ctx_cmds=(git npm pnpm)
1183
1184lean-ctx-on() {
1185    for _lc_cmd in "${_lean_ctx_cmds[@]}"; do
1186        alias "$_lc_cmd"='lean-ctx -c '"$_lc_cmd"
1187    done
1188    export LEAN_CTX_ENABLED=1
1189    [ -t 1 ] && echo "lean-ctx: ON"
1190}
1191
1192lean-ctx-off() {
1193    export LEAN_CTX_ENABLED=0
1194    [ -t 1 ] && echo "lean-ctx: OFF"
1195}
1196
1197if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ "${LEAN_CTX_ENABLED:-1}" != "0" ]; then
1198    lean-ctx-on
1199fi
1200# lean-ctx shell hook — end
1201
1202# other stuff
1203export EDITOR=vim
1204"#;
1205        let result = remove_lean_ctx_block(input);
1206        assert!(!result.contains("lean-ctx-on"), "block should be removed");
1207        assert!(!result.contains("lean-ctx shell hook"), "marker removed");
1208        assert!(result.contains("export PATH"), "other content preserved");
1209        assert!(
1210            result.contains("export EDITOR"),
1211            "trailing content preserved"
1212        );
1213    }
1214
1215    #[test]
1216    fn env_sh_for_containers_includes_self_heal() {
1217        let _g = crate::core::data_dir::test_env_lock();
1218        let tmp = tempfile::tempdir().expect("tempdir");
1219        // env.sh is a config artifact (#408) → written under config_dir().
1220        let config_dir = tmp.path().join("config");
1221        std::fs::create_dir_all(&config_dir).expect("mkdir config");
1222        crate::test_env::set_var("LEAN_CTX_CONFIG_DIR", &config_dir);
1223
1224        write_env_sh_for_containers("alias git='lean-ctx -c git'\n");
1225        let env_sh = config_dir.join("env.sh");
1226        let content = std::fs::read_to_string(&env_sh).expect("env.sh exists");
1227        if !cfg!(windows)
1228            && let Ok(mut bash) = std::process::Command::new("bash")
1229                .arg("-n")
1230                .arg(&env_sh)
1231                .spawn()
1232        {
1233            let ok = bash.wait().is_ok_and(|s| s.success());
1234            assert!(ok, "generated env.sh must be valid bash");
1235        }
1236        assert!(
1237            content.contains(r#"_lc()          { command "$@"; }"#),
1238            "env.sh must contain _lc passthrough stub for non-interactive shells"
1239        );
1240        assert!(
1241            content.contains(r#"_lc_compress() { command "$@"; }"#),
1242            "env.sh must contain _lc_compress passthrough stub"
1243        );
1244        assert!(content.contains("lean-ctx docker self-heal"));
1245        assert!(content.contains("claude mcp list"));
1246        assert!(content.contains("lean-ctx init --agent claude"));
1247        assert!(
1248            content.contains("_LEAN_CTX_HEAL"),
1249            "env.sh must guard against recursive self-heal"
1250        );
1251        assert!(
1252            content.contains("LEAN_CTX_ACTIVE"),
1253            "env.sh must check LEAN_CTX_ACTIVE to prevent re-entry"
1254        );
1255        assert!(
1256            content.contains("/.dockerenv"),
1257            "env.sh self-heal must be gated to container environments"
1258        );
1259        // GL #623/#627: the self-heal must never create or read ~/.lean-ctx,
1260        // which would re-collapse a committed XDG layout. heal_ts → XDG state,
1261        // lock count → XDG data.
1262        assert!(
1263            !content.contains("$HOME/.lean-ctx") && !content.contains("${HOME}/.lean-ctx"),
1264            "self-heal must not touch ~/.lean-ctx (GL #623)"
1265        );
1266        assert!(
1267            content.contains("${XDG_STATE_HOME:-$HOME/.local/state}/lean-ctx"),
1268            "heal_ts must live under the XDG state dir"
1269        );
1270        assert!(
1271            content.contains("${XDG_DATA_HOME:-$HOME/.local/share}/lean-ctx/locks"),
1272            "lock count must read the XDG data lock dir"
1273        );
1274
1275        crate::test_env::remove_var("LEAN_CTX_CONFIG_DIR");
1276    }
1277
1278    #[cfg(unix)]
1279    #[test]
1280    fn bash_login_profile_sources_bashrc_idempotently() {
1281        let _g = crate::core::data_dir::test_env_lock();
1282        let tmp = tempfile::tempdir().expect("tempdir");
1283        let home = tmp.path();
1284        let prev = std::env::var_os("HOME");
1285        crate::test_env::set_var("HOME", home);
1286
1287        std::fs::write(home.join(".bashrc"), "# bashrc\n").expect("write .bashrc");
1288        // No login profile yet → the function must create ~/.bash_profile.
1289
1290        ensure_bash_login_sources_bashrc();
1291        let profile = home.join(".bash_profile");
1292        let first = std::fs::read_to_string(&profile).expect(".bash_profile created");
1293        assert!(
1294            first.contains(". \"$HOME/.bashrc\""),
1295            "login profile must source ~/.bashrc: {first}"
1296        );
1297        let markers = first.matches("load ~/.bashrc in login shells").count();
1298
1299        // Second run is a no-op: it already sources ~/.bashrc.
1300        ensure_bash_login_sources_bashrc();
1301        let second = std::fs::read_to_string(&profile).expect("read profile");
1302        assert_eq!(
1303            second.matches("load ~/.bashrc in login shells").count(),
1304            markers,
1305            "snippet must not be duplicated on re-run"
1306        );
1307
1308        match prev {
1309            Some(v) => crate::test_env::set_var("HOME", v),
1310            None => crate::test_env::remove_var("HOME"),
1311        }
1312    }
1313
1314    #[test]
1315    fn test_source_line_posix() {
1316        let line = source_line_posix("zsh");
1317        assert!(line.contains("shell-hook.zsh"));
1318        assert!(line.contains("[ -f"));
1319    }
1320
1321    #[test]
1322    fn test_source_line_fish() {
1323        let line = source_line_fish();
1324        assert!(line.contains("shell-hook.fish"));
1325        assert!(line.contains("source"));
1326    }
1327
1328    #[test]
1329    fn test_source_line_powershell() {
1330        let line = source_line_powershell();
1331        assert!(line.contains("shell-hook.ps1"));
1332        assert!(line.contains("Test-Path"));
1333    }
1334}