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_comp() {{
589        shift words
590        (( CURRENT-- ))
591        _normal
592    }}
593    compdef _lean_ctx_comp _lc 2>/dev/null
594    compdef _lean_ctx_comp _lc_compress 2>/dev/null
595fi
596
597_lean_ctx_should_activate() {{
598    [ -z "${{LEAN_CTX_ACTIVE:-}}" ] && [ -z "${{LEAN_CTX_DISABLED:-}}" ] && [ "${{LEAN_CTX_ENABLED:-1}}" != "0" ] || return 1
599    case "${{LEAN_CTX_SHELL_ACTIVATION:-{baked_default}}}" in
600        off|none|manual) return 1 ;;
601        agents-only|agents_only|agentsonly)
602            _lc_is_agent ;;
603        *) return 0 ;;
604    esac
605}}
606
607if _lean_ctx_should_activate; then
608    command -v lean-ctx >/dev/null 2>&1 && lean-ctx-on
609fi
610"#
611    )
612}
613
614pub fn init_posix(is_zsh: bool, binary: &str) {
615    let rc_file = if is_zsh {
616        dirs::home_dir()
617            .map(|h| h.join(".zshrc"))
618            .unwrap_or_default()
619    } else {
620        dirs::home_dir()
621            .map(|h| h.join(".bashrc"))
622            .unwrap_or_default()
623    };
624
625    let shell_ext = if is_zsh { "zsh" } else { "bash" };
626    let hook_content = generate_hook_posix(binary);
627
628    if let Some(hook_path) = write_hook_file(&format!("shell-hook.{shell_ext}"), &hook_content) {
629        upsert_source_line(&rc_file, &source_line_posix(shell_ext));
630
631        // Bash login shells don't read ~/.bashrc — make sure they pick it up so the hook
632        // (and the installer's PATH export) take effect in Terminal.app / IDE login shells.
633        if !is_zsh {
634            ensure_bash_login_sources_bashrc();
635        }
636
637        qprintln!("  Binary: {binary}");
638
639        write_env_sh_for_containers(&hook_content);
640        write_lc_path_shims(binary);
641        print_docker_env_hints(is_zsh);
642
643        let _ = hook_path;
644    }
645}
646
647/// Bash login shells (macOS Terminal.app, many IDE terminals, `bash -l`) read
648/// `~/.bash_profile` (or `~/.bash_login` / `~/.profile`) and never `~/.bashrc`. Because we
649/// install the hook — and the installer adds `~/.local/bin` to PATH — into `~/.bashrc`, a login
650/// shell would otherwise see neither. Ensure the login profile sources `~/.bashrc`, exactly as
651/// the Debian/Ubuntu default `.profile` does. Idempotent; zsh is unaffected (it always reads
652/// `~/.zshrc`), so this is only wired in for bash.
653fn ensure_bash_login_sources_bashrc() {
654    let Some(home) = dirs::home_dir() else {
655        return;
656    };
657
658    // Bash reads only the FIRST existing of these on login; target that one, else create
659    // ~/.bash_profile. (~/.bashrc is never a login file, so it's not a candidate.)
660    let target = [".bash_profile", ".bash_login", ".profile"]
661        .iter()
662        .map(|f| home.join(f))
663        .find(|p| p.exists())
664        .unwrap_or_else(|| home.join(".bash_profile"));
665
666    // Already sourcing ~/.bashrc (our snippet or the user's own)? Nothing to do.
667    if let Ok(existing) = std::fs::read_to_string(&target) {
668        let sources_bashrc = existing
669            .lines()
670            .any(|l| !l.trim_start().starts_with('#') && l.contains(".bashrc"));
671        if sources_bashrc {
672            return;
673        }
674    }
675
676    let snippet = "\n# lean-ctx: load ~/.bashrc in login shells (e.g. macOS Terminal) — begin\n\
677         if [ -f \"$HOME/.bashrc\" ]; then . \"$HOME/.bashrc\"; fi\n\
678         # lean-ctx: load ~/.bashrc in login shells (e.g. macOS Terminal) — end\n";
679
680    backup_shell_config(&target);
681    match std::fs::OpenOptions::new()
682        .append(true)
683        .create(true)
684        .open(&target)
685    {
686        Ok(mut f) => {
687            use std::io::Write;
688            if f.write_all(snippet.as_bytes()).is_ok() {
689                qprintln!("  Login shell: {} now sources ~/.bashrc", target.display());
690            }
691        }
692        Err(e) => {
693            tracing::warn!("could not update {}: {e}", target.display());
694        }
695    }
696}
697
698pub fn write_env_sh_for_containers(aliases: &str) {
699    // env.sh is a config artifact (sourced via BASH_ENV/CLAUDE_ENV_FILE) → config_dir (#408).
700    let env_sh = match crate::core::paths::config_dir() {
701        Ok(d) => d.join("env.sh"),
702        Err(_) => return,
703    };
704    if let Some(parent) = env_sh.parent() {
705        let _ = std::fs::create_dir_all(parent);
706    }
707    let sanitized_aliases = crate::core::sanitize::neutralize_shell_content(aliases);
708    let mut content = String::from(
709        r#"# lean-ctx: passthrough stubs for non-interactive subshells (fixes #255).
710# These ensure _lc/_lc_compress exist so inherited aliases don't break.
711# The full hook definitions override these when the interactive shell loads.
712_lc()          { command "$@"; }
713_lc_compress() { command "$@"; }
714
715"#,
716    );
717    content.push_str(&sanitized_aliases);
718    content.push_str(
719        r#"
720
721# lean-ctx docker self-heal: re-inject Claude MCP config if Claude overwrote ~/.claude.json
722# Guards: container-only + no recursion + no re-entry via BASH_ENV + 60s cooldown + PID-lock
723if [ -f /.dockerenv ] || grep -qsE '/docker/|/lxc/' /proc/1/cgroup 2>/dev/null; then
724  if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ -z "${_LEAN_CTX_HEAL:-}" ]; then
725    # XDG-only paths (GL #623): never touch ~/.lean-ctx, which would re-collapse
726    # a committed XDG layout. heal_ts is STATE, locks live in the DATA dir
727    # (matches process_guard::lock_dir defaults).
728    _LEAN_CTX_STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/lean-ctx"
729    _LEAN_CTX_HEAL_TS="${_LEAN_CTX_STATE_DIR}/.heal_ts"
730    _LEAN_CTX_HEAL_COOLDOWN=60
731    _lean_ctx_heal_needed=1
732    if [ -f "$_LEAN_CTX_HEAL_TS" ]; then
733      _last_heal=$(cat "$_LEAN_CTX_HEAL_TS" 2>/dev/null || echo 0)
734      _now=$(date +%s 2>/dev/null || echo 0)
735      if [ $(( _now - _last_heal )) -lt $_LEAN_CTX_HEAL_COOLDOWN ]; then
736        _lean_ctx_heal_needed=0
737      fi
738    fi
739    _lean_ctx_lock_count=0
740    for _lf in "${XDG_DATA_HOME:-$HOME/.local/share}/lean-ctx/locks"/slot-*.lock; do
741      [ -f "$_lf" ] && _lean_ctx_lock_count=$(( _lean_ctx_lock_count + 1 ))
742    done
743    if [ "$_lean_ctx_heal_needed" = "1" ] && [ "$_lean_ctx_lock_count" -lt 4 ]; then
744      export _LEAN_CTX_HEAL=1
745      if command -v claude >/dev/null 2>&1 && command -v lean-ctx >/dev/null 2>&1; then
746        if ! claude mcp list 2>/dev/null | grep -q "lean-ctx"; then
747          LEAN_CTX_ACTIVE=1 LEAN_CTX_QUIET=1 lean-ctx init --agent claude >/dev/null 2>&1
748          mkdir -p "$_LEAN_CTX_STATE_DIR" 2>/dev/null
749          date +%s > "$_LEAN_CTX_HEAL_TS" 2>/dev/null
750        fi
751      fi
752    fi
753  fi
754fi
755"#,
756    );
757    match std::fs::write(&env_sh, content) {
758        Ok(()) => {
759            // Keep JSON-mode stdout clean; non-quiet hints go to stderr.
760            if !super::quiet_enabled() {
761                eprintln!("  env.sh: {}", env_sh.display());
762            }
763        }
764        Err(e) => tracing::warn!("could not write {}: {e}", env_sh.display()),
765    }
766}
767
768/// Directory for the `_lc`/`_lc_compress` PATH shims: the directory of the
769/// running `lean-ctx` executable, which is necessarily on `PATH` (the hook
770/// resolves the binary from there).
771fn lc_shim_dir() -> Option<std::path::PathBuf> {
772    std::env::current_exe()
773        .ok()
774        .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
775}
776
777/// Body of a `_lc`/`_lc_compress` PATH shim. Mirrors the hook's shell function
778/// of the same name: honor the disable switches, pass through raw for a
779/// non-TTY non-agent shell, otherwise route through the binary and fall back to
780/// running the command directly if the binary itself cannot exec (126/127).
781fn shim_script(name: &str, binary: &str, flag: &str) -> String {
782    format!(
783        "#!/bin/sh\n\
784         # lean-ctx PATH fallback for the `{name}` shell function -- DO NOT EDIT.\n\
785         # Shell resolves alias -> function -> PATH, so the hook's shell function\n\
786         # shadows this whenever it is loaded (identical behavior there). This runs\n\
787         # only where the function is absent: non-interactive subshells, scripts,\n\
788         # xargs/find -exec, a pipeline's outer shell, and agent harnesses that\n\
789         # snapshot+replay the shell and drop the function but keep the aliases\n\
790         # that call it. Without it those contexts fail `{name}: command not found`.\n\
791         if [ -n \"${{LEAN_CTX_DISABLED:-}}\" ] || [ -n \"${{LEAN_CTX_NO_HOOK:-}}\" ]; then\n\
792         \texec \"$@\"\n\
793         fi\n\
794         if [ ! -t 1 ] && [ -z \"${{LEAN_CTX_AGENT:-}}\" ] && [ -z \"${{CURSOR_AGENT:-}}\" ] && [ -z \"${{CODEX_CLI_SESSION:-}}\" ] \\\n\
795         \t&& [ -z \"${{CLAUDECODE:-}}\" ] && [ -z \"${{CODEBUDDY:-}}\" ] && [ -z \"${{GEMINI_SESSION:-}}\" ]; then\n\
796         \texec \"$@\"\n\
797         fi\n\
798         '{binary}' {flag} \"$@\"\n\
799         _lc_rc=$?\n\
800         if [ \"$_lc_rc\" -eq 127 ] || [ \"$_lc_rc\" -eq 126 ]; then\n\
801         \texec \"$@\"\n\
802         fi\n\
803         exit \"$_lc_rc\"\n"
804    )
805}
806
807/// Write the `_lc`/`_lc_compress` PATH shims into `dir` (executable on Unix).
808fn write_lc_path_shims_in(dir: &std::path::Path, binary: &str) {
809    for (name, flag) in [("_lc", "-t"), ("_lc_compress", "-c")] {
810        let path = dir.join(name);
811        if let Err(e) = std::fs::write(&path, shim_script(name, binary, flag)) {
812            tracing::warn!("could not write shim {}: {e}", path.display());
813            continue;
814        }
815        #[cfg(unix)]
816        {
817            use std::os::unix::fs::PermissionsExt;
818            let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755));
819        }
820    }
821}
822
823/// Install `_lc`/`_lc_compress` fallback executables on `PATH` so aliases never
824/// break when the shell function is unavailable (see [`shim_script`]).
825/// Self-contained: depends on no env wiring (BASH_ENV/env.sh) or snapshot
826/// fidelity, and the same-named function shadows it where the hook is loaded.
827fn write_lc_path_shims(binary: &str) {
828    if let Some(dir) = lc_shim_dir() {
829        write_lc_path_shims_in(&dir, binary);
830    }
831}
832
833fn print_docker_env_hints(is_zsh: bool) {
834    if is_zsh || !crate::shell::is_container() {
835        return;
836    }
837    let env_sh = crate::core::paths::config_dir().map_or_else(
838        |_| "/root/.config/lean-ctx/env.sh".to_string(),
839        |d| d.join("env.sh").to_string_lossy().to_string(),
840    );
841
842    let has_bash_env = std::env::var("BASH_ENV").is_ok();
843    let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
844
845    if has_bash_env && has_claude_env {
846        return;
847    }
848
849    eprintln!();
850    eprintln!("  \x1b[33m⚠  Docker detected — environment hints:\x1b[0m");
851
852    if !has_bash_env {
853        eprintln!("  For generic bash -c usage (non-interactive shells):");
854        eprintln!("    \x1b[1mENV BASH_ENV=\"{env_sh}\"\x1b[0m");
855    }
856    if !has_claude_env {
857        eprintln!("  For Claude Code (sources before each command):");
858        eprintln!("    \x1b[1mENV CLAUDE_ENV_FILE=\"{env_sh}\"\x1b[0m");
859    }
860    eprintln!();
861}
862
863pub fn remove_lean_ctx_block(content: &str) -> String {
864    if content.contains("# lean-ctx shell hook — end") {
865        return remove_lean_ctx_block_by_marker(content);
866    }
867    remove_lean_ctx_block_legacy(content)
868}
869
870fn remove_lean_ctx_block_by_marker(content: &str) -> String {
871    let mut result = String::new();
872    let mut in_block = false;
873
874    for line in content.lines() {
875        if !in_block && line.contains("lean-ctx shell hook") && !line.contains("end") {
876            in_block = true;
877            continue;
878        }
879        if in_block {
880            if line.trim() == "# lean-ctx shell hook — end" {
881                in_block = false;
882            }
883            continue;
884        }
885        result.push_str(line);
886        result.push('\n');
887    }
888    result
889}
890
891fn remove_lean_ctx_block_legacy(content: &str) -> String {
892    let mut result = String::new();
893    let mut in_block = false;
894
895    for line in content.lines() {
896        if line.contains("lean-ctx shell hook") {
897            in_block = true;
898            continue;
899        }
900        if in_block {
901            if line.trim() == "fi" || line.trim() == "end" || line.trim().is_empty() {
902                if line.trim() == "fi" || line.trim() == "end" {
903                    in_block = false;
904                }
905                continue;
906            }
907            if !line.starts_with("alias ") && !line.starts_with('\t') && !line.starts_with("if ") {
908                in_block = false;
909                result.push_str(line);
910                result.push('\n');
911            }
912            continue;
913        }
914        result.push_str(line);
915        result.push('\n');
916    }
917    result
918}
919
920#[cfg(test)]
921mod tests {
922    use super::*;
923
924    #[test]
925    fn lc_shim_script_is_self_contained_fallback() {
926        let s = shim_script("_lc", "/usr/bin/lean-ctx", "-t");
927        assert!(s.starts_with("#!/bin/sh\n"), "needs a shebang: {s}");
928        assert!(s.contains("'/usr/bin/lean-ctx' -t \"$@\""), "{s}");
929        assert!(s.contains("exec \"$@\""), "{s}");
930        assert!(s.contains("CLAUDECODE"), "{s}");
931        assert!(s.contains("LEAN_CTX_DISABLED"), "{s}");
932    }
933
934    #[test]
935    fn lc_compress_shim_uses_compress_flag() {
936        let s = shim_script("_lc_compress", "/usr/bin/lean-ctx", "-c");
937        assert!(s.contains("'/usr/bin/lean-ctx' -c \"$@\""), "{s}");
938    }
939
940    #[test]
941    fn write_lc_path_shims_writes_both_executables() {
942        let tmp = tempfile::tempdir().expect("tempdir");
943        write_lc_path_shims_in(tmp.path(), "/usr/bin/lean-ctx");
944        for name in ["_lc", "_lc_compress"] {
945            assert!(tmp.path().join(name).exists(), "missing shim {name}");
946        }
947    }
948
949    #[test]
950    fn test_remove_lean_ctx_block_posix() {
951        let input = r#"# existing config
952export PATH="$HOME/bin:$PATH"
953
954# lean-ctx shell hook — transparent CLI compression (95+ patterns)
955if [ -z "$LEAN_CTX_ACTIVE" ]; then
956alias git='lean-ctx -c git'
957alias npm='lean-ctx -c npm'
958fi
959
960# other stuff
961export EDITOR=vim
962"#;
963        let result = remove_lean_ctx_block(input);
964        assert!(!result.contains("lean-ctx"), "block should be removed");
965        assert!(result.contains("export PATH"), "other content preserved");
966        assert!(
967            result.contains("export EDITOR"),
968            "trailing content preserved"
969        );
970    }
971
972    #[test]
973    fn test_remove_lean_ctx_block_fish() {
974        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";
975        let result = remove_lean_ctx_block(input);
976        assert!(!result.contains("lean-ctx"), "block should be removed");
977        assert!(result.contains("set -x FOO"), "other content preserved");
978        assert!(result.contains("set -x BAZ"), "trailing content preserved");
979    }
980
981    #[test]
982    fn test_remove_lean_ctx_block_ps() {
983        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";
984        let result = remove_lean_ctx_block_ps(input);
985        assert!(
986            !result.contains("lean-ctx shell hook"),
987            "block should be removed"
988        );
989        assert!(result.contains("$env:FOO"), "other content preserved");
990        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
991    }
992
993    #[test]
994    fn test_remove_lean_ctx_block_ps_nested() {
995        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";
996        let result = remove_lean_ctx_block_ps(input);
997        assert!(
998            !result.contains("lean-ctx shell hook"),
999            "block should be removed"
1000        );
1001        assert!(!result.contains("_lc"), "function should be removed");
1002        assert!(result.contains("$env:FOO"), "other content preserved");
1003        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
1004    }
1005
1006    #[test]
1007    fn test_remove_block_no_lean_ctx() {
1008        let input = "# normal bashrc\nexport PATH=\"$HOME/bin:$PATH\"\n";
1009        let result = remove_lean_ctx_block(input);
1010        assert!(result.contains("export PATH"), "content unchanged");
1011    }
1012
1013    #[test]
1014    fn test_bash_hook_contains_pipe_guard_and_agent_bypass() {
1015        let output = generate_hook_posix("/usr/local/bin/lean-ctx");
1016        assert!(
1017            output.contains("! -t 1"),
1018            "bash/zsh hook must contain pipe guard [ ! -t 1 ]"
1019        );
1020        assert!(
1021            output.contains("_lc_is_agent"),
1022            "bash/zsh hook must have agent-aware bypass"
1023        );
1024        assert!(
1025            output.contains("CODEX_CLI_SESSION"),
1026            "agent check must include CODEX_CLI_SESSION"
1027        );
1028    }
1029
1030    #[test]
1031    fn test_lc_uses_track_mode_by_default() {
1032        let binary = "/usr/local/bin/lean-ctx";
1033        let alias_list = crate::rewrite_registry::shell_alias_list();
1034        let aliases = format!(
1035            r#"_lc() {{
1036    '{binary}' -t "$@"
1037}}
1038_lc_compress() {{
1039    '{binary}' -c "$@"
1040}}"#
1041        );
1042        assert!(
1043            aliases.contains("-t \"$@\""),
1044            "_lc must use -t (track mode) by default"
1045        );
1046        assert!(
1047            aliases.contains("-c \"$@\""),
1048            "_lc_compress must use -c (compress mode)"
1049        );
1050        let _ = alias_list;
1051    }
1052
1053    #[test]
1054    fn test_posix_shell_has_lean_ctx_mode() {
1055        let alias_list = crate::rewrite_registry::shell_alias_list();
1056        let aliases = r#"
1057lean-ctx-mode() {{
1058    case "${{1:-}}" in
1059        compress) echo compress ;;
1060        track) echo track ;;
1061        off) echo off ;;
1062    esac
1063}}
1064"#
1065        .to_string();
1066        assert!(
1067            aliases.contains("lean-ctx-mode()"),
1068            "lean-ctx-mode function must exist"
1069        );
1070        assert!(
1071            aliases.contains("compress"),
1072            "compress mode must be available"
1073        );
1074        assert!(aliases.contains("track"), "track mode must be available");
1075        let _ = alias_list;
1076    }
1077
1078    #[test]
1079    fn test_fish_hook_contains_pipe_guard_and_agent_bypass() {
1080        let output = generate_hook_fish("/usr/local/bin/lean-ctx");
1081        assert!(
1082            output.contains("isatty stdout"),
1083            "fish hook must contain pipe guard (isatty stdout)"
1084        );
1085        assert!(
1086            output.contains("_lc_is_agent"),
1087            "fish hook must have agent-aware bypass"
1088        );
1089    }
1090
1091    #[test]
1092    fn test_powershell_hook_contains_pipe_guard() {
1093        let hook = "function _lc { if ($env:LEAN_CTX_DISABLED -or [Console]::IsOutputRedirected) { & @args; return } }";
1094        assert!(
1095            hook.contains("IsOutputRedirected"),
1096            "PowerShell hook must contain pipe guard ([Console]::IsOutputRedirected)"
1097        );
1098    }
1099
1100    #[test]
1101    fn powershell_hook_binary_is_native_not_msys() {
1102        // #518: PowerShell/pwsh execute the path via the `&` call operator and
1103        // cannot run an MSYS `/c/...` path — they must get the native binary.
1104        let win = "C:/Users/Dawid/.cargo/bin/lean-ctx.exe";
1105        assert_eq!(hook_binary_for_shell("powershell", win), win);
1106        assert_eq!(hook_binary_for_shell("pwsh", win), win);
1107        assert!(!hook_binary_for_shell("powershell", win).contains("/c/"));
1108    }
1109
1110    #[test]
1111    fn posix_hook_binary_keeps_msys_form_on_windows_drive() {
1112        // bash/zsh/fish source the hook from a POSIX shell, so a Windows drive
1113        // path is converted to the MSYS `/c/...` form for them.
1114        let win = "C:/Users/Dawid/.cargo/bin/lean-ctx.exe";
1115        let msys = "/c/Users/Dawid/.cargo/bin/lean-ctx.exe";
1116        assert_eq!(hook_binary_for_shell("bash", win), msys);
1117        assert_eq!(hook_binary_for_shell("zsh", win), msys);
1118        assert_eq!(hook_binary_for_shell("fish", win), msys);
1119    }
1120
1121    #[test]
1122    fn test_remove_lean_ctx_block_new_format_with_end_marker() {
1123        let input = r#"# existing config
1124export PATH="$HOME/bin:$PATH"
1125
1126# lean-ctx shell hook — transparent CLI compression (95+ patterns)
1127_lean_ctx_cmds=(git npm pnpm)
1128
1129lean-ctx-on() {
1130    for _lc_cmd in "${_lean_ctx_cmds[@]}"; do
1131        alias "$_lc_cmd"='lean-ctx -c '"$_lc_cmd"
1132    done
1133    export LEAN_CTX_ENABLED=1
1134    [ -t 1 ] && echo "lean-ctx: ON"
1135}
1136
1137lean-ctx-off() {
1138    export LEAN_CTX_ENABLED=0
1139    [ -t 1 ] && echo "lean-ctx: OFF"
1140}
1141
1142if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ "${LEAN_CTX_ENABLED:-1}" != "0" ]; then
1143    lean-ctx-on
1144fi
1145# lean-ctx shell hook — end
1146
1147# other stuff
1148export EDITOR=vim
1149"#;
1150        let result = remove_lean_ctx_block(input);
1151        assert!(!result.contains("lean-ctx-on"), "block should be removed");
1152        assert!(!result.contains("lean-ctx shell hook"), "marker removed");
1153        assert!(result.contains("export PATH"), "other content preserved");
1154        assert!(
1155            result.contains("export EDITOR"),
1156            "trailing content preserved"
1157        );
1158    }
1159
1160    #[test]
1161    fn env_sh_for_containers_includes_self_heal() {
1162        let _g = crate::core::data_dir::test_env_lock();
1163        let tmp = tempfile::tempdir().expect("tempdir");
1164        // env.sh is a config artifact (#408) → written under config_dir().
1165        let config_dir = tmp.path().join("config");
1166        std::fs::create_dir_all(&config_dir).expect("mkdir config");
1167        crate::test_env::set_var("LEAN_CTX_CONFIG_DIR", &config_dir);
1168
1169        write_env_sh_for_containers("alias git='lean-ctx -c git'\n");
1170        let env_sh = config_dir.join("env.sh");
1171        let content = std::fs::read_to_string(&env_sh).expect("env.sh exists");
1172        if !cfg!(windows)
1173            && let Ok(mut bash) = std::process::Command::new("bash")
1174                .arg("-n")
1175                .arg(&env_sh)
1176                .spawn()
1177        {
1178            let ok = bash.wait().is_ok_and(|s| s.success());
1179            assert!(ok, "generated env.sh must be valid bash");
1180        }
1181        assert!(
1182            content.contains(r#"_lc()          { command "$@"; }"#),
1183            "env.sh must contain _lc passthrough stub for non-interactive shells"
1184        );
1185        assert!(
1186            content.contains(r#"_lc_compress() { command "$@"; }"#),
1187            "env.sh must contain _lc_compress passthrough stub"
1188        );
1189        assert!(content.contains("lean-ctx docker self-heal"));
1190        assert!(content.contains("claude mcp list"));
1191        assert!(content.contains("lean-ctx init --agent claude"));
1192        assert!(
1193            content.contains("_LEAN_CTX_HEAL"),
1194            "env.sh must guard against recursive self-heal"
1195        );
1196        assert!(
1197            content.contains("LEAN_CTX_ACTIVE"),
1198            "env.sh must check LEAN_CTX_ACTIVE to prevent re-entry"
1199        );
1200        assert!(
1201            content.contains("/.dockerenv"),
1202            "env.sh self-heal must be gated to container environments"
1203        );
1204        // GL #623/#627: the self-heal must never create or read ~/.lean-ctx,
1205        // which would re-collapse a committed XDG layout. heal_ts → XDG state,
1206        // lock count → XDG data.
1207        assert!(
1208            !content.contains("$HOME/.lean-ctx") && !content.contains("${HOME}/.lean-ctx"),
1209            "self-heal must not touch ~/.lean-ctx (GL #623)"
1210        );
1211        assert!(
1212            content.contains("${XDG_STATE_HOME:-$HOME/.local/state}/lean-ctx"),
1213            "heal_ts must live under the XDG state dir"
1214        );
1215        assert!(
1216            content.contains("${XDG_DATA_HOME:-$HOME/.local/share}/lean-ctx/locks"),
1217            "lock count must read the XDG data lock dir"
1218        );
1219
1220        crate::test_env::remove_var("LEAN_CTX_CONFIG_DIR");
1221    }
1222
1223    #[cfg(unix)]
1224    #[test]
1225    fn bash_login_profile_sources_bashrc_idempotently() {
1226        let _g = crate::core::data_dir::test_env_lock();
1227        let tmp = tempfile::tempdir().expect("tempdir");
1228        let home = tmp.path();
1229        let prev = std::env::var_os("HOME");
1230        crate::test_env::set_var("HOME", home);
1231
1232        std::fs::write(home.join(".bashrc"), "# bashrc\n").expect("write .bashrc");
1233        // No login profile yet → the function must create ~/.bash_profile.
1234
1235        ensure_bash_login_sources_bashrc();
1236        let profile = home.join(".bash_profile");
1237        let first = std::fs::read_to_string(&profile).expect(".bash_profile created");
1238        assert!(
1239            first.contains(". \"$HOME/.bashrc\""),
1240            "login profile must source ~/.bashrc: {first}"
1241        );
1242        let markers = first.matches("load ~/.bashrc in login shells").count();
1243
1244        // Second run is a no-op: it already sources ~/.bashrc.
1245        ensure_bash_login_sources_bashrc();
1246        let second = std::fs::read_to_string(&profile).expect("read profile");
1247        assert_eq!(
1248            second.matches("load ~/.bashrc in login shells").count(),
1249            markers,
1250            "snippet must not be duplicated on re-run"
1251        );
1252
1253        match prev {
1254            Some(v) => crate::test_env::set_var("HOME", v),
1255            None => crate::test_env::remove_var("HOME"),
1256        }
1257    }
1258
1259    #[test]
1260    fn test_source_line_posix() {
1261        let line = source_line_posix("zsh");
1262        assert!(line.contains("shell-hook.zsh"));
1263        assert!(line.contains("[ -f"));
1264    }
1265
1266    #[test]
1267    fn test_source_line_fish() {
1268        let line = source_line_fish();
1269        assert!(line.contains("shell-hook.fish"));
1270        assert!(line.contains("source"));
1271    }
1272
1273    #[test]
1274    fn test_source_line_powershell() {
1275        let line = source_line_powershell();
1276        assert!(line.contains("shell-hook.ps1"));
1277        assert!(line.contains("Test-Path"));
1278    }
1279}