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