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 = crate::hooks::to_bash_compatible_path(&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
26fn backup_shell_config(path: &std::path::Path) {
27    if !path.exists() {
28        return;
29    }
30    let bak = path.with_extension("lean-ctx.bak");
31    if std::fs::copy(path, &bak).is_ok() {
32        qprintln!(
33            "  Backup: {}",
34            bak.file_name().map_or_else(
35                || bak.display().to_string(),
36                |n| format!("~/{}", n.to_string_lossy())
37            )
38        );
39    }
40}
41
42fn lean_ctx_dir() -> Option<std::path::PathBuf> {
43    crate::core::data_dir::lean_ctx_data_dir().ok()
44}
45
46fn write_hook_file(filename: &str, content: &str) -> Option<std::path::PathBuf> {
47    let dir = lean_ctx_dir()?;
48    let _ = std::fs::create_dir_all(&dir);
49    let path = dir.join(filename);
50    match std::fs::write(&path, content) {
51        Ok(()) => {
52            #[cfg(unix)]
53            {
54                use std::os::unix::fs::PermissionsExt;
55                let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644));
56            }
57            Some(path)
58        }
59        Err(e) => {
60            tracing::error!("Error writing {}: {e}", path.display());
61            None
62        }
63    }
64}
65
66fn resolved_hook_dir_display() -> String {
67    lean_ctx_dir().map_or_else(
68        || "$HOME/.lean-ctx".to_string(),
69        |p| p.to_string_lossy().to_string(),
70    )
71}
72
73fn source_line_posix(shell_ext: &str) -> String {
74    let mut dir = resolved_hook_dir_display();
75    // Git Bash / MSYS expects /c/... style paths in bashrc/zshrc.
76    if cfg!(windows) {
77        dir = crate::hooks::to_bash_compatible_path(&dir);
78    }
79    format!(
80        "# lean-ctx shell hook — begin\n\
81         if [ -f \"{dir}/shell-hook.{shell_ext}\" ]; then\n\
82           . \"{dir}/shell-hook.{shell_ext}\"\n\
83         fi\n\
84         # lean-ctx shell hook — end\n"
85    )
86}
87
88fn source_line_fish() -> String {
89    let mut dir = resolved_hook_dir_display();
90    // Fish on Windows (MSYS) also expects /c/... style paths.
91    if cfg!(windows) {
92        dir = crate::hooks::to_bash_compatible_path(&dir);
93    }
94    format!(
95        "# lean-ctx shell hook — begin\n\
96         if test -f \"{dir}/shell-hook.fish\"\n\
97           source \"{dir}/shell-hook.fish\"\n\
98         end\n\
99         # lean-ctx shell hook — end\n"
100    )
101}
102
103fn source_line_powershell() -> String {
104    let dir = resolved_hook_dir_display();
105    let dir_ps = dir.replace('/', "\\");
106    format!(
107        "# lean-ctx shell hook — begin\n\
108         $leanCtxHook = \"{dir_ps}\\shell-hook.ps1\"\n\
109         if ((Test-Path $leanCtxHook) -and -not [Console]::IsOutputRedirected) {{ . $leanCtxHook }}\n"
110    )
111}
112
113fn upsert_source_line(rc_path: &std::path::Path, source_line: &str) {
114    backup_shell_config(rc_path);
115
116    if let Ok(existing) = std::fs::read_to_string(rc_path) {
117        if existing.contains(source_line.trim()) {
118            return;
119        }
120
121        // Remove any legacy blocks and one-liner source lines, then append our canonical block.
122        let cleaned = remove_lean_ctx_block(&existing);
123        let cleaned = cleaned
124            .lines()
125            .filter(|line| {
126                !line.contains("lean-ctx/shell-hook.")
127                    && !line.contains("lean-ctx\\shell-hook.")
128                    && line.trim() != "lean-ctx shell hook"
129            })
130            .collect::<Vec<_>>()
131            .join("\n");
132        let cleaned = if cleaned.ends_with('\n') {
133            cleaned
134        } else {
135            format!("{cleaned}\n")
136        };
137
138        match std::fs::write(rc_path, format!("{cleaned}{source_line}")) {
139            Ok(()) => {
140                qprintln!("Updated lean-ctx hook in {}", rc_path.display());
141            }
142            Err(e) => {
143                tracing::error!("Error updating {}: {e}", rc_path.display());
144            }
145        }
146        return;
147    }
148
149    match std::fs::OpenOptions::new()
150        .append(true)
151        .create(true)
152        .open(rc_path)
153    {
154        Ok(mut f) => {
155            use std::io::Write;
156            let _ = f.write_all(source_line.as_bytes());
157            qprintln!("Added lean-ctx hook to {}", rc_path.display());
158        }
159        Err(e) => tracing::error!("Error writing {}: {e}", rc_path.display()),
160    }
161}
162
163pub fn generate_hook_powershell(binary: &str) -> String {
164    let config = crate::core::config::Config::load();
165    let activation = config.shell_activation_effective();
166    let baked_default = match activation {
167        crate::core::config::ShellActivation::Always => "always",
168        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
169        crate::core::config::ShellActivation::Off => "off",
170    };
171    let binary_escaped = binary.replace('\\', "\\\\");
172    format!(
173        r#"# lean-ctx shell hook — transparent CLI compression (95+ patterns)
174$_leanCtxActivation = if ($env:LEAN_CTX_SHELL_ACTIVATION) {{ $env:LEAN_CTX_SHELL_ACTIVATION }} else {{ "{baked_default}" }}
175$_leanCtxShouldActivate = $false
176if (-not $env:LEAN_CTX_ACTIVE -and -not $env:LEAN_CTX_DISABLED -and -not $env:LEAN_CTX_NO_HOOK) {{
177  switch ($_leanCtxActivation) {{
178    {{ $_ -in 'off','none','manual' }} {{ $_leanCtxShouldActivate = $false }}
179    {{ $_ -in 'agents-only','agents_only','agentsonly' }} {{
180      $_leanCtxShouldActivate = $env:LEAN_CTX_AGENT -or $env:CLAUDECODE -or $env:CODEX_CLI_SESSION -or $env:GEMINI_SESSION
181    }}
182    default {{ $_leanCtxShouldActivate = $true }}
183  }}
184}}
185if ($_leanCtxShouldActivate) {{
186  $LeanCtxBin = "{binary_escaped}"
187  function _lc {{
188    if ($env:LEAN_CTX_DISABLED -or $env:LEAN_CTX_NO_HOOK -or [Console]::IsOutputRedirected) {{ & @args; return }}
189    & $LeanCtxBin -c @args
190    if ($LASTEXITCODE -eq 127 -or $LASTEXITCODE -eq 126) {{
191      & @args
192    }}
193  }}
194  function lean-ctx-raw {{ $env:LEAN_CTX_RAW = '1'; & @args; Remove-Item Env:LEAN_CTX_RAW -ErrorAction SilentlyContinue }}
195  if (Get-Command lean-ctx -ErrorAction SilentlyContinue) {{
196    function git {{ _lc git @args }}
197    function cargo {{ _lc cargo @args }}
198    function docker {{ _lc docker @args }}
199    function kubectl {{ _lc kubectl @args }}
200    function gh {{ _lc gh @args }}
201    function pip {{ _lc pip @args }}
202    function pip3 {{ _lc pip3 @args }}
203    function ruff {{ _lc ruff @args }}
204    function go {{ _lc go @args }}
205    function curl {{ _lc curl @args }}
206    function wget {{ _lc wget @args }}
207    foreach ($c in @('npm','pnpm','yarn','eslint','prettier','tsc')) {{
208      if (Get-Command $c -CommandType Application -ErrorAction SilentlyContinue) {{
209        New-Item -Path "function:$c" -Value ([scriptblock]::Create("_lc $c @args")) -Force | Out-Null
210      }}
211    }}
212  }}
213}}
214"#
215    )
216}
217
218pub fn init_powershell(binary: &str) {
219    let profile_dir = dirs::home_dir().map(|h| h.join("Documents").join("PowerShell"));
220    let profile_path = if let Some(dir) = profile_dir {
221        let _ = std::fs::create_dir_all(&dir);
222        dir.join("Microsoft.PowerShell_profile.ps1")
223    } else {
224        tracing::error!("Could not resolve PowerShell profile directory");
225        return;
226    };
227
228    let hook_content = generate_hook_powershell(binary);
229
230    if write_hook_file("shell-hook.ps1", &hook_content).is_some() {
231        upsert_source_line(&profile_path, &source_line_powershell());
232        qprintln!("  Binary: {binary}");
233    }
234}
235
236pub fn remove_lean_ctx_block_ps(content: &str) -> String {
237    let mut result = String::new();
238    let mut in_block = false;
239    let mut brace_depth = 0i32;
240
241    for line in content.lines() {
242        if line.contains("lean-ctx shell hook") {
243            in_block = true;
244            continue;
245        }
246        if in_block {
247            brace_depth += line.matches('{').count() as i32;
248            brace_depth -= line.matches('}').count() as i32;
249            if brace_depth <= 0 && (line.trim() == "}" || line.trim().is_empty()) {
250                if line.trim() == "}" {
251                    in_block = false;
252                    brace_depth = 0;
253                }
254                continue;
255            }
256            continue;
257        }
258        result.push_str(line);
259        result.push('\n');
260    }
261    result
262}
263
264pub fn generate_hook_fish(binary: &str) -> String {
265    let config = crate::core::config::Config::load();
266    let activation = config.shell_activation_effective();
267    let baked_default = match activation {
268        crate::core::config::ShellActivation::Always => "always",
269        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
270        crate::core::config::ShellActivation::Off => "off",
271    };
272    let alias_list = crate::rewrite_registry::shell_alias_list();
273    format!(
274        "# lean-ctx shell hook — smart shell mode (track-by-default)\n\
275        set -g _lean_ctx_cmds {alias_list}\n\
276        \n\
277        function _lc_is_agent\n\
278        \tset -q LEAN_CTX_AGENT; or set -q CODEX_CLI_SESSION; or set -q CLAUDECODE; or set -q GEMINI_SESSION\n\
279        end\n\
280        \n\
281        function _lc\n\
282        \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK\n\
283        \t\tcommand $argv\n\
284        \t\treturn\n\
285        \tend\n\
286        \tif not isatty stdout; and not _lc_is_agent\n\
287        \t\tcommand $argv\n\
288        \t\treturn\n\
289        \tend\n\
290        \t'{binary}' -t $argv\n\
291        \tset -l _lc_rc $status\n\
292        \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
293        \t\tcommand $argv\n\
294        \telse\n\
295        \t\treturn $_lc_rc\n\
296        \tend\n\
297        end\n\
298        \n\
299        function _lc_compress\n\
300        \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK\n\
301        \t\tcommand $argv\n\
302        \t\treturn\n\
303        \tend\n\
304        \tif not isatty stdout; and not _lc_is_agent\n\
305        \t\tcommand $argv\n\
306        \t\treturn\n\
307        \tend\n\
308        \t'{binary}' -c $argv\n\
309        \tset -l _lc_rc $status\n\
310        \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
311        \t\tcommand $argv\n\
312        \telse\n\
313        \t\treturn $_lc_rc\n\
314        \tend\n\
315        end\n\
316        \n\
317        function lean-ctx-on\n\
318        \tfor _lc_cmd in $_lean_ctx_cmds\n\
319        \t\talias $_lc_cmd '_lc '$_lc_cmd\n\
320        \tend\n\
321        \talias k '_lc kubectl'\n\
322        \tset -gx LEAN_CTX_ENABLED 1\n\
323        \tisatty stdout; and echo 'lean-ctx: ON (track mode — output unchanged, token savings recorded)'\n\
324        end\n\
325        \n\
326        function lean-ctx-off\n\
327        \tfor _lc_cmd in $_lean_ctx_cmds\n\
328        \t\tfunctions --erase $_lc_cmd 2>/dev/null; true\n\
329        \tend\n\
330        \tfunctions --erase k 2>/dev/null; true\n\
331        \tset -e LEAN_CTX_ENABLED\n\
332        \tisatty stdout; and echo 'lean-ctx: OFF'\n\
333        end\n\
334        \n\
335        function lean-ctx-mode\n\
336        \tswitch $argv[1]\n\
337        \t\tcase compress\n\
338        \t\t\tfor _lc_cmd in $_lean_ctx_cmds\n\
339        \t\t\t\talias $_lc_cmd '_lc_compress '$_lc_cmd\n\
340        \t\t\t\tend\n\
341        \t\t\talias k '_lc_compress kubectl'\n\
342        \t\t\tset -gx LEAN_CTX_ENABLED 1\n\
343        \t\t\tisatty stdout; and echo 'lean-ctx: COMPRESS mode (all output compressed)'\n\
344        \t\tcase track\n\
345        \t\t\tlean-ctx-on\n\
346        \t\tcase off\n\
347        \t\t\tlean-ctx-off\n\
348        \t\tcase '*'\n\
349        \t\t\techo 'Usage: lean-ctx-mode <track|compress|off>'\n\
350        \t\t\techo '  track    — Full output, stats recorded (default)'\n\
351        \t\t\techo '  compress — Compressed output for all commands'\n\
352        \t\t\techo '  off      — No aliases, raw shell'\n\
353        \tend\n\
354        end\n\
355        \n\
356        function lean-ctx-raw\n\
357        \tset -lx LEAN_CTX_RAW 1\n\
358        \tcommand $argv\n\
359        end\n\
360        \n\
361        function lean-ctx-status\n\
362        \tif set -q LEAN_CTX_DISABLED\n\
363        \t\tisatty stdout; and echo 'lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)'\n\
364        \telse if set -q LEAN_CTX_ENABLED\n\
365        \t\tisatty stdout; and echo 'lean-ctx: ON'\n\
366        \telse\n\
367        \t\tisatty stdout; and echo 'lean-ctx: OFF'\n\
368        \tend\n\
369        end\n\
370        \n\
371        function _lean_ctx_should_activate\n\
372        \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\
373        \t\treturn 1\n\
374        \tend\n\
375        \tset -l _lc_mode (set -q LEAN_CTX_SHELL_ACTIVATION; and echo $LEAN_CTX_SHELL_ACTIVATION; or echo '{baked_default}')\n\
376        \tswitch $_lc_mode\n\
377        \t\tcase off none manual\n\
378        \t\t\treturn 1\n\
379        \t\tcase 'agents-only' agents_only agentsonly\n\
380        \t\t\tif set -q LEAN_CTX_AGENT; or set -q CLAUDECODE; or set -q CODEX_CLI_SESSION; or set -q GEMINI_SESSION\n\
381        \t\t\t\treturn 0\n\
382        \t\t\tend\n\
383        \t\t\treturn 1\n\
384        \t\tcase '*'\n\
385        \t\t\treturn 0\n\
386        \tend\n\
387        end\n\
388        \n\
389        if _lean_ctx_should_activate\n\
390        \tif command -q lean-ctx\n\
391        \t\tlean-ctx-on\n\
392        \tend\n\
393        end\n"
394    )
395}
396
397pub fn init_fish(binary: &str) {
398    let config = dirs::home_dir()
399        .map(|h| h.join(".config/fish/config.fish"))
400        .unwrap_or_default();
401
402    let hook_content = generate_hook_fish(binary);
403
404    if write_hook_file("shell-hook.fish", &hook_content).is_some() {
405        upsert_source_line(&config, &source_line_fish());
406        qprintln!("  Binary: {binary}");
407    }
408}
409
410pub fn generate_hook_posix(binary: &str) -> String {
411    let config = crate::core::config::Config::load();
412    let activation = config.shell_activation_effective();
413    let baked_default = match activation {
414        crate::core::config::ShellActivation::Always => "always",
415        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
416        crate::core::config::ShellActivation::Off => "off",
417    };
418    let alias_list = crate::rewrite_registry::shell_alias_list();
419    format!(
420        r#"# lean-ctx shell hook — smart shell mode (track-by-default)
421_lean_ctx_cmds=({alias_list})
422
423_lc_is_agent() {{
424    [ -n "${{LEAN_CTX_AGENT:-}}" ] || [ -n "${{CODEX_CLI_SESSION:-}}" ] || [ -n "${{CLAUDECODE:-}}" ] || [ -n "${{GEMINI_SESSION:-}}" ]
425}}
426
427_lc() {{
428    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ]; then
429        command "$@"
430        return
431    fi
432    if [ ! -t 1 ] && ! _lc_is_agent; then
433        command "$@"
434        return
435    fi
436    '{binary}' -t "$@"
437    local _lc_rc=$?
438    if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
439        command "$@"
440    else
441        return "$_lc_rc"
442    fi
443}}
444
445_lc_compress() {{
446    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ]; then
447        command "$@"
448        return
449    fi
450    if [ ! -t 1 ] && ! _lc_is_agent; then
451        command "$@"
452        return
453    fi
454    '{binary}' -c "$@"
455    local _lc_rc=$?
456    if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
457        command "$@"
458    else
459        return "$_lc_rc"
460    fi
461}}
462
463lean-ctx-on() {{
464    for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
465        # shellcheck disable=SC2139
466        alias "$_lc_cmd"='_lc '"$_lc_cmd"
467    done
468    alias k='_lc kubectl'
469    export LEAN_CTX_ENABLED=1
470    [ -t 1 ] && echo "lean-ctx: ON (track mode — output unchanged, token savings recorded)"
471}}
472
473lean-ctx-off() {{
474    for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
475        unalias "$_lc_cmd" 2>/dev/null || true
476    done
477    unalias k 2>/dev/null || true
478    unset LEAN_CTX_ENABLED
479    [ -t 1 ] && echo "lean-ctx: OFF"
480}}
481
482lean-ctx-mode() {{
483    case "${{1:-}}" in
484        compress)
485            for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
486                # shellcheck disable=SC2139
487                alias "$_lc_cmd"='_lc_compress '"$_lc_cmd"
488            done
489            alias k='_lc_compress kubectl'
490            export LEAN_CTX_ENABLED=1
491            [ -t 1 ] && echo "lean-ctx: COMPRESS mode (all output compressed)"
492            ;;
493        track)
494            lean-ctx-on
495            ;;
496        off)
497            lean-ctx-off
498            ;;
499        *)
500            echo "Usage: lean-ctx-mode <track|compress|off>"
501            echo "  track    — Full output, stats recorded (default)"
502            echo "  compress — Compressed output for all commands"
503            echo "  off      — No aliases, raw shell"
504            ;;
505    esac
506}}
507
508lean-ctx-raw() {{
509    LEAN_CTX_RAW=1 command "$@"
510}}
511
512lean-ctx-status() {{
513    if [ -n "${{LEAN_CTX_DISABLED:-}}" ]; then
514        [ -t 1 ] && echo "lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)"
515    elif [ -n "${{LEAN_CTX_ENABLED:-}}" ]; then
516        [ -t 1 ] && echo "lean-ctx: ON"
517    else
518        [ -t 1 ] && echo "lean-ctx: OFF"
519    fi
520}}
521
522if [ -n "${{ZSH_VERSION:-}}" ]; then
523    _lean_ctx_comp() {{
524        shift words
525        (( CURRENT-- ))
526        _normal
527    }}
528    compdef _lean_ctx_comp _lc 2>/dev/null
529    compdef _lean_ctx_comp _lc_compress 2>/dev/null
530fi
531
532_lean_ctx_should_activate() {{
533    [ -z "${{LEAN_CTX_ACTIVE:-}}" ] && [ -z "${{LEAN_CTX_DISABLED:-}}" ] && [ "${{LEAN_CTX_ENABLED:-1}}" != "0" ] || return 1
534    case "${{LEAN_CTX_SHELL_ACTIVATION:-{baked_default}}}" in
535        off|none|manual) return 1 ;;
536        agents-only|agents_only|agentsonly)
537            [ -n "${{LEAN_CTX_AGENT:-}}" ] || [ -n "${{CLAUDECODE:-}}" ] || [ -n "${{CODEX_CLI_SESSION:-}}" ] || [ -n "${{GEMINI_SESSION:-}}" ] ;;
538        *) return 0 ;;
539    esac
540}}
541
542if _lean_ctx_should_activate; then
543    command -v lean-ctx >/dev/null 2>&1 && lean-ctx-on
544fi
545"#
546    )
547}
548
549pub fn init_posix(is_zsh: bool, binary: &str) {
550    let rc_file = if is_zsh {
551        dirs::home_dir()
552            .map(|h| h.join(".zshrc"))
553            .unwrap_or_default()
554    } else {
555        dirs::home_dir()
556            .map(|h| h.join(".bashrc"))
557            .unwrap_or_default()
558    };
559
560    let shell_ext = if is_zsh { "zsh" } else { "bash" };
561    let hook_content = generate_hook_posix(binary);
562
563    if let Some(hook_path) = write_hook_file(&format!("shell-hook.{shell_ext}"), &hook_content) {
564        upsert_source_line(&rc_file, &source_line_posix(shell_ext));
565        qprintln!("  Binary: {binary}");
566
567        write_env_sh_for_containers(&hook_content);
568        print_docker_env_hints(is_zsh);
569
570        let _ = hook_path;
571    }
572}
573
574pub fn write_env_sh_for_containers(aliases: &str) {
575    let env_sh = match crate::core::data_dir::lean_ctx_data_dir() {
576        Ok(d) => d.join("env.sh"),
577        Err(_) => return,
578    };
579    if let Some(parent) = env_sh.parent() {
580        let _ = std::fs::create_dir_all(parent);
581    }
582    let sanitized_aliases = crate::core::sanitize::neutralize_shell_content(aliases);
583    let mut content = sanitized_aliases;
584    content.push_str(
585        r#"
586
587# lean-ctx docker self-heal: re-inject Claude MCP config if Claude overwrote ~/.claude.json
588# Guards: container-only + no recursion + no re-entry via BASH_ENV + 60s cooldown + PID-lock
589if [ -f /.dockerenv ] || grep -qsE '/docker/|/lxc/' /proc/1/cgroup 2>/dev/null; then
590  if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ -z "${_LEAN_CTX_HEAL:-}" ]; then
591    _LEAN_CTX_HEAL_TS="${HOME}/.lean-ctx/.heal_ts"
592    _LEAN_CTX_HEAL_COOLDOWN=60
593    _lean_ctx_heal_needed=1
594    if [ -f "$_LEAN_CTX_HEAL_TS" ]; then
595      _last_heal=$(cat "$_LEAN_CTX_HEAL_TS" 2>/dev/null || echo 0)
596      _now=$(date +%s 2>/dev/null || echo 0)
597      if [ $(( _now - _last_heal )) -lt $_LEAN_CTX_HEAL_COOLDOWN ]; then
598        _lean_ctx_heal_needed=0
599      fi
600    fi
601    _lean_ctx_lock_count=0
602    for _lf in "${HOME}/.lean-ctx/locks"/slot-*.lock 2>/dev/null; do
603      [ -f "$_lf" ] && _lean_ctx_lock_count=$(( _lean_ctx_lock_count + 1 ))
604    done
605    if [ "$_lean_ctx_heal_needed" = "1" ] && [ "$_lean_ctx_lock_count" -lt 4 ]; then
606      export _LEAN_CTX_HEAL=1
607      if command -v claude >/dev/null 2>&1 && command -v lean-ctx >/dev/null 2>&1; then
608        if ! claude mcp list 2>/dev/null | grep -q "lean-ctx"; then
609          LEAN_CTX_ACTIVE=1 LEAN_CTX_QUIET=1 lean-ctx init --agent claude >/dev/null 2>&1
610          date +%s > "$_LEAN_CTX_HEAL_TS" 2>/dev/null
611        fi
612      fi
613    fi
614  fi
615fi
616"#,
617    );
618    match std::fs::write(&env_sh, content) {
619        Ok(()) => {
620            // Keep JSON-mode stdout clean; non-quiet hints go to stderr.
621            if !super::quiet_enabled() {
622                eprintln!("  env.sh: {}", env_sh.display());
623            }
624        }
625        Err(e) => tracing::warn!("could not write {}: {e}", env_sh.display()),
626    }
627}
628
629fn print_docker_env_hints(is_zsh: bool) {
630    if is_zsh || !crate::shell::is_container() {
631        return;
632    }
633    let env_sh = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
634        |_| "/root/.lean-ctx/env.sh".to_string(),
635        |d| d.join("env.sh").to_string_lossy().to_string(),
636    );
637
638    let has_bash_env = std::env::var("BASH_ENV").is_ok();
639    let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
640
641    if has_bash_env && has_claude_env {
642        return;
643    }
644
645    eprintln!();
646    eprintln!("  \x1b[33m⚠  Docker detected — environment hints:\x1b[0m");
647
648    if !has_bash_env {
649        eprintln!("  For generic bash -c usage (non-interactive shells):");
650        eprintln!("    \x1b[1mENV BASH_ENV=\"{env_sh}\"\x1b[0m");
651    }
652    if !has_claude_env {
653        eprintln!("  For Claude Code (sources before each command):");
654        eprintln!("    \x1b[1mENV CLAUDE_ENV_FILE=\"{env_sh}\"\x1b[0m");
655    }
656    eprintln!();
657}
658
659pub fn remove_lean_ctx_block(content: &str) -> String {
660    if content.contains("# lean-ctx shell hook — end") {
661        return remove_lean_ctx_block_by_marker(content);
662    }
663    remove_lean_ctx_block_legacy(content)
664}
665
666fn remove_lean_ctx_block_by_marker(content: &str) -> String {
667    let mut result = String::new();
668    let mut in_block = false;
669
670    for line in content.lines() {
671        if !in_block && line.contains("lean-ctx shell hook") && !line.contains("end") {
672            in_block = true;
673            continue;
674        }
675        if in_block {
676            if line.trim() == "# lean-ctx shell hook — end" {
677                in_block = false;
678            }
679            continue;
680        }
681        result.push_str(line);
682        result.push('\n');
683    }
684    result
685}
686
687fn remove_lean_ctx_block_legacy(content: &str) -> String {
688    let mut result = String::new();
689    let mut in_block = false;
690
691    for line in content.lines() {
692        if line.contains("lean-ctx shell hook") {
693            in_block = true;
694            continue;
695        }
696        if in_block {
697            if line.trim() == "fi" || line.trim() == "end" || line.trim().is_empty() {
698                if line.trim() == "fi" || line.trim() == "end" {
699                    in_block = false;
700                }
701                continue;
702            }
703            if !line.starts_with("alias ") && !line.starts_with('\t') && !line.starts_with("if ") {
704                in_block = false;
705                result.push_str(line);
706                result.push('\n');
707            }
708            continue;
709        }
710        result.push_str(line);
711        result.push('\n');
712    }
713    result
714}
715
716#[cfg(test)]
717mod tests {
718    use super::*;
719
720    #[test]
721    fn test_remove_lean_ctx_block_posix() {
722        let input = r#"# existing config
723export PATH="$HOME/bin:$PATH"
724
725# lean-ctx shell hook — transparent CLI compression (95+ patterns)
726if [ -z "$LEAN_CTX_ACTIVE" ]; then
727alias git='lean-ctx -c git'
728alias npm='lean-ctx -c npm'
729fi
730
731# other stuff
732export EDITOR=vim
733"#;
734        let result = remove_lean_ctx_block(input);
735        assert!(!result.contains("lean-ctx"), "block should be removed");
736        assert!(result.contains("export PATH"), "other content preserved");
737        assert!(
738            result.contains("export EDITOR"),
739            "trailing content preserved"
740        );
741    }
742
743    #[test]
744    fn test_remove_lean_ctx_block_fish() {
745        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";
746        let result = remove_lean_ctx_block(input);
747        assert!(!result.contains("lean-ctx"), "block should be removed");
748        assert!(result.contains("set -x FOO"), "other content preserved");
749        assert!(result.contains("set -x BAZ"), "trailing content preserved");
750    }
751
752    #[test]
753    fn test_remove_lean_ctx_block_ps() {
754        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";
755        let result = remove_lean_ctx_block_ps(input);
756        assert!(
757            !result.contains("lean-ctx shell hook"),
758            "block should be removed"
759        );
760        assert!(result.contains("$env:FOO"), "other content preserved");
761        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
762    }
763
764    #[test]
765    fn test_remove_lean_ctx_block_ps_nested() {
766        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";
767        let result = remove_lean_ctx_block_ps(input);
768        assert!(
769            !result.contains("lean-ctx shell hook"),
770            "block should be removed"
771        );
772        assert!(!result.contains("_lc"), "function should be removed");
773        assert!(result.contains("$env:FOO"), "other content preserved");
774        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
775    }
776
777    #[test]
778    fn test_remove_block_no_lean_ctx() {
779        let input = "# normal bashrc\nexport PATH=\"$HOME/bin:$PATH\"\n";
780        let result = remove_lean_ctx_block(input);
781        assert!(result.contains("export PATH"), "content unchanged");
782    }
783
784    #[test]
785    fn test_bash_hook_contains_pipe_guard_and_agent_bypass() {
786        let output = generate_hook_posix("/usr/local/bin/lean-ctx");
787        assert!(
788            output.contains("! -t 1"),
789            "bash/zsh hook must contain pipe guard [ ! -t 1 ]"
790        );
791        assert!(
792            output.contains("_lc_is_agent"),
793            "bash/zsh hook must have agent-aware bypass"
794        );
795        assert!(
796            output.contains("CODEX_CLI_SESSION"),
797            "agent check must include CODEX_CLI_SESSION"
798        );
799    }
800
801    #[test]
802    fn test_lc_uses_track_mode_by_default() {
803        let binary = "/usr/local/bin/lean-ctx";
804        let alias_list = crate::rewrite_registry::shell_alias_list();
805        let aliases = format!(
806            r#"_lc() {{
807    '{binary}' -t "$@"
808}}
809_lc_compress() {{
810    '{binary}' -c "$@"
811}}"#
812        );
813        assert!(
814            aliases.contains("-t \"$@\""),
815            "_lc must use -t (track mode) by default"
816        );
817        assert!(
818            aliases.contains("-c \"$@\""),
819            "_lc_compress must use -c (compress mode)"
820        );
821        let _ = alias_list;
822    }
823
824    #[test]
825    fn test_posix_shell_has_lean_ctx_mode() {
826        let alias_list = crate::rewrite_registry::shell_alias_list();
827        let aliases = r#"
828lean-ctx-mode() {{
829    case "${{1:-}}" in
830        compress) echo compress ;;
831        track) echo track ;;
832        off) echo off ;;
833    esac
834}}
835"#
836        .to_string();
837        assert!(
838            aliases.contains("lean-ctx-mode()"),
839            "lean-ctx-mode function must exist"
840        );
841        assert!(
842            aliases.contains("compress"),
843            "compress mode must be available"
844        );
845        assert!(aliases.contains("track"), "track mode must be available");
846        let _ = alias_list;
847    }
848
849    #[test]
850    fn test_fish_hook_contains_pipe_guard_and_agent_bypass() {
851        let output = generate_hook_fish("/usr/local/bin/lean-ctx");
852        assert!(
853            output.contains("isatty stdout"),
854            "fish hook must contain pipe guard (isatty stdout)"
855        );
856        assert!(
857            output.contains("_lc_is_agent"),
858            "fish hook must have agent-aware bypass"
859        );
860    }
861
862    #[test]
863    fn test_powershell_hook_contains_pipe_guard() {
864        let hook = "function _lc { if ($env:LEAN_CTX_DISABLED -or [Console]::IsOutputRedirected) { & @args; return } }";
865        assert!(
866            hook.contains("IsOutputRedirected"),
867            "PowerShell hook must contain pipe guard ([Console]::IsOutputRedirected)"
868        );
869    }
870
871    #[test]
872    fn test_remove_lean_ctx_block_new_format_with_end_marker() {
873        let input = r#"# existing config
874export PATH="$HOME/bin:$PATH"
875
876# lean-ctx shell hook — transparent CLI compression (95+ patterns)
877_lean_ctx_cmds=(git npm pnpm)
878
879lean-ctx-on() {
880    for _lc_cmd in "${_lean_ctx_cmds[@]}"; do
881        alias "$_lc_cmd"='lean-ctx -c '"$_lc_cmd"
882    done
883    export LEAN_CTX_ENABLED=1
884    [ -t 1 ] && echo "lean-ctx: ON"
885}
886
887lean-ctx-off() {
888    unset LEAN_CTX_ENABLED
889    [ -t 1 ] && echo "lean-ctx: OFF"
890}
891
892if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ "${LEAN_CTX_ENABLED:-1}" != "0" ]; then
893    lean-ctx-on
894fi
895# lean-ctx shell hook — end
896
897# other stuff
898export EDITOR=vim
899"#;
900        let result = remove_lean_ctx_block(input);
901        assert!(!result.contains("lean-ctx-on"), "block should be removed");
902        assert!(!result.contains("lean-ctx shell hook"), "marker removed");
903        assert!(result.contains("export PATH"), "other content preserved");
904        assert!(
905            result.contains("export EDITOR"),
906            "trailing content preserved"
907        );
908    }
909
910    #[test]
911    fn env_sh_for_containers_includes_self_heal() {
912        let _g = crate::core::data_dir::test_env_lock();
913        let tmp = tempfile::tempdir().expect("tempdir");
914        let data_dir = tmp.path().join("data");
915        std::fs::create_dir_all(&data_dir).expect("mkdir data");
916        std::env::set_var("LEAN_CTX_DATA_DIR", &data_dir);
917
918        write_env_sh_for_containers("alias git='lean-ctx -c git'\n");
919        let env_sh = data_dir.join("env.sh");
920        let content = std::fs::read_to_string(&env_sh).expect("env.sh exists");
921        assert!(content.contains("lean-ctx docker self-heal"));
922        assert!(content.contains("claude mcp list"));
923        assert!(content.contains("lean-ctx init --agent claude"));
924        assert!(
925            content.contains("_LEAN_CTX_HEAL"),
926            "env.sh must guard against recursive self-heal"
927        );
928        assert!(
929            content.contains("LEAN_CTX_ACTIVE"),
930            "env.sh must check LEAN_CTX_ACTIVE to prevent re-entry"
931        );
932        assert!(
933            content.contains("/.dockerenv"),
934            "env.sh self-heal must be gated to container environments"
935        );
936
937        std::env::remove_var("LEAN_CTX_DATA_DIR");
938    }
939
940    #[test]
941    fn test_source_line_posix() {
942        let line = source_line_posix("zsh");
943        assert!(line.contains("shell-hook.zsh"));
944        assert!(line.contains("[ -f"));
945    }
946
947    #[test]
948    fn test_source_line_fish() {
949        let line = source_line_fish();
950        assert!(line.contains("shell-hook.fish"));
951        assert!(line.contains("source"));
952    }
953
954    #[test]
955    fn test_source_line_powershell() {
956        let line = source_line_powershell();
957        assert!(line.contains("shell-hook.ps1"));
958        assert!(line.contains("Test-Path"));
959    }
960}