1macro_rules! qprintln {
2 ($($t:tt)*) => {
3 if !super::quiet_enabled() {
4 println!($($t)*);
5 }
6 };
7}
8
9pub fn print_hook_stdout(shell: &str) {
10 let binary = crate::core::portable_binary::resolve_portable_binary();
11 let binary = hook_binary_for_shell(shell, &binary);
12
13 let code = match shell {
14 "bash" | "zsh" => generate_hook_posix(&binary),
15 "fish" => generate_hook_fish(&binary),
16 "powershell" | "pwsh" => generate_hook_powershell(&binary),
17 _ => {
18 tracing::error!("lean-ctx: unsupported shell '{shell}'");
19 eprintln!("Supported: bash, zsh, fish, powershell");
20 std::process::exit(1);
21 }
22 };
23 print!("{code}");
24}
25
26fn hook_binary_for_shell(shell: &str, binary: &str) -> String {
34 match shell {
35 "powershell" | "pwsh" => binary.to_string(),
36 _ => crate::hooks::to_bash_compatible_path(binary),
37 }
38}
39
40fn backup_shell_config(path: &std::path::Path) {
41 if !path.exists() {
42 return;
43 }
44 let bak = path.with_extension("lean-ctx.bak");
45 if std::fs::copy(path, &bak).is_ok() {
46 qprintln!(
47 " Backup: {}",
48 bak.file_name().map_or_else(
49 || bak.display().to_string(),
50 |n| format!("~/{}", n.to_string_lossy())
51 )
52 );
53 }
54}
55
56fn config_artifact_dir() -> Option<std::path::PathBuf> {
61 crate::core::paths::config_dir().ok()
62}
63
64fn write_hook_file(filename: &str, content: &str) -> Option<std::path::PathBuf> {
65 let dir = config_artifact_dir()?;
66 let _ = std::fs::create_dir_all(&dir);
67 let path = dir.join(filename);
68 match std::fs::write(&path, content) {
69 Ok(()) => {
70 #[cfg(unix)]
71 {
72 use std::os::unix::fs::PermissionsExt;
73 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644));
74 }
75 Some(path)
76 }
77 Err(e) => {
78 tracing::error!("Error writing {}: {e}", path.display());
79 None
80 }
81 }
82}
83
84fn resolved_hook_dir_display() -> String {
85 config_artifact_dir().map_or_else(
86 || "$HOME/.config/lean-ctx".to_string(),
87 |p| p.to_string_lossy().to_string(),
88 )
89}
90
91fn source_line_posix(shell_ext: &str) -> String {
92 let mut dir = resolved_hook_dir_display();
93 if cfg!(windows) {
95 dir = crate::hooks::to_bash_compatible_path(&dir);
96 }
97 format!(
98 "# lean-ctx shell hook — begin\n\
99 if [ -f \"{dir}/shell-hook.{shell_ext}\" ]; then\n\
100 . \"{dir}/shell-hook.{shell_ext}\"\n\
101 fi\n\
102 # lean-ctx shell hook — end\n"
103 )
104}
105
106fn source_line_fish() -> String {
107 let mut dir = resolved_hook_dir_display();
108 if cfg!(windows) {
110 dir = crate::hooks::to_bash_compatible_path(&dir);
111 }
112 format!(
113 "# lean-ctx shell hook — begin\n\
114 if test -f \"{dir}/shell-hook.fish\"\n\
115 source \"{dir}/shell-hook.fish\"\n\
116 end\n\
117 # lean-ctx shell hook — end\n"
118 )
119}
120
121fn source_line_powershell() -> String {
122 let dir = resolved_hook_dir_display();
123 let dir_ps = dir.replace('/', "\\");
124 format!(
125 "# lean-ctx shell hook — begin\n\
126 $leanCtxHook = \"{dir_ps}\\shell-hook.ps1\"\n\
127 if ((Test-Path $leanCtxHook) -and -not [Console]::IsOutputRedirected) {{ . $leanCtxHook }}\n"
128 )
129}
130
131fn upsert_source_line(rc_path: &std::path::Path, source_line: &str) {
132 backup_shell_config(rc_path);
133
134 if let Ok(existing) = std::fs::read_to_string(rc_path) {
135 if existing.contains(source_line.trim()) {
136 return;
137 }
138
139 let cleaned = remove_lean_ctx_block(&existing);
141 let cleaned = cleaned
142 .lines()
143 .filter(|line| {
144 !line.contains("lean-ctx/shell-hook.")
145 && !line.contains("lean-ctx\\shell-hook.")
146 && line.trim() != "lean-ctx shell hook"
147 })
148 .collect::<Vec<_>>()
149 .join("\n");
150 let cleaned = if cleaned.ends_with('\n') {
151 cleaned
152 } else {
153 format!("{cleaned}\n")
154 };
155
156 match std::fs::write(rc_path, format!("{cleaned}{source_line}")) {
157 Ok(()) => {
158 qprintln!("Updated lean-ctx hook in {}", rc_path.display());
159 }
160 Err(e) => {
161 tracing::error!("Error updating {}: {e}", rc_path.display());
162 print_shell_write_error(rc_path, source_line, &e);
163 }
164 }
165 return;
166 }
167
168 match std::fs::OpenOptions::new()
169 .append(true)
170 .create(true)
171 .open(rc_path)
172 {
173 Ok(mut f) => {
174 use std::io::Write;
175 let _ = f.write_all(source_line.as_bytes());
176 qprintln!("Added lean-ctx hook to {}", rc_path.display());
177 }
178 Err(e) => {
179 tracing::error!("Error writing {}: {e}", rc_path.display());
180 print_shell_write_error(rc_path, source_line, &e);
181 }
182 }
183}
184
185fn print_shell_write_error(rc_path: &std::path::Path, source_line: &str, err: &std::io::Error) {
186 eprintln!();
187 eprintln!(" \x1B[33m⚠ Cannot write to {}\x1B[0m", rc_path.display());
188 eprintln!(" Error: {err}");
189 if err.kind() == std::io::ErrorKind::PermissionDenied {
190 eprintln!();
191 eprintln!(" Your shell config is read-only (nix-darwin, Home Manager, or similar).");
192 eprintln!(" Add the following to a writable shell config file manually:");
193 } else {
194 eprintln!();
195 eprintln!(" Add the following to your shell config manually:");
196 }
197 eprintln!();
198 for line in source_line.lines() {
199 eprintln!(" {line}");
200 }
201 eprintln!();
202 eprintln!(" Or source it from a writable file (e.g. ~/.zshrc.local):");
203 eprintln!(" echo 'source ~/.zshrc.local' # (add to nix config)");
204 eprintln!(" Then add the hook lines to ~/.zshrc.local");
205 eprintln!();
206}
207
208pub fn generate_hook_powershell(binary: &str) -> String {
209 let config = crate::core::config::Config::load();
210 let activation = config.shell_activation_effective();
211 let baked_default = match activation {
212 crate::core::config::ShellActivation::Always => "always",
213 crate::core::config::ShellActivation::AgentsOnly => "agents-only",
214 crate::core::config::ShellActivation::Off => "off",
215 };
216 let binary_escaped = binary.replace('\\', "\\\\");
217 format!(
218 r#"# lean-ctx shell hook — transparent CLI compression (95+ patterns)
219$_leanCtxActivation = if ($env:LEAN_CTX_SHELL_ACTIVATION) {{ $env:LEAN_CTX_SHELL_ACTIVATION }} else {{ "{baked_default}" }}
220$_leanCtxShouldActivate = $false
221if (-not $env:LEAN_CTX_ACTIVE -and -not $env:LEAN_CTX_DISABLED -and -not $env:LEAN_CTX_NO_HOOK) {{
222 switch ($_leanCtxActivation) {{
223 {{ $_ -in 'off','none','manual' }} {{ $_leanCtxShouldActivate = $false }}
224 {{ $_ -in 'agents-only','agents_only','agentsonly' }} {{
225 $_leanCtxShouldActivate = $env:LEAN_CTX_AGENT -or $env:CLAUDECODE -or $env:CODEBUDDY -or $env:CODEX_CLI_SESSION -or $env:GEMINI_SESSION
226 }}
227 default {{ $_leanCtxShouldActivate = $true }}
228 }}
229}}
230if ($_leanCtxShouldActivate) {{
231 $LeanCtxBin = "{binary_escaped}"
232 function _lc {{
233 $nativeCmd = Get-Command $args[0] -CommandType Application -ErrorAction SilentlyContinue
234 if ($env:LEAN_CTX_DISABLED -or $env:LEAN_CTX_NO_HOOK -or [Console]::IsOutputRedirected) {{
235 if ($nativeCmd) {{ & $nativeCmd.Source $args[1..$args.Length] }} else {{ Write-Error "Command not found: $($args[0])" }}
236 return
237 }}
238 & $LeanCtxBin -c @args
239 if ($LASTEXITCODE -eq 127 -or $LASTEXITCODE -eq 126) {{
240 if ($nativeCmd) {{ & $nativeCmd.Source $args[1..$args.Length] }} else {{ Write-Error "Command not found: $($args[0])" }}
241 }}
242 }}
243 function lean-ctx-raw {{ $env:LEAN_CTX_RAW = '1'; & @args; Remove-Item Env:LEAN_CTX_RAW -ErrorAction SilentlyContinue }}
244 if (Get-Command lean-ctx -ErrorAction SilentlyContinue) {{
245 function git {{ _lc git @args }}
246 function cargo {{ _lc cargo @args }}
247 function docker {{ _lc docker @args }}
248 function kubectl {{ _lc kubectl @args }}
249 function gh {{ _lc gh @args }}
250 function pip {{ _lc pip @args }}
251 function pip3 {{ _lc pip3 @args }}
252 function ruff {{ _lc ruff @args }}
253 function go {{ _lc go @args }}
254 function curl {{ _lc curl @args }}
255 function wget {{ _lc wget @args }}
256 foreach ($c in @('npm','pnpm','yarn','eslint','prettier','tsc')) {{
257 if (Get-Command $c -CommandType Application -ErrorAction SilentlyContinue) {{
258 $body = "_lc $c `@args"
259 New-Item -Path "function:$c" -Value ([scriptblock]::Create($body)) -Force | Out-Null
260 }}
261 }}
262 }}
263}}
264"#
265 )
266}
267
268pub fn init_powershell(binary: &str) {
269 let profile_path = if let Some(home) = dirs::home_dir() {
272 let path = crate::shell::platform::powershell_profile_path(&home);
273 if let Some(dir) = path.parent() {
274 let _ = std::fs::create_dir_all(dir);
275 }
276 path
277 } else {
278 tracing::error!("Could not resolve PowerShell profile directory");
279 return;
280 };
281
282 let hook_content = generate_hook_powershell(binary);
283
284 if write_hook_file("shell-hook.ps1", &hook_content).is_some() {
285 upsert_source_line(&profile_path, &source_line_powershell());
286 qprintln!(" Binary: {binary}");
287 }
288}
289
290pub fn remove_lean_ctx_block_ps(content: &str) -> String {
291 let mut result = String::new();
292 let mut in_block = false;
293 let mut brace_depth = 0i32;
294
295 for line in content.lines() {
296 if line.contains("lean-ctx shell hook") {
297 in_block = true;
298 continue;
299 }
300 if in_block {
301 brace_depth += line.matches('{').count() as i32;
302 brace_depth -= line.matches('}').count() as i32;
303 if brace_depth <= 0 && (line.trim() == "}" || line.trim().is_empty()) {
304 if line.trim() == "}" {
305 in_block = false;
306 brace_depth = 0;
307 }
308 continue;
309 }
310 continue;
311 }
312 result.push_str(line);
313 result.push('\n');
314 }
315 result
316}
317
318pub fn generate_hook_fish(binary: &str) -> String {
319 let config = crate::core::config::Config::load();
320 let activation = config.shell_activation_effective();
321 let baked_default = match activation {
322 crate::core::config::ShellActivation::Always => "always",
323 crate::core::config::ShellActivation::AgentsOnly => "agents-only",
324 crate::core::config::ShellActivation::Off => "off",
325 };
326 let alias_list = crate::rewrite_registry::shell_alias_list();
327 format!(
328 "# lean-ctx shell hook — smart shell mode (track-by-default)\n\
329 set -g _lean_ctx_cmds {alias_list}\n\
330 \n\
331 function _lc_is_agent\n\
332 \tset -q LEAN_CTX_AGENT; or set -q CODEX_CLI_SESSION; or set -q CLAUDECODE; or set -q CODEBUDDY; or set -q GEMINI_SESSION\n\
333 end\n\
334 \n\
335 function _lc\n\
336 \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK\n\
337 \t\tcommand $argv\n\
338 \t\treturn\n\
339 \tend\n\
340 \tif not isatty stdout; and not _lc_is_agent\n\
341 \t\tcommand $argv\n\
342 \t\treturn\n\
343 \tend\n\
344 \t'{binary}' -t $argv\n\
345 \tset -l _lc_rc $status\n\
346 \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
347 \t\tcommand $argv\n\
348 \telse\n\
349 \t\treturn $_lc_rc\n\
350 \tend\n\
351 end\n\
352 \n\
353 function _lc_compress\n\
354 \tif set -q LEAN_CTX_DISABLED; or set -q LEAN_CTX_NO_HOOK\n\
355 \t\tcommand $argv\n\
356 \t\treturn\n\
357 \tend\n\
358 \tif not isatty stdout; and not _lc_is_agent\n\
359 \t\tcommand $argv\n\
360 \t\treturn\n\
361 \tend\n\
362 \t'{binary}' -c $argv\n\
363 \tset -l _lc_rc $status\n\
364 \tif test $_lc_rc -eq 127 -o $_lc_rc -eq 126\n\
365 \t\tcommand $argv\n\
366 \telse\n\
367 \t\treturn $_lc_rc\n\
368 \tend\n\
369 end\n\
370 \n\
371 function lean-ctx-on\n\
372 \tfor _lc_cmd in $_lean_ctx_cmds\n\
373 \t\talias $_lc_cmd '_lc '$_lc_cmd\n\
374 \tend\n\
375 \talias k '_lc kubectl'\n\
376 \tset -gx LEAN_CTX_ENABLED 1\n\
377 \tisatty stdout; and echo 'lean-ctx: ON (track mode — output unchanged, token savings recorded)'\n\
378 end\n\
379 \n\
380 function lean-ctx-off\n\
381 \tfor _lc_cmd in $_lean_ctx_cmds\n\
382 \t\tfunctions --erase $_lc_cmd 2>/dev/null; true\n\
383 \tend\n\
384 \tfunctions --erase k 2>/dev/null; true\n\
385 \tset -gx LEAN_CTX_ENABLED 0\n\
386 \tisatty stdout; and echo 'lean-ctx: OFF'\n\
387 end\n\
388 \n\
389 function lean-ctx-mode\n\
390 \tswitch $argv[1]\n\
391 \t\tcase compress\n\
392 \t\t\tfor _lc_cmd in $_lean_ctx_cmds\n\
393 \t\t\t\talias $_lc_cmd '_lc_compress '$_lc_cmd\n\
394 \t\t\t\tend\n\
395 \t\t\talias k '_lc_compress kubectl'\n\
396 \t\t\tset -gx LEAN_CTX_ENABLED 1\n\
397 \t\t\tisatty stdout; and echo 'lean-ctx: COMPRESS mode (all output compressed)'\n\
398 \t\tcase track\n\
399 \t\t\tlean-ctx-on\n\
400 \t\tcase off\n\
401 \t\t\tlean-ctx-off\n\
402 \t\tcase '*'\n\
403 \t\t\techo 'Usage: lean-ctx-mode <track|compress|off>'\n\
404 \t\t\techo ' track — Full output, stats recorded (default)'\n\
405 \t\t\techo ' compress — Compressed output for all commands'\n\
406 \t\t\techo ' off — No aliases, raw shell'\n\
407 \tend\n\
408 end\n\
409 \n\
410 function lean-ctx-raw\n\
411 \tset -lx LEAN_CTX_RAW 1\n\
412 \tcommand $argv\n\
413 end\n\
414 \n\
415 function lean-ctx-status\n\
416 \tif set -q LEAN_CTX_DISABLED\n\
417 \t\tisatty stdout; and echo 'lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)'\n\
418 \telse if set -q LEAN_CTX_ENABLED\n\
419 \t\tisatty stdout; and echo 'lean-ctx: ON'\n\
420 \telse\n\
421 \t\tisatty stdout; and echo 'lean-ctx: OFF'\n\
422 \tend\n\
423 end\n\
424 \n\
425 function _lean_ctx_should_activate\n\
426 \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\
427 \t\treturn 1\n\
428 \tend\n\
429 \tset -l _lc_mode (set -q LEAN_CTX_SHELL_ACTIVATION; and echo $LEAN_CTX_SHELL_ACTIVATION; or echo '{baked_default}')\n\
430 \tswitch $_lc_mode\n\
431 \t\tcase off none manual\n\
432 \t\t\treturn 1\n\
433 \t\tcase 'agents-only' agents_only agentsonly\n\
434 \t\t\tif set -q LEAN_CTX_AGENT; or set -q CLAUDECODE; or set -q CODEBUDDY; or set -q CODEX_CLI_SESSION; or set -q GEMINI_SESSION\n\
435 \t\t\t\treturn 0\n\
436 \t\t\tend\n\
437 \t\t\treturn 1\n\
438 \t\tcase '*'\n\
439 \t\t\treturn 0\n\
440 \tend\n\
441 end\n\
442 \n\
443 if _lean_ctx_should_activate\n\
444 \tif command -q lean-ctx\n\
445 \t\tlean-ctx-on\n\
446 \tend\n\
447 end\n"
448 )
449}
450
451pub fn init_fish(binary: &str) {
452 let config = dirs::home_dir()
453 .map(|h| h.join(".config/fish/config.fish"))
454 .unwrap_or_default();
455
456 let hook_content = generate_hook_fish(binary);
457
458 if write_hook_file("shell-hook.fish", &hook_content).is_some() {
459 upsert_source_line(&config, &source_line_fish());
460 qprintln!(" Binary: {binary}");
461 }
462}
463
464pub fn generate_hook_posix(binary: &str) -> String {
465 let config = crate::core::config::Config::load();
466 let activation = config.shell_activation_effective();
467 let baked_default = match activation {
468 crate::core::config::ShellActivation::Always => "always",
469 crate::core::config::ShellActivation::AgentsOnly => "agents-only",
470 crate::core::config::ShellActivation::Off => "off",
471 };
472 let alias_list = crate::rewrite_registry::shell_alias_list();
473 format!(
474 r#"# lean-ctx shell hook — smart shell mode (track-by-default)
475_lean_ctx_cmds=({alias_list})
476
477_lc_is_agent() {{
478 [ -n "${{LEAN_CTX_AGENT:-}}" ] || [ -n "${{CODEX_CLI_SESSION:-}}" ] || [ -n "${{CLAUDECODE:-}}" ] || [ -n "${{CODEBUDDY:-}}" ] || [ -n "${{GEMINI_SESSION:-}}" ]
479}}
480
481_lc() {{
482 if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ]; then
483 command "$@"
484 return
485 fi
486 if [ ! -t 1 ] && ! _lc_is_agent; then
487 command "$@"
488 return
489 fi
490 '{binary}' -t "$@"
491 local _lc_rc=$?
492 if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
493 command "$@"
494 else
495 return "$_lc_rc"
496 fi
497}}
498
499_lc_compress() {{
500 if [ -n "${{LEAN_CTX_DISABLED:-}}" ] || [ -n "${{LEAN_CTX_NO_HOOK:-}}" ]; then
501 command "$@"
502 return
503 fi
504 if [ ! -t 1 ] && ! _lc_is_agent; then
505 command "$@"
506 return
507 fi
508 '{binary}' -c "$@"
509 local _lc_rc=$?
510 if [ "$_lc_rc" -eq 127 ] || [ "$_lc_rc" -eq 126 ]; then
511 command "$@"
512 else
513 return "$_lc_rc"
514 fi
515}}
516
517lean-ctx-on() {{
518 for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
519 # shellcheck disable=SC2139
520 alias "$_lc_cmd"='_lc '"$_lc_cmd"
521 done
522 alias k='_lc kubectl'
523 export LEAN_CTX_ENABLED=1
524 [ -t 1 ] && echo "lean-ctx: ON (track mode — output unchanged, token savings recorded)"
525}}
526
527lean-ctx-off() {{
528 for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
529 unalias "$_lc_cmd" 2>/dev/null || true
530 done
531 unalias k 2>/dev/null || true
532 export LEAN_CTX_ENABLED=0
533 [ -t 1 ] && echo "lean-ctx: OFF"
534}}
535
536lean-ctx-mode() {{
537 case "${{1:-}}" in
538 compress)
539 for _lc_cmd in "${{_lean_ctx_cmds[@]}}"; do
540 # shellcheck disable=SC2139
541 alias "$_lc_cmd"='_lc_compress '"$_lc_cmd"
542 done
543 alias k='_lc_compress kubectl'
544 export LEAN_CTX_ENABLED=1
545 [ -t 1 ] && echo "lean-ctx: COMPRESS mode (all output compressed)"
546 ;;
547 track)
548 lean-ctx-on
549 ;;
550 off)
551 lean-ctx-off
552 ;;
553 *)
554 echo "Usage: lean-ctx-mode <track|compress|off>"
555 echo " track — Full output, stats recorded (default)"
556 echo " compress — Compressed output for all commands"
557 echo " off — No aliases, raw shell"
558 ;;
559 esac
560}}
561
562lean-ctx-raw() {{
563 LEAN_CTX_RAW=1 command "$@"
564}}
565
566lean-ctx-status() {{
567 if [ -n "${{LEAN_CTX_DISABLED:-}}" ]; then
568 [ -t 1 ] && echo "lean-ctx: DISABLED (LEAN_CTX_DISABLED is set)"
569 elif [ -n "${{LEAN_CTX_ENABLED:-}}" ]; then
570 [ -t 1 ] && echo "lean-ctx: ON"
571 else
572 [ -t 1 ] && echo "lean-ctx: OFF"
573 fi
574}}
575
576if [ -n "${{ZSH_VERSION:-}}" ]; then
577 _lean_ctx_comp() {{
578 shift words
579 (( CURRENT-- ))
580 _normal
581 }}
582 compdef _lean_ctx_comp _lc 2>/dev/null
583 compdef _lean_ctx_comp _lc_compress 2>/dev/null
584fi
585
586_lean_ctx_should_activate() {{
587 [ -z "${{LEAN_CTX_ACTIVE:-}}" ] && [ -z "${{LEAN_CTX_DISABLED:-}}" ] && [ "${{LEAN_CTX_ENABLED:-1}}" != "0" ] || return 1
588 case "${{LEAN_CTX_SHELL_ACTIVATION:-{baked_default}}}" in
589 off|none|manual) return 1 ;;
590 agents-only|agents_only|agentsonly)
591 [ -n "${{LEAN_CTX_AGENT:-}}" ] || [ -n "${{CLAUDECODE:-}}" ] || [ -n "${{CODEBUDDY:-}}" ] || [ -n "${{CODEX_CLI_SESSION:-}}" ] || [ -n "${{GEMINI_SESSION:-}}" ] ;;
592 *) return 0 ;;
593 esac
594}}
595
596if _lean_ctx_should_activate; then
597 command -v lean-ctx >/dev/null 2>&1 && lean-ctx-on
598fi
599"#
600 )
601}
602
603pub fn init_posix(is_zsh: bool, binary: &str) {
604 let rc_file = if is_zsh {
605 dirs::home_dir()
606 .map(|h| h.join(".zshrc"))
607 .unwrap_or_default()
608 } else {
609 dirs::home_dir()
610 .map(|h| h.join(".bashrc"))
611 .unwrap_or_default()
612 };
613
614 let shell_ext = if is_zsh { "zsh" } else { "bash" };
615 let hook_content = generate_hook_posix(binary);
616
617 if let Some(hook_path) = write_hook_file(&format!("shell-hook.{shell_ext}"), &hook_content) {
618 upsert_source_line(&rc_file, &source_line_posix(shell_ext));
619
620 if !is_zsh {
623 ensure_bash_login_sources_bashrc();
624 }
625
626 qprintln!(" Binary: {binary}");
627
628 write_env_sh_for_containers(&hook_content);
629 print_docker_env_hints(is_zsh);
630
631 let _ = hook_path;
632 }
633}
634
635fn ensure_bash_login_sources_bashrc() {
642 let Some(home) = dirs::home_dir() else {
643 return;
644 };
645
646 let target = [".bash_profile", ".bash_login", ".profile"]
649 .iter()
650 .map(|f| home.join(f))
651 .find(|p| p.exists())
652 .unwrap_or_else(|| home.join(".bash_profile"));
653
654 if let Ok(existing) = std::fs::read_to_string(&target) {
656 let sources_bashrc = existing
657 .lines()
658 .any(|l| !l.trim_start().starts_with('#') && l.contains(".bashrc"));
659 if sources_bashrc {
660 return;
661 }
662 }
663
664 let snippet = "\n# lean-ctx: load ~/.bashrc in login shells (e.g. macOS Terminal) — begin\n\
665 if [ -f \"$HOME/.bashrc\" ]; then . \"$HOME/.bashrc\"; fi\n\
666 # lean-ctx: load ~/.bashrc in login shells (e.g. macOS Terminal) — end\n";
667
668 backup_shell_config(&target);
669 match std::fs::OpenOptions::new()
670 .append(true)
671 .create(true)
672 .open(&target)
673 {
674 Ok(mut f) => {
675 use std::io::Write;
676 if f.write_all(snippet.as_bytes()).is_ok() {
677 qprintln!(" Login shell: {} now sources ~/.bashrc", target.display());
678 }
679 }
680 Err(e) => {
681 tracing::warn!("could not update {}: {e}", target.display());
682 }
683 }
684}
685
686pub fn write_env_sh_for_containers(aliases: &str) {
687 let env_sh = match crate::core::paths::config_dir() {
689 Ok(d) => d.join("env.sh"),
690 Err(_) => return,
691 };
692 if let Some(parent) = env_sh.parent() {
693 let _ = std::fs::create_dir_all(parent);
694 }
695 let sanitized_aliases = crate::core::sanitize::neutralize_shell_content(aliases);
696 let mut content = String::from(
697 r#"# lean-ctx: passthrough stubs for non-interactive subshells (fixes #255).
698# These ensure _lc/_lc_compress exist so inherited aliases don't break.
699# The full hook definitions override these when the interactive shell loads.
700_lc() { command "$@"; }
701_lc_compress() { command "$@"; }
702
703"#,
704 );
705 content.push_str(&sanitized_aliases);
706 content.push_str(
707 r#"
708
709# lean-ctx docker self-heal: re-inject Claude MCP config if Claude overwrote ~/.claude.json
710# Guards: container-only + no recursion + no re-entry via BASH_ENV + 60s cooldown + PID-lock
711if [ -f /.dockerenv ] || grep -qsE '/docker/|/lxc/' /proc/1/cgroup 2>/dev/null; then
712 if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ -z "${_LEAN_CTX_HEAL:-}" ]; then
713 # XDG-only paths (GL #623): never touch ~/.lean-ctx, which would re-collapse
714 # a committed XDG layout. heal_ts is STATE, locks live in the DATA dir
715 # (matches process_guard::lock_dir defaults).
716 _LEAN_CTX_STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/lean-ctx"
717 _LEAN_CTX_HEAL_TS="${_LEAN_CTX_STATE_DIR}/.heal_ts"
718 _LEAN_CTX_HEAL_COOLDOWN=60
719 _lean_ctx_heal_needed=1
720 if [ -f "$_LEAN_CTX_HEAL_TS" ]; then
721 _last_heal=$(cat "$_LEAN_CTX_HEAL_TS" 2>/dev/null || echo 0)
722 _now=$(date +%s 2>/dev/null || echo 0)
723 if [ $(( _now - _last_heal )) -lt $_LEAN_CTX_HEAL_COOLDOWN ]; then
724 _lean_ctx_heal_needed=0
725 fi
726 fi
727 _lean_ctx_lock_count=0
728 for _lf in "${XDG_DATA_HOME:-$HOME/.local/share}/lean-ctx/locks"/slot-*.lock; do
729 [ -f "$_lf" ] && _lean_ctx_lock_count=$(( _lean_ctx_lock_count + 1 ))
730 done
731 if [ "$_lean_ctx_heal_needed" = "1" ] && [ "$_lean_ctx_lock_count" -lt 4 ]; then
732 export _LEAN_CTX_HEAL=1
733 if command -v claude >/dev/null 2>&1 && command -v lean-ctx >/dev/null 2>&1; then
734 if ! claude mcp list 2>/dev/null | grep -q "lean-ctx"; then
735 LEAN_CTX_ACTIVE=1 LEAN_CTX_QUIET=1 lean-ctx init --agent claude >/dev/null 2>&1
736 mkdir -p "$_LEAN_CTX_STATE_DIR" 2>/dev/null
737 date +%s > "$_LEAN_CTX_HEAL_TS" 2>/dev/null
738 fi
739 fi
740 fi
741 fi
742fi
743"#,
744 );
745 match std::fs::write(&env_sh, content) {
746 Ok(()) => {
747 if !super::quiet_enabled() {
749 eprintln!(" env.sh: {}", env_sh.display());
750 }
751 }
752 Err(e) => tracing::warn!("could not write {}: {e}", env_sh.display()),
753 }
754}
755
756fn print_docker_env_hints(is_zsh: bool) {
757 if is_zsh || !crate::shell::is_container() {
758 return;
759 }
760 let env_sh = crate::core::paths::config_dir().map_or_else(
761 |_| "/root/.config/lean-ctx/env.sh".to_string(),
762 |d| d.join("env.sh").to_string_lossy().to_string(),
763 );
764
765 let has_bash_env = std::env::var("BASH_ENV").is_ok();
766 let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
767
768 if has_bash_env && has_claude_env {
769 return;
770 }
771
772 eprintln!();
773 eprintln!(" \x1b[33m⚠ Docker detected — environment hints:\x1b[0m");
774
775 if !has_bash_env {
776 eprintln!(" For generic bash -c usage (non-interactive shells):");
777 eprintln!(" \x1b[1mENV BASH_ENV=\"{env_sh}\"\x1b[0m");
778 }
779 if !has_claude_env {
780 eprintln!(" For Claude Code (sources before each command):");
781 eprintln!(" \x1b[1mENV CLAUDE_ENV_FILE=\"{env_sh}\"\x1b[0m");
782 }
783 eprintln!();
784}
785
786pub fn remove_lean_ctx_block(content: &str) -> String {
787 if content.contains("# lean-ctx shell hook — end") {
788 return remove_lean_ctx_block_by_marker(content);
789 }
790 remove_lean_ctx_block_legacy(content)
791}
792
793fn remove_lean_ctx_block_by_marker(content: &str) -> String {
794 let mut result = String::new();
795 let mut in_block = false;
796
797 for line in content.lines() {
798 if !in_block && line.contains("lean-ctx shell hook") && !line.contains("end") {
799 in_block = true;
800 continue;
801 }
802 if in_block {
803 if line.trim() == "# lean-ctx shell hook — end" {
804 in_block = false;
805 }
806 continue;
807 }
808 result.push_str(line);
809 result.push('\n');
810 }
811 result
812}
813
814fn remove_lean_ctx_block_legacy(content: &str) -> String {
815 let mut result = String::new();
816 let mut in_block = false;
817
818 for line in content.lines() {
819 if line.contains("lean-ctx shell hook") {
820 in_block = true;
821 continue;
822 }
823 if in_block {
824 if line.trim() == "fi" || line.trim() == "end" || line.trim().is_empty() {
825 if line.trim() == "fi" || line.trim() == "end" {
826 in_block = false;
827 }
828 continue;
829 }
830 if !line.starts_with("alias ") && !line.starts_with('\t') && !line.starts_with("if ") {
831 in_block = false;
832 result.push_str(line);
833 result.push('\n');
834 }
835 continue;
836 }
837 result.push_str(line);
838 result.push('\n');
839 }
840 result
841}
842
843#[cfg(test)]
844mod tests {
845 use super::*;
846
847 #[test]
848 fn test_remove_lean_ctx_block_posix() {
849 let input = r#"# existing config
850export PATH="$HOME/bin:$PATH"
851
852# lean-ctx shell hook — transparent CLI compression (95+ patterns)
853if [ -z "$LEAN_CTX_ACTIVE" ]; then
854alias git='lean-ctx -c git'
855alias npm='lean-ctx -c npm'
856fi
857
858# other stuff
859export EDITOR=vim
860"#;
861 let result = remove_lean_ctx_block(input);
862 assert!(!result.contains("lean-ctx"), "block should be removed");
863 assert!(result.contains("export PATH"), "other content preserved");
864 assert!(
865 result.contains("export EDITOR"),
866 "trailing content preserved"
867 );
868 }
869
870 #[test]
871 fn test_remove_lean_ctx_block_fish() {
872 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";
873 let result = remove_lean_ctx_block(input);
874 assert!(!result.contains("lean-ctx"), "block should be removed");
875 assert!(result.contains("set -x FOO"), "other content preserved");
876 assert!(result.contains("set -x BAZ"), "trailing content preserved");
877 }
878
879 #[test]
880 fn test_remove_lean_ctx_block_ps() {
881 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";
882 let result = remove_lean_ctx_block_ps(input);
883 assert!(
884 !result.contains("lean-ctx shell hook"),
885 "block should be removed"
886 );
887 assert!(result.contains("$env:FOO"), "other content preserved");
888 assert!(result.contains("$env:EDITOR"), "trailing content preserved");
889 }
890
891 #[test]
892 fn test_remove_lean_ctx_block_ps_nested() {
893 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";
894 let result = remove_lean_ctx_block_ps(input);
895 assert!(
896 !result.contains("lean-ctx shell hook"),
897 "block should be removed"
898 );
899 assert!(!result.contains("_lc"), "function should be removed");
900 assert!(result.contains("$env:FOO"), "other content preserved");
901 assert!(result.contains("$env:EDITOR"), "trailing content preserved");
902 }
903
904 #[test]
905 fn test_remove_block_no_lean_ctx() {
906 let input = "# normal bashrc\nexport PATH=\"$HOME/bin:$PATH\"\n";
907 let result = remove_lean_ctx_block(input);
908 assert!(result.contains("export PATH"), "content unchanged");
909 }
910
911 #[test]
912 fn test_bash_hook_contains_pipe_guard_and_agent_bypass() {
913 let output = generate_hook_posix("/usr/local/bin/lean-ctx");
914 assert!(
915 output.contains("! -t 1"),
916 "bash/zsh hook must contain pipe guard [ ! -t 1 ]"
917 );
918 assert!(
919 output.contains("_lc_is_agent"),
920 "bash/zsh hook must have agent-aware bypass"
921 );
922 assert!(
923 output.contains("CODEX_CLI_SESSION"),
924 "agent check must include CODEX_CLI_SESSION"
925 );
926 }
927
928 #[test]
929 fn test_lc_uses_track_mode_by_default() {
930 let binary = "/usr/local/bin/lean-ctx";
931 let alias_list = crate::rewrite_registry::shell_alias_list();
932 let aliases = format!(
933 r#"_lc() {{
934 '{binary}' -t "$@"
935}}
936_lc_compress() {{
937 '{binary}' -c "$@"
938}}"#
939 );
940 assert!(
941 aliases.contains("-t \"$@\""),
942 "_lc must use -t (track mode) by default"
943 );
944 assert!(
945 aliases.contains("-c \"$@\""),
946 "_lc_compress must use -c (compress mode)"
947 );
948 let _ = alias_list;
949 }
950
951 #[test]
952 fn test_posix_shell_has_lean_ctx_mode() {
953 let alias_list = crate::rewrite_registry::shell_alias_list();
954 let aliases = r#"
955lean-ctx-mode() {{
956 case "${{1:-}}" in
957 compress) echo compress ;;
958 track) echo track ;;
959 off) echo off ;;
960 esac
961}}
962"#
963 .to_string();
964 assert!(
965 aliases.contains("lean-ctx-mode()"),
966 "lean-ctx-mode function must exist"
967 );
968 assert!(
969 aliases.contains("compress"),
970 "compress mode must be available"
971 );
972 assert!(aliases.contains("track"), "track mode must be available");
973 let _ = alias_list;
974 }
975
976 #[test]
977 fn test_fish_hook_contains_pipe_guard_and_agent_bypass() {
978 let output = generate_hook_fish("/usr/local/bin/lean-ctx");
979 assert!(
980 output.contains("isatty stdout"),
981 "fish hook must contain pipe guard (isatty stdout)"
982 );
983 assert!(
984 output.contains("_lc_is_agent"),
985 "fish hook must have agent-aware bypass"
986 );
987 }
988
989 #[test]
990 fn test_powershell_hook_contains_pipe_guard() {
991 let hook = "function _lc { if ($env:LEAN_CTX_DISABLED -or [Console]::IsOutputRedirected) { & @args; return } }";
992 assert!(
993 hook.contains("IsOutputRedirected"),
994 "PowerShell hook must contain pipe guard ([Console]::IsOutputRedirected)"
995 );
996 }
997
998 #[test]
999 fn powershell_hook_binary_is_native_not_msys() {
1000 let win = "C:/Users/Dawid/.cargo/bin/lean-ctx.exe";
1003 assert_eq!(hook_binary_for_shell("powershell", win), win);
1004 assert_eq!(hook_binary_for_shell("pwsh", win), win);
1005 assert!(!hook_binary_for_shell("powershell", win).contains("/c/"));
1006 }
1007
1008 #[test]
1009 fn posix_hook_binary_keeps_msys_form_on_windows_drive() {
1010 let win = "C:/Users/Dawid/.cargo/bin/lean-ctx.exe";
1013 let msys = "/c/Users/Dawid/.cargo/bin/lean-ctx.exe";
1014 assert_eq!(hook_binary_for_shell("bash", win), msys);
1015 assert_eq!(hook_binary_for_shell("zsh", win), msys);
1016 assert_eq!(hook_binary_for_shell("fish", win), msys);
1017 }
1018
1019 #[test]
1020 fn test_remove_lean_ctx_block_new_format_with_end_marker() {
1021 let input = r#"# existing config
1022export PATH="$HOME/bin:$PATH"
1023
1024# lean-ctx shell hook — transparent CLI compression (95+ patterns)
1025_lean_ctx_cmds=(git npm pnpm)
1026
1027lean-ctx-on() {
1028 for _lc_cmd in "${_lean_ctx_cmds[@]}"; do
1029 alias "$_lc_cmd"='lean-ctx -c '"$_lc_cmd"
1030 done
1031 export LEAN_CTX_ENABLED=1
1032 [ -t 1 ] && echo "lean-ctx: ON"
1033}
1034
1035lean-ctx-off() {
1036 export LEAN_CTX_ENABLED=0
1037 [ -t 1 ] && echo "lean-ctx: OFF"
1038}
1039
1040if [ -z "${LEAN_CTX_ACTIVE:-}" ] && [ "${LEAN_CTX_ENABLED:-1}" != "0" ]; then
1041 lean-ctx-on
1042fi
1043# lean-ctx shell hook — end
1044
1045# other stuff
1046export EDITOR=vim
1047"#;
1048 let result = remove_lean_ctx_block(input);
1049 assert!(!result.contains("lean-ctx-on"), "block should be removed");
1050 assert!(!result.contains("lean-ctx shell hook"), "marker removed");
1051 assert!(result.contains("export PATH"), "other content preserved");
1052 assert!(
1053 result.contains("export EDITOR"),
1054 "trailing content preserved"
1055 );
1056 }
1057
1058 #[test]
1059 fn env_sh_for_containers_includes_self_heal() {
1060 let _g = crate::core::data_dir::test_env_lock();
1061 let tmp = tempfile::tempdir().expect("tempdir");
1062 let config_dir = tmp.path().join("config");
1064 std::fs::create_dir_all(&config_dir).expect("mkdir config");
1065 crate::test_env::set_var("LEAN_CTX_CONFIG_DIR", &config_dir);
1066
1067 write_env_sh_for_containers("alias git='lean-ctx -c git'\n");
1068 let env_sh = config_dir.join("env.sh");
1069 let content = std::fs::read_to_string(&env_sh).expect("env.sh exists");
1070 if !cfg!(windows)
1071 && let Ok(mut bash) = std::process::Command::new("bash")
1072 .arg("-n")
1073 .arg(&env_sh)
1074 .spawn()
1075 {
1076 let ok = bash.wait().is_ok_and(|s| s.success());
1077 assert!(ok, "generated env.sh must be valid bash");
1078 }
1079 assert!(
1080 content.contains(r#"_lc() { command "$@"; }"#),
1081 "env.sh must contain _lc passthrough stub for non-interactive shells"
1082 );
1083 assert!(
1084 content.contains(r#"_lc_compress() { command "$@"; }"#),
1085 "env.sh must contain _lc_compress passthrough stub"
1086 );
1087 assert!(content.contains("lean-ctx docker self-heal"));
1088 assert!(content.contains("claude mcp list"));
1089 assert!(content.contains("lean-ctx init --agent claude"));
1090 assert!(
1091 content.contains("_LEAN_CTX_HEAL"),
1092 "env.sh must guard against recursive self-heal"
1093 );
1094 assert!(
1095 content.contains("LEAN_CTX_ACTIVE"),
1096 "env.sh must check LEAN_CTX_ACTIVE to prevent re-entry"
1097 );
1098 assert!(
1099 content.contains("/.dockerenv"),
1100 "env.sh self-heal must be gated to container environments"
1101 );
1102 assert!(
1106 !content.contains("$HOME/.lean-ctx") && !content.contains("${HOME}/.lean-ctx"),
1107 "self-heal must not touch ~/.lean-ctx (GL #623)"
1108 );
1109 assert!(
1110 content.contains("${XDG_STATE_HOME:-$HOME/.local/state}/lean-ctx"),
1111 "heal_ts must live under the XDG state dir"
1112 );
1113 assert!(
1114 content.contains("${XDG_DATA_HOME:-$HOME/.local/share}/lean-ctx/locks"),
1115 "lock count must read the XDG data lock dir"
1116 );
1117
1118 crate::test_env::remove_var("LEAN_CTX_CONFIG_DIR");
1119 }
1120
1121 #[cfg(unix)]
1122 #[test]
1123 fn bash_login_profile_sources_bashrc_idempotently() {
1124 let _g = crate::core::data_dir::test_env_lock();
1125 let tmp = tempfile::tempdir().expect("tempdir");
1126 let home = tmp.path();
1127 let prev = std::env::var_os("HOME");
1128 crate::test_env::set_var("HOME", home);
1129
1130 std::fs::write(home.join(".bashrc"), "# bashrc\n").expect("write .bashrc");
1131 ensure_bash_login_sources_bashrc();
1134 let profile = home.join(".bash_profile");
1135 let first = std::fs::read_to_string(&profile).expect(".bash_profile created");
1136 assert!(
1137 first.contains(". \"$HOME/.bashrc\""),
1138 "login profile must source ~/.bashrc: {first}"
1139 );
1140 let markers = first.matches("load ~/.bashrc in login shells").count();
1141
1142 ensure_bash_login_sources_bashrc();
1144 let second = std::fs::read_to_string(&profile).expect("read profile");
1145 assert_eq!(
1146 second.matches("load ~/.bashrc in login shells").count(),
1147 markers,
1148 "snippet must not be duplicated on re-run"
1149 );
1150
1151 match prev {
1152 Some(v) => crate::test_env::set_var("HOME", v),
1153 None => crate::test_env::remove_var("HOME"),
1154 }
1155 }
1156
1157 #[test]
1158 fn test_source_line_posix() {
1159 let line = source_line_posix("zsh");
1160 assert!(line.contains("shell-hook.zsh"));
1161 assert!(line.contains("[ -f"));
1162 }
1163
1164 #[test]
1165 fn test_source_line_fish() {
1166 let line = source_line_fish();
1167 assert!(line.contains("shell-hook.fish"));
1168 assert!(line.contains("source"));
1169 }
1170
1171 #[test]
1172 fn test_source_line_powershell() {
1173 let line = source_line_powershell();
1174 assert!(line.contains("shell-hook.ps1"));
1175 assert!(line.contains("Test-Path"));
1176 }
1177}