Skip to main content

lean_ctx_cli/cli/
shell_init.rs

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