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