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