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\n\
278        \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK; or not isatty stdout\n\
279        \t\tcommand $argv\n\
280        \t\treturn\n\
281        \tend\n\
282        \t'{binary}' -t $argv\n\
283        \tset -l _lc_rc $status\n\
284        \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
285        \t\tcommand $argv\n\
286        \telse\n\
287        \t\treturn $_lc_rc\n\
288        \tend\n\
289        end\n\
290        \n\
291        function _lc_compress\n\
292        \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK; or not isatty stdout\n\
293        \t\tcommand $argv\n\
294        \t\treturn\n\
295        \tend\n\
296        \t'{binary}' -c $argv\n\
297        \tset -l _lc_rc $status\n\
298        \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
299        \t\tcommand $argv\n\
300        \telse\n\
301        \t\treturn $_lc_rc\n\
302        \tend\n\
303        end\n\
304        \n\
305        function lean-ctx-on\n\
306        \tfor _lc_cmd in $_lean_ctx_cmds\n\
307        \t\talias $_lc_cmd '_lc '$_lc_cmd\n\
308        \tend\n\
309        \talias k '_lc kubectl'\n\
310        \tset -gx LEAN_CTX_ENABLED 1\n\
311        \tisatty stdout; and echo 'lean-ctx: ON (track mode — output unchanged, token savings recorded)'\n\
312        end\n\
313        \n\
314        function lean-ctx-off\n\
315        \tfor _lc_cmd in $_lean_ctx_cmds\n\
316        \t\tfunctions --erase $_lc_cmd 2>/dev/null; true\n\
317        \tend\n\
318        \tfunctions --erase k 2>/dev/null; true\n\
319        \tset -e LEAN_CTX_ENABLED\n\
320        \tisatty stdout; and echo 'lean-ctx: OFF'\n\
321        end\n\
322        \n\
323        function lean-ctx-mode\n\
324        \tswitch $argv[1]\n\
325        \t\tcase compress\n\
326        \t\t\tfor _lc_cmd in $_lean_ctx_cmds\n\
327        \t\t\t\talias $_lc_cmd '_lc_compress '$_lc_cmd\n\
328        \t\t\t\tend\n\
329        \t\t\talias k '_lc_compress kubectl'\n\
330        \t\t\tset -gx LEAN_CTX_ENABLED 1\n\
331        \t\t\tisatty stdout; and echo 'lean-ctx: COMPRESS mode (all output compressed)'\n\
332        \t\tcase track\n\
333        \t\t\tlean-ctx-on\n\
334        \t\tcase off\n\
335        \t\t\tlean-ctx-off\n\
336        \t\tcase '*'\n\
337        \t\t\techo 'Usage: lean-ctx-mode <track|compress|off>'\n\
338        \t\t\techo '  track    — Full output, stats recorded (default)'\n\
339        \t\t\techo '  compress — Compressed output for all commands'\n\
340        \t\t\techo '  off      — No aliases, raw shell'\n\
341        \tend\n\
342        end\n\
343        \n\
344        function lean-ctx-raw\n\
345        \tset -lx LEAN_CTX_RAW 1\n\
346        \tcommand $argv\n\
347        end\n\
348        \n\
349        function lean-ctx-status\n\
350        \tif set -q LEAN_CTX_DISABLED\n\
351        \t\tisatty stdout; and echo 'lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)'\n\
352        \telse if set -q LEAN_CTX_ENABLED\n\
353        \t\tisatty stdout; and echo 'lean-ctx: ON'\n\
354        \telse\n\
355        \t\tisatty stdout; and echo 'lean-ctx: OFF'\n\
356        \tend\n\
357        end\n\
358        \n\
359        function _lean_ctx_should_activate\n\
360        \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\
361        \t\treturn 1\n\
362        \tend\n\
363        \tset -l _lc_mode (set -q LEAN_CTX_SHELL_ACTIVATION; and echo $LEAN_CTX_SHELL_ACTIVATION; or echo '{baked_default}')\n\
364        \tswitch $_lc_mode\n\
365        \t\tcase off none manual\n\
366        \t\t\treturn 1\n\
367        \t\tcase 'agents-only' agents_only agentsonly\n\
368        \t\t\tif set -q LEAN_CTX_AGENT; or set -q CLAUDECODE; or set -q CODEX_CLI_SESSION; or set -q GEMINI_SESSION\n\
369        \t\t\t\treturn 0\n\
370        \t\t\tend\n\
371        \t\t\treturn 1\n\
372        \t\tcase '*'\n\
373        \t\t\treturn 0\n\
374        \tend\n\
375        end\n\
376        \n\
377        if _lean_ctx_should_activate\n\
378        \tif command -q lean-ctx\n\
379        \t\tlean-ctx-on\n\
380        \tend\n\
381        end\n"
382    )
383}
384
385pub fn init_fish(binary: &str) {
386    let config = dirs::home_dir()
387        .map(|h| h.join(".config/fish/config.fish"))
388        .unwrap_or_default();
389
390    let hook_content = generate_hook_fish(binary);
391
392    if write_hook_file("shell-hook.fish", &hook_content).is_some() {
393        upsert_source_line(&config, &source_line_fish());
394        qprintln!("  Binary: {binary}");
395    }
396}
397
398pub fn generate_hook_posix(binary: &str) -> String {
399    let config = crate::core::config::Config::load();
400    let activation = config.shell_activation_effective();
401    let baked_default = match activation {
402        crate::core::config::ShellActivation::Always => "always",
403        crate::core::config::ShellActivation::AgentsOnly => "agents-only",
404        crate::core::config::ShellActivation::Off => "off",
405    };
406    let alias_list = crate::rewrite_registry::shell_alias_list();
407    format!(
408        r#"# lean-ctx shell hook — smart shell mode (track-by-default)
409_lean_ctx_cmds=({alias_list})
410
411_lc() {{
412    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ] || [ ! -t 1 ]; then
413        command "$@"
414        return
415    fi
416    '{binary}' -t "$@"
417    local _lc_rc=$?
418    if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
419        command "$@"
420    else
421        return "$_lc_rc"
422    fi
423}}
424
425_lc_compress() {{
426    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ] || [ ! -t 1 ]; then
427        command "$@"
428        return
429    fi
430    '{binary}' -c "$@"
431    local _lc_rc=$?
432    if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
433        command "$@"
434    else
435        return "$_lc_rc"
436    fi
437}}
438
439lean-ctx-on() {{
440    for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
441        # shellcheck disable=SC2139
442        alias "$_lc_cmd"='_lc '"$_lc_cmd"
443    done
444    alias k='_lc kubectl'
445    export LEAN_CTX_ENABLED=1
446    [ -t 1 ] && echo "lean-ctx: ON (track mode — output unchanged, token savings recorded)"
447}}
448
449lean-ctx-off() {{
450    for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
451        unalias "$_lc_cmd" 2>/dev/null || true
452    done
453    unalias k 2>/dev/null || true
454    unset LEAN_CTX_ENABLED
455    [ -t 1 ] && echo "lean-ctx: OFF"
456}}
457
458lean-ctx-mode() {{
459    case "${{1:-}}" in
460        compress)
461            for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
462                # shellcheck disable=SC2139
463                alias "$_lc_cmd"='_lc_compress '"$_lc_cmd"
464            done
465            alias k='_lc_compress kubectl'
466            export LEAN_CTX_ENABLED=1
467            [ -t 1 ] && echo "lean-ctx: COMPRESS mode (all output compressed)"
468            ;;
469        track)
470            lean-ctx-on
471            ;;
472        off)
473            lean-ctx-off
474            ;;
475        *)
476            echo "Usage: lean-ctx-mode <track|compress|off>"
477            echo "  track    — Full output, stats recorded (default)"
478            echo "  compress — Compressed output for all commands"
479            echo "  off      — No aliases, raw shell"
480            ;;
481    esac
482}}
483
484lean-ctx-raw() {{
485    LEAN_CTX_RAW=1 command "$@"
486}}
487
488lean-ctx-status() {{
489    if [ -n "${{LEAN_CTX_DISABLED:-}}" ]; then
490        [ -t 1 ] && echo "lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)"
491    elif [ -n "${{LEAN_CTX_ENABLED:-}}" ]; then
492        [ -t 1 ] && echo "lean-ctx: ON"
493    else
494        [ -t 1 ] && echo "lean-ctx: OFF"
495    fi
496}}
497
498if [ -n "${{ZSH_VERSION:-}}" ]; then
499    _lean_ctx_comp() {{
500        shift words
501        (( CURRENT-- ))
502        _normal
503    }}
504    compdef _lean_ctx_comp _lc 2>/dev/null
505    compdef _lean_ctx_comp _lc_compress 2>/dev/null
506fi
507
508_lean_ctx_should_activate() {{
509    [ -z "${{LEAN_CTX_ACTIVE:-}}" ] && [ -z "${{LEAN_CTX_DISABLED:-}}" ] && [ "${{LEAN_CTX_ENABLED:-1}}" != "0" ] || return 1
510    case "${{LEAN_CTX_SHELL_ACTIVATION:-{baked_default}}}" in
511        off|none|manual) return 1 ;;
512        agents-only|agents_only|agentsonly)
513            [ -n "${{LEAN_CTX_AGENT:-}}" ] || [ -n "${{CLAUDECODE:-}}" ] || [ -n "${{CODEX_CLI_SESSION:-}}" ] || [ -n "${{GEMINI_SESSION:-}}" ] ;;
514        *) return 0 ;;
515    esac
516}}
517
518if _lean_ctx_should_activate; then
519    command -v lean-ctx >/dev/null 2>&1 && lean-ctx-on
520fi
521"#
522    )
523}
524
525pub fn init_posix(is_zsh: bool, binary: &str) {
526    let rc_file = if is_zsh {
527        dirs::home_dir()
528            .map(|h| h.join(".zshrc"))
529            .unwrap_or_default()
530    } else {
531        dirs::home_dir()
532            .map(|h| h.join(".bashrc"))
533            .unwrap_or_default()
534    };
535
536    let shell_ext = if is_zsh { "zsh" } else { "bash" };
537    let hook_content = generate_hook_posix(binary);
538
539    if let Some(hook_path) = write_hook_file(&format!("shell-hook.{shell_ext}"), &hook_content) {
540        upsert_source_line(&rc_file, &source_line_posix(shell_ext));
541        qprintln!("  Binary: {binary}");
542
543        write_env_sh_for_containers(&hook_content);
544        print_docker_env_hints(is_zsh);
545
546        let _ = hook_path;
547    }
548}
549
550pub fn write_env_sh_for_containers(aliases: &str) {
551    let env_sh = match crate::core::data_dir::lean_ctx_data_dir() {
552        Ok(d) => d.join("env.sh"),
553        Err(_) => return,
554    };
555    if let Some(parent) = env_sh.parent() {
556        let _ = std::fs::create_dir_all(parent);
557    }
558    let sanitized_aliases = crate::core::sanitize::neutralize_shell_content(aliases);
559    let mut content = sanitized_aliases;
560    content.push_str(
561        r#"
562
563# lean-ctx docker self-heal: re-inject Claude MCP config if Claude overwrote ~/.claude.json
564if command -v claude >/dev/null 2>&1 && command -v lean-ctx >/dev/null 2>&1; then
565  if ! claude mcp list 2>/dev/null | grep -q "lean-ctx"; then
566    LEAN_CTX_QUIET=1 lean-ctx init --agent claude >/dev/null 2>&1
567  fi
568fi
569"#,
570    );
571    match std::fs::write(&env_sh, content) {
572        Ok(()) => {
573            // Keep JSON-mode stdout clean; non-quiet hints go to stderr.
574            if !super::quiet_enabled() {
575                eprintln!("  env.sh: {}", env_sh.display());
576            }
577        }
578        Err(e) => tracing::warn!("could not write {}: {e}", env_sh.display()),
579    }
580}
581
582fn print_docker_env_hints(is_zsh: bool) {
583    if is_zsh || !crate::shell::is_container() {
584        return;
585    }
586    let env_sh = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
587        |_| "/root/.lean-ctx/env.sh".to_string(),
588        |d| d.join("env.sh").to_string_lossy().to_string(),
589    );
590
591    let has_bash_env = std::env::var("BASH_ENV").is_ok();
592    let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
593
594    if has_bash_env && has_claude_env {
595        return;
596    }
597
598    eprintln!();
599    eprintln!("  \x1b[33m⚠  Docker detected — environment hints:\x1b[0m");
600
601    if !has_bash_env {
602        eprintln!("  For generic bash -c usage (non-interactive shells):");
603        eprintln!("    \x1b[1mENV BASH_ENV=\"{env_sh}\"\x1b[0m");
604    }
605    if !has_claude_env {
606        eprintln!("  For Claude Code (sources before each command):");
607        eprintln!("    \x1b[1mENV CLAUDE_ENV_FILE=\"{env_sh}\"\x1b[0m");
608    }
609    eprintln!();
610}
611
612pub fn remove_lean_ctx_block(content: &str) -> String {
613    if content.contains("# lean-ctx shell hook — end") {
614        return remove_lean_ctx_block_by_marker(content);
615    }
616    remove_lean_ctx_block_legacy(content)
617}
618
619fn remove_lean_ctx_block_by_marker(content: &str) -> String {
620    let mut result = String::new();
621    let mut in_block = false;
622
623    for line in content.lines() {
624        if !in_block && line.contains("lean-ctx shell hook") && !line.contains("end") {
625            in_block = true;
626            continue;
627        }
628        if in_block {
629            if line.trim() == "# lean-ctx shell hook — end" {
630                in_block = false;
631            }
632            continue;
633        }
634        result.push_str(line);
635        result.push('\n');
636    }
637    result
638}
639
640fn remove_lean_ctx_block_legacy(content: &str) -> String {
641    let mut result = String::new();
642    let mut in_block = false;
643
644    for line in content.lines() {
645        if line.contains("lean-ctx shell hook") {
646            in_block = true;
647            continue;
648        }
649        if in_block {
650            if line.trim() == "fi" || line.trim() == "end" || line.trim().is_empty() {
651                if line.trim() == "fi" || line.trim() == "end" {
652                    in_block = false;
653                }
654                continue;
655            }
656            if !line.starts_with("alias ") && !line.starts_with('\t') && !line.starts_with("if ") {
657                in_block = false;
658                result.push_str(line);
659                result.push('\n');
660            }
661            continue;
662        }
663        result.push_str(line);
664        result.push('\n');
665    }
666    result
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    #[test]
674    fn test_remove_lean_ctx_block_posix() {
675        let input = r#"# existing config
676export PATH="$HOME/bin:$PATH"
677
678# lean-ctx shell hook — transparent CLI compression (95+ patterns)
679if [ -z "$LEAN_CTX_ACTIVE" ]; then
680alias git='lean-ctx -c git'
681alias npm='lean-ctx -c npm'
682fi
683
684# other stuff
685export EDITOR=vim
686"#;
687        let result = remove_lean_ctx_block(input);
688        assert!(!result.contains("lean-ctx"), "block should be removed");
689        assert!(result.contains("export PATH"), "other content preserved");
690        assert!(
691            result.contains("export EDITOR"),
692            "trailing content preserved"
693        );
694    }
695
696    #[test]
697    fn test_remove_lean_ctx_block_fish() {
698        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";
699        let result = remove_lean_ctx_block(input);
700        assert!(!result.contains("lean-ctx"), "block should be removed");
701        assert!(result.contains("set -x FOO"), "other content preserved");
702        assert!(result.contains("set -x BAZ"), "trailing content preserved");
703    }
704
705    #[test]
706    fn test_remove_lean_ctx_block_ps() {
707        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";
708        let result = remove_lean_ctx_block_ps(input);
709        assert!(
710            !result.contains("lean-ctx shell hook"),
711            "block should be removed"
712        );
713        assert!(result.contains("$env:FOO"), "other content preserved");
714        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
715    }
716
717    #[test]
718    fn test_remove_lean_ctx_block_ps_nested() {
719        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";
720        let result = remove_lean_ctx_block_ps(input);
721        assert!(
722            !result.contains("lean-ctx shell hook"),
723            "block should be removed"
724        );
725        assert!(!result.contains("_lc"), "function should be removed");
726        assert!(result.contains("$env:FOO"), "other content preserved");
727        assert!(result.contains("$env:EDITOR"), "trailing content preserved");
728    }
729
730    #[test]
731    fn test_remove_block_no_lean_ctx() {
732        let input = "# normal bashrc\nexport PATH=\"$HOME/bin:$PATH\"\n";
733        let result = remove_lean_ctx_block(input);
734        assert!(result.contains("export PATH"), "content unchanged");
735    }
736
737    #[test]
738    fn test_bash_hook_contains_pipe_guard() {
739        let binary = "/usr/local/bin/lean-ctx";
740        let hook = format!(
741            r#"_lc() {{
742    if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ ! -t 1 ]; then
743        command "$@"
744        return
745    fi
746    '{binary}' -t "$@"
747}}"#
748        );
749        assert!(
750            hook.contains("! -t 1"),
751            "bash/zsh hook must contain pipe guard [ ! -t 1 ]"
752        );
753        assert!(
754            hook.contains("LEAN_CTX_DISABLED") && hook.contains("! -t 1"),
755            "pipe guard must be in the same conditional as LEAN_CTX_DISABLED"
756        );
757    }
758
759    #[test]
760    fn test_lc_uses_track_mode_by_default() {
761        let binary = "/usr/local/bin/lean-ctx";
762        let alias_list = crate::rewrite_registry::shell_alias_list();
763        let aliases = format!(
764            r#"_lc() {{
765    '{binary}' -t "$@"
766}}
767_lc_compress() {{
768    '{binary}' -c "$@"
769}}"#
770        );
771        assert!(
772            aliases.contains("-t \"$@\""),
773            "_lc must use -t (track mode) by default"
774        );
775        assert!(
776            aliases.contains("-c \"$@\""),
777            "_lc_compress must use -c (compress mode)"
778        );
779        let _ = alias_list;
780    }
781
782    #[test]
783    fn test_posix_shell_has_lean_ctx_mode() {
784        let alias_list = crate::rewrite_registry::shell_alias_list();
785        let aliases = r#"
786lean-ctx-mode() {{
787    case "${{1:-}}" in
788        compress) echo compress ;;
789        track) echo track ;;
790        off) echo off ;;
791    esac
792}}
793"#
794        .to_string();
795        assert!(
796            aliases.contains("lean-ctx-mode()"),
797            "lean-ctx-mode function must exist"
798        );
799        assert!(
800            aliases.contains("compress"),
801            "compress mode must be available"
802        );
803        assert!(aliases.contains("track"), "track mode must be available");
804        let _ = alias_list;
805    }
806
807    #[test]
808    fn test_fish_hook_contains_pipe_guard() {
809        let hook = "function _lc\n\tif set -q LEAN_CTX_DISABLED; or not isatty stdout\n\t\tcommand $argv\n\t\treturn\n\tend\nend";
810        assert!(
811            hook.contains("isatty stdout"),
812            "fish hook must contain pipe guard (isatty stdout)"
813        );
814    }
815
816    #[test]
817    fn test_powershell_hook_contains_pipe_guard() {
818        let hook = "function _lc { if ($env:LEAN_CTX_DISABLED -or [Console]::IsOutputRedirected) { & @args; return } }";
819        assert!(
820            hook.contains("IsOutputRedirected"),
821            "PowerShell hook must contain pipe guard ([Console]::IsOutputRedirected)"
822        );
823    }
824
825    #[test]
826    fn test_remove_lean_ctx_block_new_format_with_end_marker() {
827        let input = r#"# existing config
828export PATH="$HOME/bin:$PATH"
829
830# lean-ctx shell hook — transparent CLI compression (95+ patterns)
831_lean_ctx_cmds=(git npm pnpm)
832
833lean-ctx-on() {
834    for _lc_cmd in "${_lean_ctx_cmds[@]}"; do
835        alias "$_lc_cmd"='lean-ctx -c '"$_lc_cmd"
836    done
837    export LEAN_CTX_ENABLED=1
838    [ -t 1 ] && echo "lean-ctx: ON"
839}
840
841lean-ctx-off() {
842    unset LEAN_CTX_ENABLED
843    [ -t 1 ] && echo "lean-ctx: OFF"
844}
845
846if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ "${LEAN_CTX_ENABLED:-1}" != "0" ]; then
847    lean-ctx-on
848fi
849# lean-ctx shell hook — end
850
851# other stuff
852export EDITOR=vim
853"#;
854        let result = remove_lean_ctx_block(input);
855        assert!(!result.contains("lean-ctx-on"), "block should be removed");
856        assert!(!result.contains("lean-ctx shell hook"), "marker removed");
857        assert!(result.contains("export PATH"), "other content preserved");
858        assert!(
859            result.contains("export EDITOR"),
860            "trailing content preserved"
861        );
862    }
863
864    #[test]
865    fn env_sh_for_containers_includes_self_heal() {
866        let _g = crate::core::data_dir::test_env_lock();
867        let tmp = tempfile::tempdir().expect("tempdir");
868        let data_dir = tmp.path().join("data");
869        std::fs::create_dir_all(&data_dir).expect("mkdir data");
870        std::env::set_var("LEAN_CTX_DATA_DIR", &data_dir);
871
872        write_env_sh_for_containers("alias git='lean-ctx -c git'\n");
873        let env_sh = data_dir.join("env.sh");
874        let content = std::fs::read_to_string(&env_sh).expect("env.sh exists");
875        assert!(content.contains("lean-ctx docker self-heal"));
876        assert!(content.contains("claude mcp list"));
877        assert!(content.contains("lean-ctx init --agent claude"));
878
879        std::env::remove_var("LEAN_CTX_DATA_DIR");
880    }
881
882    #[test]
883    fn test_source_line_posix() {
884        let line = source_line_posix("zsh");
885        assert!(line.contains("shell-hook.zsh"));
886        assert!(line.contains("[ -f"));
887    }
888
889    #[test]
890    fn test_source_line_fish() {
891        let line = source_line_fish();
892        assert!(line.contains("shell-hook.fish"));
893        assert!(line.contains("source"));
894    }
895
896    #[test]
897    fn test_source_line_powershell() {
898        let line = source_line_powershell();
899        assert!(line.contains("shell-hook.ps1"));
900        assert!(line.contains("Test-Path"));
901    }
902}