1use fs2::FileExt;
3use std::io::Read;
4use std::process::Stdio;
5use std::sync::{Arc, Mutex, atomic::AtomicBool, mpsc};
6use std::time::{Duration, Instant};
7
8const READER_RESULT_TIMEOUT: Duration = Duration::from_secs(2);
9
10const TIMEOUT_MARKER: &str = "ERROR: command timed out after ";
12
13fn is_build_or_test_command(command: &str) -> bool {
14 let tokens: Vec<_> = command
15 .split(|ch: char| ch.is_ascii_whitespace() || matches!(ch, ';' | '&' | '|'))
16 .filter(|token| !token.is_empty())
17 .collect();
18 tokens.windows(2).any(|pair| {
19 let tool = std::path::Path::new(pair[0])
20 .file_name()
21 .and_then(|name| name.to_str())
22 .unwrap_or(pair[0]);
23 (tool == "cargo"
24 && matches!(
25 pair[1],
26 "build" | "check" | "clippy" | "test" | "run" | "bench" | "install" | "fast"
27 ))
28 || (matches!(tool, "npm" | "pnpm" | "yarn" | "bun")
29 && matches!(pair[1], "test" | "build" | "check"))
30 || (tool == "lean-ctx" && pair[1] == "dev-install")
31 || (matches!(tool, "make" | "gmake")
32 && matches!(
33 pair[1],
34 "build"
35 | "check"
36 | "dev"
37 | "install"
38 | "install-release"
39 | "test"
40 | "preflight"
41 | "preflight-fast"
42 ))
43 }) || tokens.windows(3).any(|triple| {
44 matches!(triple[0], "npm" | "pnpm" | "yarn" | "bun")
45 && triple[1] == "run"
46 && matches!(triple[2], "test" | "build" | "check" | "lint" | "typecheck")
47 }) || tokens.iter().any(|token| {
48 std::path::Path::new(token)
49 .file_name()
50 .and_then(|name| name.to_str())
51 .is_some_and(|name| matches!(name, "rustc" | "dev-install.sh" | "install.sh"))
52 })
53}
54
55fn acquire_build_lease(
56 command: &str,
57 cancel: Option<&AtomicBool>,
58) -> Result<Option<lean_ctx::core::file_lock::FlockGuard>, String> {
59 let config = lean_ctx::core::config::Config::load();
60 if !config.agents.serialize_build_commands || !is_build_or_test_command(command) {
61 return Ok(None);
62 }
63 let dir = lean_ctx::core::data_dir::lean_ctx_data_dir()?.join("resources");
64 std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
65 let path = dir.join("build.lock");
66 let file = std::fs::OpenOptions::new()
67 .create(true)
68 .truncate(false)
69 .read(true)
70 .write(true)
71 .open(&path)
72 .map_err(|error| format!("open build lease {}: {error}", path.display()))?;
73 loop {
74 match file.try_lock_exclusive() {
75 Ok(()) => {
76 return Ok(Some(lean_ctx::core::file_lock::FlockGuard::from_locked(
77 file,
78 )));
79 }
80 Err(error) if lock_is_contended(&error) => {
81 if cancel.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire)) {
82 return Err(
83 "build cancelled while waiting for the machine-wide slot".to_string()
84 );
85 }
86 std::thread::sleep(Duration::from_millis(100));
87 }
88 Err(error) => {
89 return Err(format!("acquire build lease {}: {error}", path.display()));
90 }
91 }
92 }
93}
94
95fn lock_is_contended(error: &std::io::Error) -> bool {
96 error.kind() == std::io::ErrorKind::WouldBlock
97 || cfg!(windows) && matches!(error.raw_os_error(), Some(32 | 33))
98}
99
100pub(crate) fn output_before_timeout_marker(output: &str) -> Option<&str> {
110 output.find(TIMEOUT_MARKER).map(|idx| output[..idx].trim())
111}
112
113#[cfg(test)]
114pub(crate) fn execute_command_in(command: &str, cwd: &str) -> (String, i32) {
115 execute_command_with_env(command, cwd, &std::collections::HashMap::new(), None)
116}
117
118#[cfg(test)]
119pub(crate) fn execute_command_with_env(
120 command: &str,
121 cwd: &str,
122 extra_env: &std::collections::HashMap<String, String>,
123 timeout_ms: Option<u64>,
124) -> (String, i32) {
125 execute_command_with_env_cancellable(command, cwd, extra_env, timeout_ms, None, false, None)
126}
127
128pub(crate) struct ShellExecution {
146 pub output: String,
147 pub exit_code: i32,
148 pub completeness: lean_ctx::core::context_admission::OutputCompleteness,
149 pub notice: Option<&'static str>,
155}
156
157pub(crate) fn with_notice(notice: Option<&'static str>, text: String) -> String {
160 match notice {
161 Some(notice) => format!("{notice}\n{text}"),
162 None => text,
163 }
164}
165
166#[cfg(unix)]
170fn split_notice(text: String) -> (Option<&'static str>, String) {
171 match leading_notice(&text) {
172 Some(notice) => {
173 let rest = text.get(notice.len() + 1..).unwrap_or_default().to_string();
174 (Some(notice), rest)
175 }
176 None => (None, text),
177 }
178}
179
180#[cfg(unix)]
182pub(crate) fn leading_notice(text: &str) -> Option<&'static str> {
183 use lean_ctx::shell::containment::{END_NOTICE, HELPER_NOTICE, RELEASE_NOTICE, UNCLEAR_NOTICE};
184 [HELPER_NOTICE, END_NOTICE, UNCLEAR_NOTICE, RELEASE_NOTICE]
185 .into_iter()
186 .find(|notice| {
187 text.strip_prefix(notice)
188 .is_some_and(|rest| rest.is_empty() || rest.starts_with('\n'))
189 })
190}
191
192#[cfg(not(unix))]
194pub(crate) fn leading_notice(_text: &str) -> Option<&'static str> {
195 None
196}
197
198pub(crate) fn keep_notice(notice: Option<&'static str>, text: String) -> String {
202 if leading_notice(&text).is_some() {
203 text
204 } else {
205 with_notice(notice, text)
206 }
207}
208
209impl ShellExecution {
210 fn complete(output: String, exit_code: i32) -> Self {
211 Self {
212 output,
213 exit_code,
214 completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
215 notice: None,
216 }
217 }
218
219 #[cfg(unix)]
222 fn unknown_capture(output: String, exit_code: i32) -> Self {
223 Self {
224 output,
225 exit_code,
226 completeness: lean_ctx::core::context_admission::OutputCompleteness {
227 reader_incomplete: true,
228 ..lean_ctx::core::context_admission::OutputCompleteness::complete()
229 },
230 notice: None,
231 }
232 }
233}
234
235#[cfg(unix)]
239pub fn register_protected_shell_runner() {
240 lean_ctx_ext::core::protected_execution::register_shell_runner(
241 execute_command_with_env_cancellable,
242 );
243}
244
245#[cfg(any(unix, test))]
248pub(crate) fn execute_command_with_env_cancellable(
249 command: &str,
250 cwd: &str,
251 extra_env: &std::collections::HashMap<String, String>,
252 timeout_ms: Option<u64>,
253 cancel: Option<&AtomicBool>,
254 idle_keyed: bool,
255 live: Option<&std::sync::Mutex<String>>,
256) -> (String, i32) {
257 let _ = live;
260 let execution = execute_command_with_env_cancellable_captured(
261 command, cwd, extra_env, timeout_ms, cancel, idle_keyed,
262 );
263 (
265 with_notice(execution.notice, execution.output),
266 execution.exit_code,
267 )
268}
269
270#[cfg(all(test, unix))]
273pub(crate) fn execute_command_with_env_captured(
274 command: &str,
275 cwd: &str,
276 extra_env: &std::collections::HashMap<String, String>,
277 timeout_ms: Option<u64>,
278) -> ShellExecution {
279 execute_command_with_env_cancellable_captured(command, cwd, extra_env, timeout_ms, None, false)
280}
281
282pub(crate) fn execute_command_with_env_cancellable_captured(
283 command: &str,
284 cwd: &str,
285 extra_env: &std::collections::HashMap<String, String>,
286 timeout_ms: Option<u64>,
287 cancel: Option<&AtomicBool>,
288 idle_keyed: bool,
289) -> ShellExecution {
290 #[cfg(unix)]
305 let protected_prefix: Option<Vec<String>> = {
306 use lean_ctx_ext::core::protected_execution::{Mode, launch_mode, sandbox_prefix};
307 match launch_mode() {
308 Err(error) => return ShellExecution::complete(format!("ERROR: {error}"), 1),
309 Ok(Mode::Brokered(client)) => {
310 let (output, exit_code) = client.shell(
311 command, cwd, extra_env, timeout_ms, cancel, idle_keyed, None,
312 );
313 let (notice, output) = split_notice(output);
314 return ShellExecution {
315 notice,
316 ..ShellExecution::unknown_capture(output, exit_code)
317 };
318 }
319 Ok(Mode::Sandboxed(profile)) => Some(sandbox_prefix(&profile)),
320 Ok(Mode::Direct) => None,
321 }
322 };
323 #[cfg(not(unix))]
324 let protected_prefix = match lean_ctx::core::protected_store::protected_child_prefix() {
325 Ok(prefix) => prefix,
326 Err(error) => return ShellExecution::complete(format!("ERROR: {error}"), 1),
327 };
328
329 let _build_lease = match acquire_build_lease(command, cancel) {
330 Ok(lease) => lease,
331 Err(error) => return ShellExecution::complete(format!("ERROR: {error}"), 130),
332 };
333 let resource_config = lean_ctx::core::config::Config::load().agents;
334 let (shell, flag) = lean_ctx::shell::shell_and_flag();
335 let normalized_cmd = crate::tools::ctx_shell::normalize_command_for_shell(command);
336 let normalized_cmd = lean_ctx::shell::platform::zsh_safe_command(&normalized_cmd, &shell);
337 let dir = std::path::Path::new(cwd);
338 let mut cmd = std::process::Command::new(&shell);
339 if let Some([program, arguments @ ..]) = protected_prefix.as_deref() {
340 cmd = std::process::Command::new(program);
341 cmd.args(arguments).arg(&shell);
342 }
343 if cfg!(windows) && lean_ctx::shell::platform::is_powershell(&shell) {
344 cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass"]);
345 }
346 cmd.arg(&flag)
347 .arg(&normalized_cmd)
348 .env("GIT_TERMINAL_PROMPT", "0")
349 .stdin(Stdio::null());
350 lean_ctx::shell::reentry::mark_child(&mut cmd);
351
352 if !extra_env.contains_key("GIT_PAGER") {
353 cmd.env("GIT_PAGER", "cat");
354 }
355 if !extra_env.contains_key("PAGER") {
356 cmd.env("PAGER", "cat");
357 }
358
359 ensure_utf8_locale(&mut cmd, extra_env);
360 lean_ctx::shell::platform::apply_profile_free_env(&mut cmd);
361
362 let mut forwarded: std::collections::HashSet<String> = std::collections::HashSet::new();
371 for (key, val) in std::env::vars() {
372 if lean_ctx_ext::core::agent_runtime_env::is_forwardable(&key) {
373 cmd.env(&key, &val);
374 forwarded.insert(key);
375 }
376 }
377 for (key, val) in lean_ctx_ext::core::agent_runtime_env::load() {
378 if !forwarded.contains(&key) {
379 cmd.env(&key, &val);
380 }
381 }
382
383 for (key, val) in extra_env {
385 cmd.env(key, val);
386 }
387 if is_build_or_test_command(command) {
388 if resource_config.cargo_build_jobs > 0 && !extra_env.contains_key("CARGO_BUILD_JOBS") {
389 cmd.env(
390 "CARGO_BUILD_JOBS",
391 resource_config.cargo_build_jobs.to_string(),
392 );
393 }
394 if resource_config.shared_cargo_target
395 && !extra_env.contains_key("CARGO_TARGET_DIR")
396 && let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir()
397 {
398 cmd.env(
399 "CARGO_TARGET_DIR",
400 data_dir.join("build-cache/cargo-target"),
401 );
402 }
403 }
404 if dir.is_dir() {
405 cmd.current_dir(dir);
406 } else {
407 return ShellExecution::complete(
408 format!("ERROR: working directory does not exist or is not a directory: {cwd}"),
409 1,
410 );
411 }
412 let cap = lean_ctx::core::limits::max_shell_bytes();
413
414 lean_ctx::shell::process_tree::ProcessTree::prepare(&mut cmd);
436
437 let started = match lean_ctx::shell::process_tree::ShellChild::start(&mut cmd) {
438 Ok(started) => started,
439 Err(e) => return ShellExecution::complete(format!("ERROR: {e}"), 1),
440 };
441 let mut child = started.child;
442 let (out_buf, out_done) = spawn_capture(started.stdout, cap);
446 let (err_buf, err_done) = spawn_capture(started.stderr, cap);
447
448 let timeout = command_timeout(command, timeout_ms);
449 let start = Instant::now();
450 let hard_deadline = idle_keyed.then(|| start + streaming_max_lifetime());
451 let mut last_len = 0usize;
452 let mut last_output_at = start;
453 let mut still_running: Vec<String> = Vec::new();
455 let (code, timed_out, cancelled) = loop {
456 match child.try_wait() {
457 Ok(Some(status)) => {
458 break (
459 lean_ctx::shell::exit_status::exit_code(status),
460 false,
461 false,
462 );
463 }
464 Ok(None) => {
465 if cancel.is_some_and(|signal| signal.load(std::sync::atomic::Ordering::Acquire)) {
466 child.kill();
467 child.wait();
468 break (130, false, true);
469 }
470 let idle_for = if idle_keyed {
471 let len = captured_len(&out_buf) + captured_len(&err_buf);
472 if len != last_len {
473 last_len = len;
474 last_output_at = Instant::now();
475 }
476 last_output_at.elapsed()
477 } else {
478 start.elapsed()
479 };
480 if idle_for >= timeout || hard_deadline.is_some_and(|d| Instant::now() >= d) {
481 still_running = running_segments(child.id(), &normalized_cmd);
482 child.kill();
483 child.wait();
484 break (124, true, false);
485 }
486 std::thread::sleep(Duration::from_millis(25));
487 }
488 Err(_) => {
489 child.kill();
490 break (1, false, false);
491 }
492 }
493 };
494 let lost_notice = child.lost_notice();
499 let release_notice = child.release();
503 let containment_notice = started.notice.or(lost_notice).or(release_notice);
504
505 let reader_deadline = Instant::now() + READER_RESULT_TIMEOUT;
510 let out_complete = wait_for_reader(&out_done, reader_deadline);
511 let err_complete = wait_for_reader(&err_done, reader_deadline);
512 let (out_bytes, out_trunc, out_read_failed) = snapshot(&out_buf);
513 let (err_bytes, err_trunc, err_read_failed) = snapshot(&err_buf);
514 let reader_incomplete = !out_complete || !err_complete || out_read_failed || err_read_failed;
515 let decode_lossy =
518 std::str::from_utf8(&out_bytes).is_err() || std::str::from_utf8(&err_bytes).is_err();
519
520 let stdout =
521 lean_ctx::shell::resolve_carriage_returns(&lean_ctx::shell::decode_output(&out_bytes));
522 let stderr =
523 lean_ctx::shell::resolve_carriage_returns(&lean_ctx::shell::decode_output(&err_bytes));
524 let mut text = lean_ctx::shell::combine_streams(&stdout, &stderr, code);
527
528 if out_trunc || err_trunc {
529 text.push_str(&format!(
530 "\n[truncated: cap={}B stdout={}B stderr={}B]",
531 cap,
532 out_bytes.len(),
533 err_bytes.len()
534 ));
535 }
536 if reader_incomplete && !timed_out {
541 if !text.is_empty() && !text.ends_with('\n') {
542 text.push('\n');
543 }
544 text.push_str(&format!(
545 "[lean-ctx: output reader still draining after {}s — a background process is likely \
546 holding the pipe open; output above may be partial]",
547 READER_RESULT_TIMEOUT.as_secs()
548 ));
549 }
550 if timed_out {
551 if !text.ends_with('\n') && !text.is_empty() {
552 text.push('\n');
553 }
554 text.push_str(&format!(
555 "{TIMEOUT_MARKER}{}ms{}",
556 timeout.as_millis(),
557 if idle_keyed {
558 " without new output"
559 } else {
560 ""
561 }
562 ));
563 if !still_running.is_empty() {
573 text.push_str(&format!(
574 "\n[still running at timeout: {}]",
575 still_running.join("; ")
576 ));
577 }
578 }
579 if let Some(hint) = super::walk_hint::walk_hint(command, cwd) {
591 if !text.is_empty() && !text.ends_with('\n') {
592 text.push('\n');
593 }
594 text.push_str(&hint);
595 }
596 if cancelled {
597 if !text.ends_with('\n') && !text.is_empty() {
598 text.push('\n');
599 }
600 text.push_str("[cancelled: command stopped on request]");
602 }
603
604 ShellExecution {
605 output: text,
606 exit_code: code,
607 notice: containment_notice,
609 completeness: lean_ctx::core::context_admission::OutputCompleteness {
610 truncated: out_trunc || err_trunc,
611 timed_out,
612 reader_incomplete: reader_incomplete || lost_notice.is_some(),
613 cancelled,
614 decode_lossy,
615 },
616 }
617}
618
619#[derive(Default)]
625struct CaptureBuf {
626 bytes: Vec<u8>,
627 truncated: bool,
628 read_failed: bool,
629}
630
631fn spawn_capture<R: Read + Send + 'static>(
636 pipe: Option<R>,
637 cap: usize,
638) -> (Arc<Mutex<CaptureBuf>>, mpsc::Receiver<()>) {
639 let shared = Arc::new(Mutex::new(CaptureBuf::default()));
640 let (done_tx, done_rx) = mpsc::channel();
641 let writer = Arc::clone(&shared);
642 std::thread::spawn(move || {
643 if let Some(mut r) = pipe {
644 let mut buf = [0u8; 8192];
645 loop {
646 match r.read(&mut buf) {
647 Ok(0) => break,
648 Err(ref error) if error.kind() == std::io::ErrorKind::Interrupted => {}
649 Err(_) => {
650 writer
651 .lock()
652 .unwrap_or_else(std::sync::PoisonError::into_inner)
653 .read_failed = true;
654 break;
655 }
656 Ok(n) => {
657 let mut s = writer
658 .lock()
659 .unwrap_or_else(std::sync::PoisonError::into_inner);
660 if s.bytes.len() < cap {
661 let remaining = cap - s.bytes.len();
662 let take = remaining.min(n);
663 s.bytes.extend_from_slice(&buf[..take]);
664 if take < n {
665 s.truncated = true;
666 }
667 } else {
668 s.truncated = true;
669 }
670 }
671 }
672 }
673 }
674 let _ = done_tx.send(());
675 });
676 (shared, done_rx)
677}
678
679fn snapshot(buf: &Arc<Mutex<CaptureBuf>>) -> (Vec<u8>, bool, bool) {
682 let s = buf
683 .lock()
684 .unwrap_or_else(std::sync::PoisonError::into_inner);
685 (s.bytes.clone(), s.truncated, s.read_failed)
686}
687
688fn captured_len(buf: &Arc<Mutex<CaptureBuf>>) -> usize {
691 buf.lock()
692 .unwrap_or_else(std::sync::PoisonError::into_inner)
693 .bytes
694 .len()
695}
696
697fn streaming_max_lifetime() -> Duration {
700 Duration::from_millis(
701 std::env::var("LEAN_CTX_SHELL_BG_MAX_MS")
702 .ok()
703 .and_then(|v| v.parse().ok())
704 .filter(|&ms: &u64| ms > 0)
705 .unwrap_or(3_600_000),
706 )
707}
708
709#[cfg(unix)]
711struct LiveProc {
712 pid: u32,
713 ppid: u32,
714 args: String,
715}
716
717#[cfg(unix)]
733fn running_segments(pgid: u32, command: &str) -> Vec<String> {
734 let Ok(out) = std::process::Command::new("ps")
738 .args(["-A", "-o", "pid=,ppid=,pgid=,args="])
739 .output()
740 else {
741 return Vec::new();
742 };
743 let needle = command.split_whitespace().collect::<Vec<_>>().join(" ");
744 let live: Vec<LiveProc> = String::from_utf8_lossy(&out.stdout)
745 .lines()
746 .filter_map(|line| parse_ps_row(line, pgid, &needle))
747 .collect();
748
749 describe_live(&live)
750}
751
752#[cfg(unix)]
757fn describe_live(live: &[LiveProc]) -> Vec<String> {
758 let pids: std::collections::HashSet<u32> = live.iter().map(|p| p.pid).collect();
759 live.iter()
760 .filter(|p| !pids.contains(&p.ppid))
761 .map(|parent| {
762 let kids: Vec<&str> = live
763 .iter()
764 .filter(|c| c.ppid == parent.pid)
765 .map(|c| c.args.as_str())
766 .collect();
767 if kids.is_empty() {
768 parent.args.clone()
769 } else {
770 format!("{} (spawned: {})", parent.args, kids.join(", "))
771 }
772 })
773 .collect()
774}
775
776#[cfg(unix)]
780fn parse_ps_row(line: &str, pgid: u32, needle: &str) -> Option<LiveProc> {
781 let rest = line.trim_start();
782 let (pid, rest) = rest.split_once(char::is_whitespace)?;
783 let rest = rest.trim_start();
784 let (ppid, rest) = rest.split_once(char::is_whitespace)?;
785 let args = rest
786 .trim_start()
787 .split_once(char::is_whitespace)
788 .and_then(|(row_pgid, args)| {
789 (row_pgid.parse::<u32>().ok()? == pgid).then_some(args.trim())
790 })?;
791 if args.is_empty() || args.contains(needle) {
792 return None;
793 }
794 Some(LiveProc {
795 pid: pid.parse().ok()?,
796 ppid: ppid.parse().ok()?,
797 args: args.chars().take(200).collect(),
798 })
799}
800
801#[cfg(not(unix))]
802fn running_segments(_pgid: u32, _command: &str) -> Vec<String> {
803 Vec::new()
805}
806
807fn wait_for_reader(done: &mpsc::Receiver<()>, deadline: Instant) -> bool {
810 let remaining = deadline.saturating_duration_since(Instant::now());
811 done.recv_timeout(remaining).is_ok()
812}
813
814fn ensure_utf8_locale(
815 cmd: &mut std::process::Command,
816 extra_env: &std::collections::HashMap<String, String>,
817) {
818 if extra_env.contains_key("LC_ALL") || extra_env.contains_key("LC_CTYPE") {
819 return;
820 }
821 lean_ctx::shell::platform::apply_utf8_locale(cmd);
822}
823
824fn command_timeout(command: &str, timeout_ms: Option<u64>) -> Duration {
825 lean_ctx::shell::shell_timeout_with_override(command, timeout_ms)
829}
830
831#[cfg(all(test, target_os = "macos"))]
832#[path = "execute_supervised_tests.rs"]
833mod supervised_tests;
834
835#[cfg(all(test, unix))]
836#[path = "execute_containment_tests.rs"]
837mod containment_tests;
838
839#[cfg(test)]
840mod tests {
841 use super::{
842 command_timeout, ensure_utf8_locale, execute_command_in, is_build_or_test_command,
843 };
844
845 #[test]
846 fn resource_broker_build_slot_classifier_is_precise() {
847 for command in [
848 "cargo test --lib",
849 "cargo fast",
850 "cd rust && cargo fast --features dev-tools",
851 "make dev",
852 "make build",
853 "make preflight-fast",
854 "make install-release",
855 "./install.sh --build-only",
856 "bash rust/dev-install.sh --fast",
857 "./rust/dev-install.sh --release",
858 "lean-ctx dev-install",
859 "/opt/bin/lean-ctx dev-install --fast",
860 "cd rust && cargo clippy --all-features",
861 "/opt/bin/cargo build --release",
862 "npm test",
863 "npm run typecheck",
864 "pnpm build",
865 "rustc main.rs",
866 ] {
867 assert!(is_build_or_test_command(command), "{command}");
868 }
869 for command in [
870 "git status",
871 "cargo metadata",
872 "make help",
873 "lean-ctx --version",
874 "npm view lean-ctx",
875 "rg cargo",
876 ] {
877 assert!(!is_build_or_test_command(command), "{command}");
878 }
879 }
880
881 #[test]
882 fn resource_broker_serializes_build_leases() {
883 let isolation = lean_ctx::core::data_dir::isolated_data_dir();
884 assert!(
886 super::acquire_build_lease("cargo test", None)
887 .expect("lease")
888 .is_none()
889 );
890 std::fs::write(
891 isolation.path().join("config.toml"),
892 "[agents]\nserialize_build_commands = true\n",
893 )
894 .expect("opt in");
895 let first = super::acquire_build_lease("cargo test first", None)
896 .expect("first lease")
897 .expect("build command gets lease");
898 let acquired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
899 let worker_acquired = std::sync::Arc::clone(&acquired);
900 let worker = std::thread::spawn(move || {
901 let _second = super::acquire_build_lease("cargo test second", None)
902 .expect("second lease")
903 .expect("build command gets lease");
904 worker_acquired.store(true, std::sync::atomic::Ordering::Release);
905 });
906 std::thread::sleep(std::time::Duration::from_millis(50));
907 assert!(!acquired.load(std::sync::atomic::Ordering::Acquire));
908 drop(first);
909 worker.join().expect("lease waiter");
910 assert!(acquired.load(std::sync::atomic::Ordering::Acquire));
911 }
912
913 #[test]
914 fn command_timeout_delegates_to_shell_timeout() {
915 let _lock = lean_ctx::core::data_dir::test_env_lock();
919 let saved = std::env::var("LEAN_CTX_SHELL_TIMEOUT_MS").ok();
920 lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
921
922 assert!(
923 command_timeout("cargo install --path .", None) > command_timeout("git status", None)
924 );
925
926 lean_ctx::test_env::set_var("LEAN_CTX_SHELL_TIMEOUT_MS", "5000");
927 assert_eq!(
928 command_timeout("cargo install --path .", None),
929 std::time::Duration::from_secs(5)
930 );
931 assert_eq!(
932 command_timeout("git status", None),
933 std::time::Duration::from_secs(5)
934 );
935
936 lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
937 if let Some(v) = saved {
938 lean_ctx::test_env::set_var("LEAN_CTX_SHELL_TIMEOUT_MS", v);
939 }
940 }
941
942 #[cfg(target_os = "macos")]
947 #[test]
948 fn the_supervisor_runs_the_shell_under_the_pinned_child_rules() {
949 let _lock = lean_ctx::core::data_dir::test_env_lock();
950 let isolation = lean_ctx::core::data_dir::isolated_data_dir();
951 let fact = isolation.path().join("knowledge/knowledge.json");
952 std::fs::create_dir_all(fact.parent().unwrap()).unwrap();
953 std::fs::write(&fact, "synthetic-provider-fact").unwrap();
954 let work = tempfile::tempdir().unwrap();
955 let cwd = work.path().to_str().unwrap();
956 let read_fact = format!("cat {}", fact.display());
957 let write_fact = format!("printf downgraded > {}", fact.display());
958
959 lean_ctx::core::protected_store::unpin_synthetic_session();
961 let (text, code) = execute_command_in(&read_fact, cwd);
962 assert_eq!(code, 0, "{text}");
963 assert!(text.contains("synthetic-provider-fact"), "{text}");
964
965 let _session = lean_ctx::core::protected_store::pin_synthetic_session(isolation.path())
966 .expect("pinned rules");
967 lean_ctx_ext::core::protected_execution::with_test_supervisor(|| {
968 let (text, code) = execute_command_in(&read_fact, cwd);
969 assert_ne!(code, 0, "{text}");
970 assert!(!text.contains("synthetic-provider-fact"), "{text}");
971 let (text, code) = execute_command_in(&write_fact, cwd);
972 assert_ne!(code, 0, "{text}");
973 let (text, code) =
975 execute_command_in("printf 'fn main() {}' > main.rs && cat main.rs", cwd);
976 assert_eq!(code, 0, "{text}");
977 assert!(text.contains("fn main()"), "{text}");
978 });
979 assert_eq!(
981 std::fs::read_to_string(&fact).unwrap(),
982 "synthetic-provider-fact"
983 );
984 std::fs::write(&fact, "engine-write").unwrap();
985
986 lean_ctx::test_env::remove_var(lean_ctx::core::protected_store::CHILD_PROFILE_ENV);
989 let (text, code) = execute_command_in("printf ran-unconfined", cwd);
990 assert_ne!(code, 0, "{text}");
991 assert!(text.starts_with("ERROR:"), "{text}");
992 assert!(!text.contains("ran-unconfined"), "{text}");
993 }
994
995 #[test]
999 #[cfg_attr(windows, ignore)]
1000 fn idle_keyed_timeout_survives_a_trickling_loop() {
1001 let _lock = lean_ctx::core::data_dir::test_env_lock();
1002 lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
1003 let env = std::collections::HashMap::new();
1004 let cmd = "for i in 1 2 3 4 5 6 7 8 9; do printf T; sleep 0.1; done; printf DONE";
1006
1007 let (idle_out, idle_code) = super::execute_command_with_env_cancellable(
1008 cmd,
1009 ".",
1010 &env,
1011 Some(400),
1012 None,
1013 true,
1014 None,
1015 );
1016 assert_eq!(
1017 idle_code, 0,
1018 "output kept resetting the idle clock: {idle_out}"
1019 );
1020 assert!(idle_out.contains("DONE"));
1021
1022 let (wall_out, wall_code) = super::execute_command_with_env_cancellable(
1023 cmd,
1024 ".",
1025 &env,
1026 Some(400),
1027 None,
1028 false,
1029 None,
1030 );
1031 assert_eq!(wall_code, 124, "wall-clock mode must still enforce the cap");
1032 assert!(wall_out.contains("timed out"));
1033 }
1034
1035 #[test]
1038 #[cfg_attr(windows, ignore)]
1039 fn timeout_names_the_still_running_segment() {
1040 let _lock = lean_ctx::core::data_dir::test_env_lock();
1041 lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
1042 let env = std::collections::HashMap::new();
1043 let (out, code) = super::execute_command_with_env_cancellable(
1044 "printf FIRST_OK; sleep 47",
1045 ".",
1046 &env,
1047 Some(600),
1048 None,
1049 false,
1050 None,
1051 );
1052 assert_eq!(code, 124);
1053 assert!(
1054 out.contains("FIRST_OK"),
1055 "partial output must survive: {out}"
1056 );
1057 assert!(
1058 out.contains("still running at timeout") && out.contains("47"),
1059 "the hung segment must be named: {out}"
1060 );
1061 }
1062
1063 #[test]
1064 #[cfg(unix)]
1065 fn ps_row_names_segments_and_drops_the_whole_command() {
1066 let whole = "printf hi; grep -rn needle /repo";
1068 assert_eq!(
1069 super::parse_ps_row(" 4242 4200 4200 grep -rn needle /repo", 4200, whole)
1070 .map(|p| p.args),
1071 Some("grep -rn needle /repo".to_string()),
1072 "a segment must be named"
1073 );
1074 assert!(
1076 super::parse_ps_row(
1077 "4200 1 4200 /bin/sh -c printf hi; grep -rn needle /repo",
1078 4200,
1079 whole
1080 )
1081 .is_none()
1082 );
1083 assert!(super::parse_ps_row("4242 4200 9999 sleep 5", 4200, whole).is_none());
1085 assert!(super::parse_ps_row("garbage", 4200, whole).is_none());
1086 }
1087
1088 #[test]
1095 #[cfg(unix)]
1096 fn a_spawned_child_is_labelled_not_presented_as_a_stage() {
1097 let live = vec![
1098 super::LiveProc {
1099 pid: 100,
1100 ppid: 1,
1101 args: "go run ./ --template x".into(),
1102 },
1103 super::LiveProc {
1104 pid: 101,
1105 ppid: 100,
1106 args: "/var/folders/T/go-build/b001/exe/evcc --template x".into(),
1107 },
1108 ];
1109 let out = super::describe_live(&live);
1110 assert_eq!(out.len(), 1, "the child is not a peer entry: {out:?}");
1111 assert!(out[0].starts_with("go run ./"), "{out:?}");
1112 assert!(
1113 out[0].contains("(spawned: /var/folders/T/go-build/b001/exe/evcc"),
1114 "the descendant is named as one: {out:?}"
1115 );
1116 }
1117
1118 #[test]
1122 #[cfg(unix)]
1123 fn genuine_pipeline_siblings_both_stay_top_level() {
1124 let live = vec![
1125 super::LiveProc {
1126 pid: 200,
1127 ppid: 50,
1128 args: "grep -rn needle /repo".into(),
1129 },
1130 super::LiveProc {
1131 pid: 201,
1132 ppid: 50,
1133 args: "head -30".into(),
1134 },
1135 ];
1136 let mut out = super::describe_live(&live);
1137 out.sort();
1138 assert_eq!(out, vec!["grep -rn needle /repo", "head -30"]);
1139 }
1140
1141 #[test]
1144 #[cfg(unix)]
1145 fn the_timeout_line_does_not_imply_a_pipeline() {
1146 let joined = ["a".to_string(), "b".to_string()].join("; ");
1147 assert!(!joined.contains('|'), "no pipe may be invented: {joined}");
1148 }
1149
1150 #[test]
1151 fn ensure_utf8_locale_sets_fallback_when_none_inherited() {
1152 let _env_lock = lean_ctx::core::data_dir::test_env_lock();
1153 let empty: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1154 let mut cmd = std::process::Command::new("true");
1155
1156 let saved = (
1158 std::env::var("LC_ALL").ok(),
1159 std::env::var("LC_CTYPE").ok(),
1160 std::env::var("LANG").ok(),
1161 );
1162 lean_ctx::test_env::remove_var("LC_ALL");
1163 lean_ctx::test_env::remove_var("LC_CTYPE");
1164 lean_ctx::test_env::remove_var("LANG");
1165
1166 ensure_utf8_locale(&mut cmd, &empty);
1167
1168 if let Some(v) = saved.0 {
1170 lean_ctx::test_env::set_var("LC_ALL", v);
1171 }
1172 if let Some(v) = saved.1 {
1173 lean_ctx::test_env::set_var("LC_CTYPE", v);
1174 }
1175 if let Some(v) = saved.2 {
1176 lean_ctx::test_env::set_var("LANG", v);
1177 }
1178
1179 }
1182
1183 #[test]
1184 fn ensure_utf8_locale_skips_when_extra_env_has_lc_all() {
1185 let mut extra = std::collections::HashMap::new();
1186 extra.insert("LC_ALL".to_string(), "C".to_string());
1187 let mut cmd = std::process::Command::new("true");
1188 ensure_utf8_locale(&mut cmd, &extra);
1189 }
1191
1192 #[test]
1193 #[cfg_attr(windows, ignore)]
1194 fn utf8_bytes_survive_shell_roundtrip() {
1195 let _lock = lean_ctx::core::data_dir::test_env_lock();
1196 let (output, code) = execute_command_in(
1197 "printf '\\xD0\\x9F\\xD1\\x80\\xD0\\xB8\\xD0\\xB2\\xD0\\xB5\\xD1\\x82'",
1198 ".",
1199 );
1200 assert_eq!(code, 0, "printf failed: {output}");
1201 assert_eq!(output, "Привет", "Cyrillic bytes must survive roundtrip");
1202 }
1203
1204 #[test]
1205 #[cfg_attr(windows, ignore)] fn execute_command_closes_stdin() {
1207 let _lock = lean_ctx::core::data_dir::test_env_lock();
1208 let command = "sh -c 'if read -t 1 line; then echo 67890; else echo 12345; fi'";
1209 let (output, code) = execute_command_in(command, ".");
1210 assert_eq!(code, 0, "command failed: {output}");
1211 assert!(
1212 output.contains("12345"),
1213 "child process should receive EOF on stdin, got: {output}"
1214 );
1215 }
1216
1217 #[test]
1220 #[cfg(unix)]
1221 fn execute_command_reports_signal_termination_as_128_plus_signal() {
1222 let (output, code) = execute_command_in("echo before-kill; kill -TERM $$", ".");
1223 assert_eq!(code, 143, "SIGTERM must map to 143, got {code}: {output}");
1224 assert!(output.contains("before-kill"), "output kept: {output}");
1225
1226 let (_, code) = execute_command_in("kill -KILL $$", ".");
1227 assert_eq!(code, 137, "SIGKILL must map to 137");
1228 }
1229
1230 #[test]
1236 #[cfg_attr(windows, ignore)] fn background_pipe_holder_keeps_foreground_output() {
1238 let _lock = lean_ctx::core::data_dir::test_env_lock();
1239 let (output, code) = execute_command_in("echo REPRO_CANARY_945; sleep 4 &", ".");
1240 assert_eq!(code, 0, "command should succeed: {output:?}");
1241 assert!(
1242 output.contains("REPRO_CANARY_945"),
1243 "foreground stdout must survive a lingering background pipe holder, got: {output:?}"
1244 );
1245 assert!(
1246 output.contains("output reader still draining"),
1247 "an incomplete reader must be flagged, got: {output:?}"
1248 );
1249 }
1250
1251 #[test]
1255 #[cfg(unix)]
1256 fn command_has_no_controlling_terminal() {
1257 let (output, code) = execute_command_in(
1258 "if (exec 3</dev/tty) 2>/dev/null; then echo HAS_TTY; else echo NO_TTY; fi",
1259 ".",
1260 );
1261 assert_eq!(code, 0, "{output:?}");
1262 assert!(output.contains("NO_TTY"), "got: {output:?}");
1263 }
1264
1265 #[test]
1266 #[cfg_attr(windows, ignore)]
1267 fn forwards_captured_agent_runtime_env() {
1268 let _iso = lean_ctx::core::data_dir::isolated_data_dir();
1273
1274 lean_ctx::test_env::remove_var("CODEX_THREAD_ID");
1276 lean_ctx::test_env::set_var("CODEX_THREAD_ID", "thread-from-hook");
1277 lean_ctx_ext::core::agent_runtime_env::capture();
1278 lean_ctx::test_env::remove_var("CODEX_THREAD_ID");
1280
1281 let (output, code) = execute_command_in("printf 'TID=%s' \"$CODEX_THREAD_ID\"", ".");
1282
1283 assert_eq!(code, 0, "command failed: {output}");
1284 assert!(
1285 output.contains("TID=thread-from-hook"),
1286 "captured agent runtime var must be forwarded, got: {output}"
1287 );
1288 }
1289
1290 #[test]
1293 #[cfg_attr(windows, ignore)] fn per_call_timeout_kills_long_command() {
1295 let _lock = lean_ctx::core::data_dir::test_env_lock();
1296 let (output, code) = super::execute_command_with_env(
1297 "sleep 3",
1298 ".",
1299 &std::collections::HashMap::new(),
1300 Some(200),
1301 );
1302 assert_eq!(code, 124, "timed-out command must exit 124: {output}");
1303 assert!(
1304 output.contains("timed out after 200ms"),
1305 "timeout message must carry the per-call budget, got: {output}"
1306 );
1307 }
1308
1309 #[test]
1312 #[cfg_attr(windows, ignore)] fn per_call_timeout_preserves_partial_output() {
1314 let _lock = lean_ctx::core::data_dir::test_env_lock();
1315 let (output, code) = super::execute_command_with_env(
1316 "printf TIMEOUT_PARTIAL_995; sleep 3",
1317 ".",
1318 &std::collections::HashMap::new(),
1319 Some(200),
1320 );
1321 assert_eq!(code, 124, "timed-out command must exit 124: {output}");
1322 assert!(
1323 output.contains("TIMEOUT_PARTIAL_995"),
1324 "stdout emitted before timeout must be preserved: {output:?}"
1325 );
1326 assert!(
1327 output.contains("timed out after 200ms"),
1328 "timeout notice must remain explicit: {output:?}"
1329 );
1330 }
1331
1332 #[test]
1333 fn git_version_returns_when_git_is_available() {
1334 let _lock = lean_ctx::core::data_dir::test_env_lock();
1335 let git_available = std::process::Command::new("git")
1336 .arg("--version")
1337 .stdout(std::process::Stdio::null())
1338 .stderr(std::process::Stdio::null())
1339 .status()
1340 .is_ok();
1341 if !git_available {
1342 return;
1343 }
1344
1345 let (output, code) = execute_command_in("git --version", ".");
1346 assert_eq!(code, 0, "git command failed: {output}");
1347 assert!(
1348 output.to_ascii_lowercase().contains("git version"),
1349 "unexpected git output: {output}"
1350 );
1351 }
1352}