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