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 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
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 export _LEAN_CTX_HEAL=1
592 if command -v claude >/dev/null 2>&1 && command -v lean-ctx >/dev/null 2>&1; then
593 if ! claude mcp list 2>/dev/null | grep -q "lean-ctx"; then
594 LEAN_CTX_ACTIVE=1 LEAN_CTX_QUIET=1 lean-ctx init --agent claude >/dev/null 2>&1
595 fi
596 fi
597 fi
598fi
599"#,
600 );
601 match std::fs::write(&env_sh, content) {
602 Ok(()) => {
603 if !super::quiet_enabled() {
605 eprintln!(" env.sh: {}", env_sh.display());
606 }
607 }
608 Err(e) => tracing::warn!("could not write {}: {e}", env_sh.display()),
609 }
610}
611
612fn print_docker_env_hints(is_zsh: bool) {
613 if is_zsh || !crate::shell::is_container() {
614 return;
615 }
616 let env_sh = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
617 |_| "/root/.lean-ctx/env.sh".to_string(),
618 |d| d.join("env.sh").to_string_lossy().to_string(),
619 );
620
621 let has_bash_env = std::env::var("BASH_ENV").is_ok();
622 let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
623
624 if has_bash_env && has_claude_env {
625 return;
626 }
627
628 eprintln!();
629 eprintln!(" \x1b[33m⚠ Docker detected — environment hints:\x1b[0m");
630
631 if !has_bash_env {
632 eprintln!(" For generic bash -c usage (non-interactive shells):");
633 eprintln!(" \x1b[1mENV BASH_ENV=\"{env_sh}\"\x1b[0m");
634 }
635 if !has_claude_env {
636 eprintln!(" For Claude Code (sources before each command):");
637 eprintln!(" \x1b[1mENV CLAUDE_ENV_FILE=\"{env_sh}\"\x1b[0m");
638 }
639 eprintln!();
640}
641
642pub fn remove_lean_ctx_block(content: &str) -> String {
643 if content.contains("# lean-ctx shell hook — end") {
644 return remove_lean_ctx_block_by_marker(content);
645 }
646 remove_lean_ctx_block_legacy(content)
647}
648
649fn remove_lean_ctx_block_by_marker(content: &str) -> String {
650 let mut result = String::new();
651 let mut in_block = false;
652
653 for line in content.lines() {
654 if !in_block && line.contains("lean-ctx shell hook") && !line.contains("end") {
655 in_block = true;
656 continue;
657 }
658 if in_block {
659 if line.trim() == "# lean-ctx shell hook — end" {
660 in_block = false;
661 }
662 continue;
663 }
664 result.push_str(line);
665 result.push('\n');
666 }
667 result
668}
669
670fn remove_lean_ctx_block_legacy(content: &str) -> String {
671 let mut result = String::new();
672 let mut in_block = false;
673
674 for line in content.lines() {
675 if line.contains("lean-ctx shell hook") {
676 in_block = true;
677 continue;
678 }
679 if in_block {
680 if line.trim() == "fi" || line.trim() == "end" || line.trim().is_empty() {
681 if line.trim() == "fi" || line.trim() == "end" {
682 in_block = false;
683 }
684 continue;
685 }
686 if !line.starts_with("alias ") && !line.starts_with('\t') && !line.starts_with("if ") {
687 in_block = false;
688 result.push_str(line);
689 result.push('\n');
690 }
691 continue;
692 }
693 result.push_str(line);
694 result.push('\n');
695 }
696 result
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702
703 #[test]
704 fn test_remove_lean_ctx_block_posix() {
705 let input = r#"# existing config
706export PATH="$HOME/bin:$PATH"
707
708# lean-ctx shell hook — transparent CLI compression (95+ patterns)
709if [ -z "$LEAN_CTX_ACTIVE" ]; then
710alias git='lean-ctx -c git'
711alias npm='lean-ctx -c npm'
712fi
713
714# other stuff
715export EDITOR=vim
716"#;
717 let result = remove_lean_ctx_block(input);
718 assert!(!result.contains("lean-ctx"), "block should be removed");
719 assert!(result.contains("export PATH"), "other content preserved");
720 assert!(
721 result.contains("export EDITOR"),
722 "trailing content preserved"
723 );
724 }
725
726 #[test]
727 fn test_remove_lean_ctx_block_fish() {
728 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";
729 let result = remove_lean_ctx_block(input);
730 assert!(!result.contains("lean-ctx"), "block should be removed");
731 assert!(result.contains("set -x FOO"), "other content preserved");
732 assert!(result.contains("set -x BAZ"), "trailing content preserved");
733 }
734
735 #[test]
736 fn test_remove_lean_ctx_block_ps() {
737 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";
738 let result = remove_lean_ctx_block_ps(input);
739 assert!(
740 !result.contains("lean-ctx shell hook"),
741 "block should be removed"
742 );
743 assert!(result.contains("$env:FOO"), "other content preserved");
744 assert!(result.contains("$env:EDITOR"), "trailing content preserved");
745 }
746
747 #[test]
748 fn test_remove_lean_ctx_block_ps_nested() {
749 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";
750 let result = remove_lean_ctx_block_ps(input);
751 assert!(
752 !result.contains("lean-ctx shell hook"),
753 "block should be removed"
754 );
755 assert!(!result.contains("_lc"), "function should be removed");
756 assert!(result.contains("$env:FOO"), "other content preserved");
757 assert!(result.contains("$env:EDITOR"), "trailing content preserved");
758 }
759
760 #[test]
761 fn test_remove_block_no_lean_ctx() {
762 let input = "# normal bashrc\nexport PATH=\"$HOME/bin:$PATH\"\n";
763 let result = remove_lean_ctx_block(input);
764 assert!(result.contains("export PATH"), "content unchanged");
765 }
766
767 #[test]
768 fn test_bash_hook_contains_pipe_guard_and_agent_bypass() {
769 let output = generate_hook_posix("/usr/local/bin/lean-ctx");
770 assert!(
771 output.contains("! -t 1"),
772 "bash/zsh hook must contain pipe guard [ ! -t 1 ]"
773 );
774 assert!(
775 output.contains("_lc_is_agent"),
776 "bash/zsh hook must have agent-aware bypass"
777 );
778 assert!(
779 output.contains("CODEX_CLI_SESSION"),
780 "agent check must include CODEX_CLI_SESSION"
781 );
782 }
783
784 #[test]
785 fn test_lc_uses_track_mode_by_default() {
786 let binary = "/usr/local/bin/lean-ctx";
787 let alias_list = crate::rewrite_registry::shell_alias_list();
788 let aliases = format!(
789 r#"_lc() {{
790 '{binary}' -t "$@"
791}}
792_lc_compress() {{
793 '{binary}' -c "$@"
794}}"#
795 );
796 assert!(
797 aliases.contains("-t \"$@\""),
798 "_lc must use -t (track mode) by default"
799 );
800 assert!(
801 aliases.contains("-c \"$@\""),
802 "_lc_compress must use -c (compress mode)"
803 );
804 let _ = alias_list;
805 }
806
807 #[test]
808 fn test_posix_shell_has_lean_ctx_mode() {
809 let alias_list = crate::rewrite_registry::shell_alias_list();
810 let aliases = r#"
811lean-ctx-mode() {{
812 case "${{1:-}}" in
813 compress) echo compress ;;
814 track) echo track ;;
815 off) echo off ;;
816 esac
817}}
818"#
819 .to_string();
820 assert!(
821 aliases.contains("lean-ctx-mode()"),
822 "lean-ctx-mode function must exist"
823 );
824 assert!(
825 aliases.contains("compress"),
826 "compress mode must be available"
827 );
828 assert!(aliases.contains("track"), "track mode must be available");
829 let _ = alias_list;
830 }
831
832 #[test]
833 fn test_fish_hook_contains_pipe_guard_and_agent_bypass() {
834 let output = generate_hook_fish("/usr/local/bin/lean-ctx");
835 assert!(
836 output.contains("isatty stdout"),
837 "fish hook must contain pipe guard (isatty stdout)"
838 );
839 assert!(
840 output.contains("_lc_is_agent"),
841 "fish hook must have agent-aware bypass"
842 );
843 }
844
845 #[test]
846 fn test_powershell_hook_contains_pipe_guard() {
847 let hook = "function _lc { if ($env:LEAN_CTX_DISABLED -or [Console]::IsOutputRedirected) { & @args; return } }";
848 assert!(
849 hook.contains("IsOutputRedirected"),
850 "PowerShell hook must contain pipe guard ([Console]::IsOutputRedirected)"
851 );
852 }
853
854 #[test]
855 fn test_remove_lean_ctx_block_new_format_with_end_marker() {
856 let input = r#"# existing config
857export PATH="$HOME/bin:$PATH"
858
859# lean-ctx shell hook — transparent CLI compression (95+ patterns)
860_lean_ctx_cmds=(git npm pnpm)
861
862lean-ctx-on() {
863 for _lc_cmd in "${_lean_ctx_cmds[@]}"; do
864 alias "$_lc_cmd"='lean-ctx -c '"$_lc_cmd"
865 done
866 export LEAN_CTX_ENABLED=1
867 [ -t 1 ] && echo "lean-ctx: ON"
868}
869
870lean-ctx-off() {
871 unset LEAN_CTX_ENABLED
872 [ -t 1 ] && echo "lean-ctx: OFF"
873}
874
875if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ "${LEAN_CTX_ENABLED:-1}" != "0" ]; then
876 lean-ctx-on
877fi
878# lean-ctx shell hook — end
879
880# other stuff
881export EDITOR=vim
882"#;
883 let result = remove_lean_ctx_block(input);
884 assert!(!result.contains("lean-ctx-on"), "block should be removed");
885 assert!(!result.contains("lean-ctx shell hook"), "marker removed");
886 assert!(result.contains("export PATH"), "other content preserved");
887 assert!(
888 result.contains("export EDITOR"),
889 "trailing content preserved"
890 );
891 }
892
893 #[test]
894 fn env_sh_for_containers_includes_self_heal() {
895 let _g = crate::core::data_dir::test_env_lock();
896 let tmp = tempfile::tempdir().expect("tempdir");
897 let data_dir = tmp.path().join("data");
898 std::fs::create_dir_all(&data_dir).expect("mkdir data");
899 std::env::set_var("LEAN_CTX_DATA_DIR", &data_dir);
900
901 write_env_sh_for_containers("alias git='lean-ctx -c git'\n");
902 let env_sh = data_dir.join("env.sh");
903 let content = std::fs::read_to_string(&env_sh).expect("env.sh exists");
904 assert!(content.contains("lean-ctx docker self-heal"));
905 assert!(content.contains("claude mcp list"));
906 assert!(content.contains("lean-ctx init --agent claude"));
907 assert!(
908 content.contains("_LEAN_CTX_HEAL"),
909 "env.sh must guard against recursive self-heal"
910 );
911 assert!(
912 content.contains("LEAN_CTX_ACTIVE"),
913 "env.sh must check LEAN_CTX_ACTIVE to prevent re-entry"
914 );
915 assert!(
916 content.contains("/.dockerenv"),
917 "env.sh self-heal must be gated to container environments"
918 );
919
920 std::env::remove_var("LEAN_CTX_DATA_DIR");
921 }
922
923 #[test]
924 fn test_source_line_posix() {
925 let line = source_line_posix("zsh");
926 assert!(line.contains("shell-hook.zsh"));
927 assert!(line.contains("[ -f"));
928 }
929
930 #[test]
931 fn test_source_line_fish() {
932 let line = source_line_fish();
933 assert!(line.contains("shell-hook.fish"));
934 assert!(line.contains("source"));
935 }
936
937 #[test]
938 fn test_source_line_powershell() {
939 let line = source_line_powershell();
940 assert!(line.contains("shell-hook.ps1"));
941 assert!(line.contains("Test-Path"));
942 }
943}