Skip to main content

codex_wrapper/
exec.rs

1//! Process execution layer for spawning and communicating with the `codex`
2//! binary, including timeout and retry support.
3
4use std::fmt;
5use std::path::Path;
6use std::process::ExitStatus;
7use std::time::{Duration, Instant};
8
9use tokio::process::Command;
10use tracing::{Instrument, Span, debug, field, info_span};
11
12use crate::Codex;
13use crate::error::{Error, OutputStream, Result, ShutdownAction};
14
15/// Build the span covering one invocation.
16///
17/// The fields carry what identifies a run, never what it contains: no prompt
18/// and no environment. Both routinely hold content a host would not want in
19/// its logs, and a span is recorded whenever any subscriber is installed.
20pub(crate) fn command_span(name: &'static str, codex: &Codex, args: &[String]) -> Span {
21    info_span!(
22        parent: Span::current(),
23        "codex",
24        otel.name = name,
25        subcommand = trace_subcommand(args),
26        arg_count = args.len(),
27        working_dir_set = codex.working_dir.is_some(),
28        outcome = field::Empty,
29        exit_code = field::Empty,
30        duration_ms = field::Empty,
31    )
32}
33
34/// RawCommand permits arbitrary first tokens; only fixed operation labels may
35/// enter diagnostics. Counts retain observability for future/unknown commands.
36fn trace_subcommand(args: &[String]) -> &'static str {
37    match args.first().map(String::as_str) {
38        None => "(none)",
39        Some("exec") => "exec",
40        Some("archive") => "archive",
41        Some("delete") => "delete",
42        Some("unarchive") => "unarchive",
43        Some("--version" | "-V") => "version",
44        Some("review") => "review",
45        Some("login") => "login",
46        Some("logout") => "logout",
47        Some("mcp") => "mcp",
48        Some("mcp-server") => "mcp-server",
49        Some("app-server") => "app-server",
50        Some("completion") => "completion",
51        Some("sandbox") => "sandbox",
52        Some("apply") => "apply",
53        Some("resume") => "resume",
54        Some("fork") => "fork",
55        Some("features") => "features",
56        Some("plugin") => "plugin",
57        Some("doctor") => "doctor",
58        Some("update") => "update",
59        Some(_) => "other",
60    }
61}
62
63/// Records how a run ended on its span, including when it does not end at all.
64///
65/// The dropped-future case is the one worth the machinery. Cancellation kills
66/// the process and runs nothing else, so without this the span would close
67/// with no outcome and an abandoned run would be indistinguishable from one
68/// still in progress. The span is passed in and held rather than read from
69/// [`Span::current`]: current-span tracking is the subscriber's job, and a
70/// subscriber that does not implement it would silently drop every record,
71/// including the drop-time one this exists for.
72pub(crate) struct SpanOutcome {
73    span: Span,
74    started: Instant,
75    settled: bool,
76}
77
78impl SpanOutcome {
79    pub(crate) fn start(span: Span) -> Self {
80        Self {
81            span,
82            started: Instant::now(),
83            settled: false,
84        }
85    }
86
87    pub(crate) fn settle(&mut self, outcome: &'static str, exit_code: Option<i32>) {
88        self.settled = true;
89        self.span.record("outcome", outcome);
90        self.span
91            .record("duration_ms", self.started.elapsed().as_millis() as u64);
92        if let Some(code) = exit_code {
93            self.span.record("exit_code", code);
94        }
95    }
96
97    fn settle_from_ref(&mut self, result: &Result<CommandOutput>) {
98        self.settle_from(result);
99    }
100
101    fn settle_from(&mut self, result: &Result<CommandOutput>) {
102        match result {
103            Ok(output) => self.settle("ok", Some(output.exit_code)),
104            Err(Error::Timeout { .. }) => self.settle("timeout", None),
105            // Its own outcome so the span never reads as a settled timeout or
106            // cancellation when the child may not have been reaped.
107            Err(Error::CleanupFailed { .. }) => self.settle("cleanup_failed", None),
108            // Covers the classified failures too, which are no longer
109            // CommandFailed but did still come from a process exit.
110            Err(e) => match e.exit_code() {
111                Some(code) => self.settle("failed", Some(code)),
112                None => self.settle("error", None),
113            },
114        }
115    }
116}
117
118impl Drop for SpanOutcome {
119    fn drop(&mut self) {
120        if !self.settled {
121            self.settle("cancelled", None);
122        }
123    }
124}
125
126/// Put the child in its own process group so signals also reach descendants
127/// that stay in that group. Tools that detach require cooperative CLI cleanup;
128/// `kill_on_drop` alone only reaches the direct child.
129#[cfg(unix)]
130fn own_process_group(cmd: &mut Command, enabled: bool) {
131    if enabled {
132        cmd.process_group(0);
133    }
134}
135
136#[cfg(not(unix))]
137fn own_process_group(_cmd: &mut Command, _enabled: bool) {}
138
139/// Whether [`CodexBuilder::die_with_parent`](crate::CodexBuilder::die_with_parent)
140/// has a kernel-level effect on this platform.
141///
142/// This is true only on Linux, where `PR_SET_PDEATHSIG` is available. A
143/// supervisor that needs portable containment should use
144/// [`CodexBuilder::on_spawn`](crate::CodexBuilder::on_spawn) to maintain its
145/// own watchdog on other targets.
146#[must_use]
147pub const fn die_with_parent_supported() -> bool {
148    cfg!(target_os = "linux")
149}
150
151/// Ask the kernel to SIGKILL the child when its immediate parent dies.
152///
153/// The parent pid is captured before the fork. After arming the signal in the
154/// child, the hook checks it again and exits if the parent changed in the
155/// fork-to-prctl window. Every call here is async-signal-safe because this hook
156/// runs after `fork` and before `exec`.
157#[cfg(unix)]
158fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
159    let parent = std::process::id();
160    move || {
161        #[cfg(target_os = "linux")]
162        {
163            // SAFETY: prctl, getppid, and _exit are async-signal-safe calls.
164            unsafe {
165                if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
166                    return Err(std::io::Error::last_os_error());
167                }
168                if libc::getppid() as u32 != parent {
169                    libc::_exit(1);
170                }
171            }
172        }
173        #[cfg(not(target_os = "linux"))]
174        {
175            let _ = parent;
176        }
177        Ok(())
178    }
179}
180
181/// Apply the parent-death policy to a spawn command.
182fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
183    #[cfg(unix)]
184    if enabled {
185        // SAFETY: `pdeathsig_hook` uses only async-signal-safe operations.
186        unsafe {
187            cmd.pre_exec(pdeathsig_hook());
188        }
189    }
190    #[cfg(not(unix))]
191    {
192        let _ = (cmd, enabled);
193    }
194}
195
196/// Construct a CLI command with the process policies shared by every spawn path.
197pub(crate) fn child_command(binary: &Path, process_group: bool, die_with_parent: bool) -> Command {
198    let mut cmd = Command::new(binary);
199    // Dropping a future must stop a child even when it shares the parent's group.
200    cmd.kill_on_drop(true);
201    own_process_group(&mut cmd, process_group);
202    apply_die_with_parent(&mut cmd, die_with_parent);
203    #[cfg(any(target_os = "macos", target_os = "ios"))]
204    mark_inherited_fds_close_on_exec(&mut cmd);
205    cmd
206}
207
208/// On macOS and iOS, Rust creates pipes before setting CLOEXEC. A concurrent
209/// fork can inherit the pipes in that window and delay EOF for a sibling.
210#[cfg(any(target_os = "macos", target_os = "ios"))]
211fn mark_inherited_fds_close_on_exec(cmd: &mut Command) {
212    // Bound the number of fcntl calls even if the soft limit is huge or
213    // unlimited. Query the limit in the parent so the hook needs no getrlimit.
214    const FD_SCAN_LIMIT: libc::c_int = 65_536;
215    let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
216    // SAFETY: getrlimit initializes the struct on success.
217    let end = unsafe {
218        if libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) == 0 {
219            limit
220                .assume_init()
221                .rlim_cur
222                .min(FD_SCAN_LIMIT as libc::rlim_t) as libc::c_int
223        } else {
224            FD_SCAN_LIMIT
225        }
226    };
227
228    // SAFETY: fcntl is async-signal-safe. Setting CLOEXEC leaves Rust's
229    // exec-status descriptor open so it can report a failed exec.
230    unsafe {
231        cmd.pre_exec(move || {
232            for fd in 3..end {
233                // Empty slots (EBADF) and other failures are best effort.
234                libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
235            }
236            Ok(())
237        });
238    }
239}
240
241/// Arm group cleanup and notify the observer from one process receipt.
242pub(crate) fn arm_and_notify(
243    process_group: bool,
244    termination_signal: crate::TerminationSignal,
245    pid: Option<u32>,
246    on_spawn: Option<&crate::SpawnObserver>,
247) -> GroupKillGuard {
248    if let (Some(pid), Some(observer)) = (pid, on_spawn) {
249        observer(crate::SpawnInfo {
250            pid,
251            pgid: process_group.then_some(pid),
252        });
253    }
254    GroupKillGuard::new(process_group.then_some(pid).flatten(), termination_signal)
255}
256
257/// Signal a process group, given the group leader's pid.
258///
259/// Unix only: there is no non-unix counterpart, because every caller of this
260/// is itself gated on unix. A stub would only be dead code.
261///
262/// Negating the pid is what makes this reach the group rather than the leader
263/// alone. Returns whether the OS accepted the signal.
264#[cfg(unix)]
265pub(crate) fn signal_group(pid: u32, signal: i32) -> bool {
266    let Ok(pid) = i32::try_from(pid) else {
267        return false;
268    };
269    // SAFETY: `kill` with a negative pid signals a process group. Callers must
270    // retain ownership of the group leader until their final signal is sent.
271    unsafe { libc::kill(-pid, signal) == 0 }
272}
273
274/// Check the group leader without releasing its PID before the final signal.
275#[cfg(any(
276    target_os = "linux",
277    target_os = "android",
278    target_vendor = "apple",
279    target_os = "freebsd",
280    target_os = "dragonfly",
281    target_os = "netbsd",
282    target_os = "openbsd",
283    target_os = "illumos",
284    target_os = "solaris",
285))]
286fn group_leader_running(pid: u32) -> std::io::Result<bool> {
287    loop {
288        let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
289        // SAFETY: P_PID selects our still-owned child. WNOWAIT leaves an
290        // exited child waitable, reserving its PID and process group ID.
291        let result = unsafe {
292            libc::waitid(
293                libc::P_PID,
294                pid as libc::id_t,
295                info.as_mut_ptr(),
296                libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
297            )
298        };
299        if result == 0 {
300            // SAFETY: No pending status leaves si_pid zero. Zeroing also
301            // covers kernels that leave the buffer untouched in that case.
302            return Ok(unsafe { info.assume_init().si_pid() } == 0);
303        }
304        let error = std::io::Error::last_os_error();
305        if error.kind() != std::io::ErrorKind::Interrupted {
306            return Err(error);
307        }
308    }
309}
310
311#[cfg(all(
312    unix,
313    not(any(
314        target_os = "linux",
315        target_os = "android",
316        target_vendor = "apple",
317        target_os = "freebsd",
318        target_os = "dragonfly",
319        target_os = "netbsd",
320        target_os = "openbsd",
321        target_os = "illumos",
322        target_os = "solaris",
323    ))
324))]
325fn group_leader_running(_pid: u32) -> std::io::Result<bool> {
326    // Without a non-reaping check, the final exit status is the only evidence.
327    Ok(true)
328}
329
330#[cfg(test)]
331mod group_leader_probe_tests {
332    // The targets where `group_leader_running` uses `waitid`.
333    #[cfg(any(
334        target_os = "linux",
335        target_os = "android",
336        target_vendor = "apple",
337        target_os = "freebsd",
338        target_os = "dragonfly",
339        target_os = "netbsd",
340        target_os = "openbsd",
341        target_os = "illumos",
342        target_os = "solaris",
343    ))]
344    mod waitid {
345        use super::super::*;
346        use std::os::unix::process::ExitStatusExt;
347
348        #[tokio::test]
349        async fn reports_exit_without_reaping() {
350            let mut child = Command::new("sleep")
351                .arg("60")
352                .kill_on_drop(true)
353                .spawn()
354                .unwrap();
355            let pid = child.id().unwrap();
356            assert!(group_leader_running(pid).unwrap());
357
358            child.start_kill().unwrap();
359            tokio::time::timeout(Duration::from_secs(5), async {
360                while group_leader_running(pid).unwrap() {
361                    tokio::time::sleep(Duration::from_millis(10)).await;
362                }
363            })
364            .await
365            .expect("the probe did not see the child exit");
366            assert!(!group_leader_running(pid).unwrap());
367
368            let status = child
369                .try_wait()
370                .unwrap()
371                .expect("the child is still waitable");
372            assert_eq!(status.signal(), Some(libc::SIGKILL));
373        }
374
375        #[tokio::test]
376        async fn disarms_when_the_leader_is_reaped_during_the_grace_period() {
377            let mut command = Command::new("sleep");
378            command.arg("60").kill_on_drop(true);
379            own_process_group(&mut command, true);
380            let mut child = command.spawn().unwrap();
381            let mut group = GroupKillGuard::new(child.id(), crate::TerminationSignal::Terminate);
382            let mut stop = Box::pin(group.terminate(Duration::from_millis(500)));
383
384            // Poll through SIGTERM, then let a different waiter collect the
385            // status before polling the termination future again.
386            tokio::select! {
387                biased;
388                result = &mut stop => panic!("termination finished before the grace period: {result:?}"),
389                () = std::future::ready(()) => {}
390            }
391            let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
392                .await
393                .expect("the leader did not exit")
394                .unwrap();
395            assert_eq!(status.signal(), Some(libc::SIGTERM));
396
397            let error = stop.await.unwrap_err();
398            assert_eq!(error.raw_os_error(), Some(libc::ECHILD));
399            assert!(group.pid.is_none());
400        }
401    }
402}
403
404/// SIGKILLs the run's process group when dropped.
405///
406/// `kill_on_drop` handles the direct child; this is what reaches the
407/// descendants that remain in the group. Detached tools require CLI cooperation.
408/// Drop cannot await, so this is the abrupt path.
409/// For a graceful one, see
410/// [`ExecCommand::execute_cancellable`](crate::ExecCommand::execute_cancellable).
411pub(crate) struct GroupKillGuard {
412    pid: Option<u32>,
413    signal: crate::TerminationSignal,
414}
415
416impl GroupKillGuard {
417    pub(crate) fn new(pid: Option<u32>, signal: crate::TerminationSignal) -> Self {
418        Self { pid, signal }
419    }
420
421    /// Stop killing on drop, once the run has finished on its own.
422    pub(crate) fn disarm(&mut self) {
423        self.pid = None;
424    }
425
426    #[cfg(unix)]
427    fn leader_running(&mut self, pid: u32) -> std::io::Result<bool> {
428        match group_leader_running(pid) {
429            Ok(running) => Ok(running),
430            Err(error) if error.raw_os_error() == Some(libc::ECHILD) => {
431                // A foreign wait can release the leader's PID. If the group
432                // emptied too, its ID can be reused. Skip further group
433                // signals, including on Drop, even if descendants may survive.
434                self.disarm();
435                Err(error)
436            }
437            // If the probe is unavailable, finish cleanup and use the reaped
438            // status to rule out a hard stop that did not end the leader.
439            Err(_) => Ok(true),
440        }
441    }
442
443    /// Give the group a grace period, then kill any remaining members while
444    /// the leader still reserves the group ID. Report which signals could
445    /// have reached the leader before it exited.
446    async fn terminate(
447        &mut self,
448        grace: Duration,
449    ) -> std::io::Result<(Option<ShutdownAction>, bool)> {
450        #[cfg(unix)]
451        if let Some(pid) = self.pid {
452            let running = self.leader_running(pid)?;
453            let soft = (signal_group(pid, self.signal.as_raw()) && running)
454                .then_some(ShutdownAction::Signal(self.signal));
455            // Keep drop cleanup armed while this await can be cancelled.
456            tokio::time::sleep(grace).await;
457            let running = self.leader_running(pid)?;
458            let hard = signal_group(pid, libc::SIGKILL) && running;
459            self.disarm();
460            return Ok((soft, hard));
461        }
462        #[cfg(not(unix))]
463        let _ = (self.pid.take(), self.signal, grace);
464        Ok((None, false))
465    }
466}
467
468impl Drop for GroupKillGuard {
469    fn drop(&mut self) {
470        // Taken unconditionally so the field is read on every platform, not
471        // just the one that can act on it.
472        if let Some(pid) = self.pid.take() {
473            #[cfg(unix)]
474            signal_group(pid, libc::SIGKILL);
475            #[cfg(not(unix))]
476            let _ = pid;
477        }
478    }
479}
480
481/// Raw output from a Codex CLI invocation.
482///
483/// Contains captured stdout/stderr, the process exit code, and a convenience
484/// `success` flag.
485#[derive(Clone)]
486pub struct CommandOutput {
487    /// Standard output as a UTF-8 string.
488    pub stdout: String,
489    /// Standard error as a UTF-8 string.
490    pub stderr: String,
491    /// Process exit code (`-1` if the process was killed by a signal).
492    pub exit_code: i32,
493    /// `true` when the process exited with code 0.
494    pub success: bool,
495}
496
497const DEBUG_TRUNCATE_LEN: usize = 200;
498
499fn truncate_for_debug(s: &str) -> String {
500    if s.len() > DEBUG_TRUNCATE_LEN {
501        format!("{}... ({} bytes total)", &s[..DEBUG_TRUNCATE_LEN], s.len())
502    } else {
503        s.to_string()
504    }
505}
506
507impl fmt::Debug for CommandOutput {
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        f.debug_struct("CommandOutput")
510            .field("stdout", &truncate_for_debug(&self.stdout))
511            .field("stderr", &truncate_for_debug(&self.stderr))
512            .field("exit_code", &self.exit_code)
513            .field("success", &self.success)
514            .finish()
515    }
516}
517
518/// Run a codex command with the given arguments.
519///
520/// If the [`Codex`] client has a retry policy set, transient errors will be
521/// retried according to that policy. A per-command retry policy can be passed
522/// to override the client default.
523pub async fn run_codex(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
524    run_codex_with_retry(codex, args, None).await
525}
526
527/// Run a codex command with an optional per-command retry policy override.
528pub async fn run_codex_with_retry(
529    codex: &Codex,
530    args: Vec<String>,
531    retry_override: Option<&crate::retry::RetryPolicy>,
532) -> Result<CommandOutput> {
533    let policy = retry_override.or(codex.retry_policy.as_ref());
534
535    match policy {
536        Some(policy) => {
537            // A parent span so the retry events and each attempt's own span
538            // nest under one run rather than arriving as unrelated lines.
539            let span = info_span!(
540                "codex.retry",
541                subcommand = trace_subcommand(&args),
542                max_attempts = policy.max_attempts,
543            );
544            crate::retry::with_retry(policy, || run_codex_once(codex, args.clone()))
545                .instrument(span)
546                .await
547        }
548        None => run_codex_once(codex, args).await,
549    }
550}
551
552/// Assemble the full argument list for an invocation: the client's global
553/// args first, since they precede the subcommand, then the command's own.
554///
555/// Both spawn paths and [`CodexCommand::to_command_string`] go through here,
556/// so a previewed command cannot drift from the one that actually runs.
557///
558/// [`CodexCommand::to_command_string`]: crate::command::CodexCommand::to_command_string
559pub(crate) fn assemble_args(codex: &Codex, args: Vec<String>) -> Vec<String> {
560    let mut command_args = Vec::with_capacity(codex.global_args.len() + args.len());
561    let protects_rollout_budget = args
562        .windows(2)
563        .any(|pair| pair[0] == "-c" && crate::RolloutBudgetConfig::is_config_override(&pair[1]));
564    let mut global_args = codex.global_args.iter().peekable();
565    while let Some(arg) = global_args.next() {
566        if protects_rollout_budget
567            && matches!(arg.as_str(), "--enable" | "--disable")
568            && global_args
569                .peek()
570                .is_some_and(|feature| feature.as_str() == "rollout_budget")
571        {
572            global_args.next();
573            continue;
574        }
575        if protects_rollout_budget
576            && matches!(
577                arg.as_str(),
578                "--enable=rollout_budget" | "--disable=rollout_budget"
579            )
580        {
581            continue;
582        }
583        command_args.push(arg.clone());
584    }
585    command_args.extend(args);
586    command_args
587}
588
589/// Render an invocation as a copy-pasteable shell command.
590pub(crate) fn command_string(codex: &Codex, args: Vec<String>) -> String {
591    let mut out = shell_quote(&codex.binary.display().to_string());
592    for arg in assemble_args(codex, args) {
593        out.push(' ');
594        out.push_str(&shell_quote(&arg));
595    }
596    out
597}
598
599/// Quote a single argument for a POSIX shell, if it needs it.
600///
601/// The empty string is quoted: unquoted it would vanish from the rendered
602/// command, turning a preview into something that runs differently from what
603/// it describes.
604pub(crate) fn shell_quote(arg: &str) -> String {
605    if arg.is_empty() {
606        return "''".to_string();
607    }
608    if arg.contains(|c: char| c.is_whitespace() || "\"'$\\`|;<>&()[]{}*?!~#".contains(c)) {
609        return format!("'{}'", arg.replace('\'', r"'\''"));
610    }
611    arg.to_string()
612}
613
614async fn run_codex_once(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
615    let span = command_span("codex.exec", codex, &args);
616    let outcome_span = span.clone();
617    let command_args = assemble_args(codex, args);
618
619    async move {
620        debug!(arg_count = command_args.len(), "executing codex command");
621
622        let mut outcome = SpanOutcome::start(outcome_span);
623        let result = match codex.timeout {
624            Some(timeout) => {
625                run_internal_inner(
626                    SpawnSpec {
627                        binary: &codex.binary,
628                        args: &command_args,
629                        env: &codex.env,
630                        clear_env: codex.clear_env,
631                        working_dir: codex.working_dir.as_deref(),
632                        stdin_prompt: None,
633                        process_group: codex.process_group,
634                        termination_signal: codex.termination_signal,
635                        output_limit: codex.output_limit,
636                        die_with_parent: codex.die_with_parent,
637                        on_spawn: codex.on_spawn.as_ref(),
638                    },
639                    Some(timeout_stop(timeout)),
640                    codex.termination_grace,
641                )
642                .await
643            }
644            None => {
645                run_internal_inner(
646                    SpawnSpec {
647                        binary: &codex.binary,
648                        args: &command_args,
649                        env: &codex.env,
650                        clear_env: codex.clear_env,
651                        working_dir: codex.working_dir.as_deref(),
652                        stdin_prompt: None,
653                        process_group: codex.process_group,
654                        termination_signal: codex.termination_signal,
655                        output_limit: codex.output_limit,
656                        die_with_parent: codex.die_with_parent,
657                        on_spawn: codex.on_spawn.as_ref(),
658                    },
659                    None,
660                    Duration::ZERO,
661                )
662                .await
663            }
664        };
665        outcome.settle_from(&result);
666        result
667    }
668    .instrument(span)
669    .await
670}
671
672/// Run a codex command, stopping it gracefully if `cancel` resolves first.
673///
674/// On cancellation the run's process group is sent the configured signal,
675/// given the client's [`termination_grace`](crate::CodexBuilder::termination_grace),
676/// then killed.
677/// This reaches descendants in the owned group. Detached tools require the
678/// CLI's cooperation; [`TerminationSignal::Interrupt`](crate::TerminationSignal::Interrupt)
679/// lets its interrupt handler run before the hard fallback. Output during
680/// shutdown is drained and discarded, and the cancellation reason stays latched
681/// even if the CLI exits successfully. If stopping or reaping the child fails,
682/// the stop reason is returned inside [`Error::CleanupFailed`] rather than as a
683/// bare [`Error::Cancelled`] or [`Error::Timeout`].
684///
685/// Dropping the future instead kills the owned group abruptly: `Drop` cannot
686/// wait out a grace period or allow cooperative cleanup of detached tools.
687///
688/// Retry does not apply. A cancelled run is a decision, not a transient
689/// failure.
690///
691/// On platforms without process groups this degrades to killing the child.
692pub async fn run_codex_cancellable<C>(
693    codex: &Codex,
694    args: Vec<String>,
695    cancel: C,
696) -> Result<CommandOutput>
697where
698    C: std::future::Future<Output = ()> + Send,
699{
700    let span = command_span("codex.exec", codex, &args);
701    let outcome_span = span.clone();
702    let command_args = assemble_args(codex, args);
703
704    async move {
705        debug!(
706            arg_count = command_args.len(),
707            "executing cancellable codex command"
708        );
709
710        let mut outcome = SpanOutcome::start(outcome_span);
711        let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
712        let result = run_internal_inner(
713            SpawnSpec {
714                binary: &codex.binary,
715                args: &command_args,
716                env: &codex.env,
717                clear_env: codex.clear_env,
718                working_dir: codex.working_dir.as_deref(),
719                stdin_prompt: None,
720                process_group: codex.process_group,
721                termination_signal: codex.termination_signal,
722                output_limit: codex.output_limit,
723                die_with_parent: codex.die_with_parent,
724                on_spawn: codex.on_spawn.as_ref(),
725            },
726            Some(stop),
727            codex.termination_grace,
728        )
729        .await;
730
731        match &result {
732            Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
733            other => outcome.settle_from_ref(other),
734        }
735        result
736    }
737    .instrument(span)
738    .await
739}
740
741/// Run a codex command and allow specific non-zero exit codes.
742pub async fn run_codex_allow_exit_codes(
743    codex: &Codex,
744    args: Vec<String>,
745    allowed_codes: &[i32],
746) -> Result<CommandOutput> {
747    let output = run_codex(codex, args).await;
748
749    match output {
750        // Matched on the exit code rather than the variant: classification
751        // moves some failures off CommandFailed, and an allowed code is
752        // allowed whatever the wrapper made of the message.
753        Err(e)
754            if e.exit_code()
755                .is_some_and(|code| allowed_codes.contains(&code)) =>
756        {
757            let exit_code = e.exit_code().unwrap_or(-1);
758            let (stdout, stderr) = match &e {
759                Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
760                Error::Auth { message, .. }
761                | Error::Config { message, .. }
762                | Error::NotTrustedDirectory { message, .. }
763                | Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
764                _ => (String::new(), String::new()),
765            };
766            Ok(CommandOutput {
767                stdout,
768                stderr,
769                exit_code,
770                success: false,
771            })
772        }
773        other => other,
774    }
775}
776
777/// Run a codex command, writing `prompt` to the child's stdin.
778///
779/// For `codex exec -`, where the prompt is delivered on stdin rather than as
780/// an argument. The prompt is written and the handle dropped, so the CLI sees
781/// EOF and stops waiting for more.
782///
783/// Retry does not apply. The policy is deliberately ignored rather than
784/// honored: a retry would have to write the prompt again, and the first
785/// attempt has already moved the caller's data into a pipe that cannot be
786/// rewound. Silently retrying with an empty stdin would be worse than not
787/// retrying at all.
788pub async fn run_codex_with_stdin_prompt(
789    codex: &Codex,
790    args: Vec<String>,
791    prompt: &str,
792) -> Result<CommandOutput> {
793    let span = command_span("codex.exec", codex, &args);
794    let outcome_span = span.clone();
795    let command_args = assemble_args(codex, args);
796
797    async move {
798        debug!(
799            arg_count = command_args.len(),
800            prompt_bytes = prompt.len(),
801            "executing codex command with a stdin prompt"
802        );
803
804        let mut outcome = SpanOutcome::start(outcome_span);
805        let stop = codex.timeout.map(timeout_stop);
806        let result = run_internal_inner(
807            SpawnSpec {
808                binary: &codex.binary,
809                args: &command_args,
810                env: &codex.env,
811                clear_env: codex.clear_env,
812                working_dir: codex.working_dir.as_deref(),
813                stdin_prompt: Some(prompt),
814                process_group: codex.process_group,
815                termination_signal: codex.termination_signal,
816                output_limit: codex.output_limit,
817                die_with_parent: codex.die_with_parent,
818                on_spawn: codex.on_spawn.as_ref(),
819            },
820            stop,
821            codex.termination_grace,
822        )
823        .await;
824        outcome.settle_from(&result);
825        result
826    }
827    .instrument(span)
828    .await
829}
830
831/// Run a codex command with a stdin prompt and an explicit cancellation signal.
832///
833/// Cancellation and the client's timeout both terminate the owned process
834/// group and await the direct child before returning. Retry does not apply.
835pub async fn run_codex_with_stdin_prompt_cancellable<C>(
836    codex: &Codex,
837    args: Vec<String>,
838    prompt: &str,
839    cancel: C,
840) -> Result<CommandOutput>
841where
842    C: std::future::Future<Output = ()> + Send,
843{
844    let span = command_span("codex.exec", codex, &args);
845    let outcome_span = span.clone();
846    let command_args = assemble_args(codex, args);
847
848    async move {
849        debug!(
850            arg_count = command_args.len(),
851            prompt_bytes = prompt.len(),
852            "executing cancellable codex command with a stdin prompt"
853        );
854
855        let mut outcome = SpanOutcome::start(outcome_span);
856        let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
857        let result = run_internal_inner(
858            SpawnSpec {
859                binary: &codex.binary,
860                args: &command_args,
861                env: &codex.env,
862                clear_env: codex.clear_env,
863                working_dir: codex.working_dir.as_deref(),
864                stdin_prompt: Some(prompt),
865                process_group: codex.process_group,
866                termination_signal: codex.termination_signal,
867                output_limit: codex.output_limit,
868                die_with_parent: codex.die_with_parent,
869                on_spawn: codex.on_spawn.as_ref(),
870            },
871            Some(stop),
872            codex.termination_grace,
873        )
874        .await;
875
876        match &result {
877            Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
878            other => outcome.settle_from_ref(other),
879        }
880        result
881    }
882    .instrument(span)
883    .await
884}
885
886#[derive(Clone, Copy, Debug)]
887enum StopReason {
888    Cancelled { grace_seconds: u64 },
889    Timeout { timeout_seconds: u64 },
890}
891
892impl StopReason {
893    fn into_error(self) -> Error {
894        match self {
895            Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
896            Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
897        }
898    }
899}
900
901type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
902
903fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
904    Box::pin(async move {
905        tokio::time::sleep(timeout).await;
906        StopReason::Timeout {
907            timeout_seconds: timeout.as_secs(),
908        }
909    })
910}
911
912fn cancellation_or_timeout<'a, C>(
913    cancel: C,
914    timeout: Option<Duration>,
915    grace: Duration,
916) -> StopFuture<'a>
917where
918    C: std::future::Future<Output = ()> + Send + 'a,
919{
920    Box::pin(async move {
921        match timeout {
922            Some(timeout) => tokio::select! {
923                () = cancel => StopReason::Cancelled {
924                    grace_seconds: grace.as_secs(),
925                },
926                () = tokio::time::sleep(timeout) => StopReason::Timeout {
927                    timeout_seconds: timeout.as_secs(),
928                },
929            },
930            None => {
931                cancel.await;
932                StopReason::Cancelled {
933                    grace_seconds: grace.as_secs(),
934                }
935            }
936        }
937    })
938}
939
940/// Everything one spawn needs, gathered so the signature stays readable.
941struct SpawnSpec<'a> {
942    binary: &'a std::path::Path,
943    args: &'a [String],
944    env: &'a std::collections::HashMap<String, String>,
945    /// Whether the child starts without the wrapper's ambient environment.
946    clear_env: bool,
947    working_dir: Option<&'a std::path::Path>,
948    /// A prompt to deliver on stdin, for `codex exec -`.
949    stdin_prompt: Option<&'a str>,
950    /// Whether the run leads its own process group.
951    process_group: bool,
952    termination_signal: crate::TerminationSignal,
953    /// Stop capturing a stream once it passes this many bytes.
954    output_limit: Option<usize>,
955    /// Whether the child should die with its immediate parent on Linux.
956    die_with_parent: bool,
957    /// Who to notify immediately after a successful spawn.
958    on_spawn: Option<&'a crate::SpawnObserver>,
959}
960
961/// Read one captured stream to EOF, or stop once it passes `limit`.
962///
963/// With no limit this is `read_to_end`, unchanged. With one, the buffer never
964/// exceeds the ceiling, so a run holds at most twice it across the two
965/// streams no matter what the child prints.
966///
967/// Exceeding it is an error rather than a truncated success. A prefix
968/// returned as though it were the whole result would be indistinguishable
969/// from a short answer, which is the failure worth preventing. Enough of the
970/// prefix to identify the runaway is logged instead.
971async fn capture<R>(
972    reader: &mut R,
973    limit: Option<usize>,
974    stream: OutputStream,
975    working_dir: Option<&std::path::Path>,
976) -> Result<Vec<u8>>
977where
978    R: tokio::io::AsyncRead + Unpin,
979{
980    use tokio::io::AsyncReadExt;
981
982    let io_error = |e: std::io::Error| Error::Io {
983        message: format!("failed to read codex {stream}: {e}"),
984        source: e,
985        working_dir: working_dir.map(std::path::Path::to_path_buf),
986    };
987
988    let Some(limit) = limit else {
989        let mut bytes = Vec::new();
990        reader.read_to_end(&mut bytes).await.map_err(io_error)?;
991        return Ok(bytes);
992    };
993
994    let mut bytes = Vec::new();
995    let mut chunk = [0u8; CAPTURE_CHUNK];
996    loop {
997        let read = reader.read(&mut chunk).await.map_err(io_error)?;
998        if read == 0 {
999            return Ok(bytes);
1000        }
1001        if bytes.len() + read > limit {
1002            tracing::warn!(
1003                %stream,
1004                limit_bytes = limit,
1005                captured_bytes = bytes.len(),
1006                "codex output exceeded its capture limit; stopping the run"
1007            );
1008            return Err(Error::OutputLimitExceeded {
1009                stream,
1010                limit_bytes: limit,
1011            });
1012        }
1013        bytes.extend_from_slice(&chunk[..read]);
1014    }
1015}
1016
1017/// Read size for a bounded capture. Large enough not to syscall per line,
1018/// small enough that the overshoot before noticing stays trivial.
1019const CAPTURE_CHUNK: usize = 8 * 1024;
1020
1021async fn run_internal_inner(
1022    spec: SpawnSpec<'_>,
1023    stop: Option<StopFuture<'_>>,
1024    grace: Duration,
1025) -> Result<CommandOutput> {
1026    let SpawnSpec {
1027        binary,
1028        args,
1029        env,
1030        clear_env,
1031        working_dir,
1032        stdin_prompt,
1033        process_group,
1034        termination_signal,
1035        output_limit,
1036        die_with_parent,
1037        on_spawn,
1038    } = spec;
1039    let mut cmd = child_command(binary, process_group, die_with_parent);
1040    cmd.args(args);
1041
1042    // Pipe stdin only when there is a prompt to write. Otherwise close it, so
1043    // the child neither inherits nor blocks on the parent's.
1044    if stdin_prompt.is_some() {
1045        cmd.stdin(std::process::Stdio::piped());
1046    } else {
1047        cmd.stdin(std::process::Stdio::null());
1048    }
1049
1050    if let Some(dir) = working_dir {
1051        cmd.current_dir(dir);
1052    }
1053
1054    apply_child_environment(&mut cmd, clear_env, env);
1055
1056    // Always spawn rather than using `Command::output`: the pid is needed to
1057    // signal the process group, and `output` does not surrender it. It also
1058    // forces stdin to null, which the stdin-prompt path cannot use.
1059    cmd.stdout(std::process::Stdio::piped());
1060    cmd.stderr(std::process::Stdio::piped());
1061
1062    let mut child = cmd.spawn().map_err(|e| Error::Io {
1063        message: format!("failed to spawn codex: {e}"),
1064        source: e,
1065        working_dir: working_dir.map(|p| p.to_path_buf()),
1066    })?;
1067
1068    // Armed for the whole run. If this future is dropped, its Drop signals the
1069    // group, which also reaches descendants still in that group.
1070    // Only meaningful when the run leads its own group. Sharing the parent's
1071    // means signalling it would hit the parent too.
1072    let mut group = arm_and_notify(process_group, termination_signal, child.id(), on_spawn);
1073    let child_stdin = child.stdin.take();
1074    let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
1075    let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
1076
1077    let write = async move {
1078        let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
1079            return Ok(());
1080        };
1081        use tokio::io::AsyncWriteExt;
1082        stdin
1083            .write_all(prompt.as_bytes())
1084            .await
1085            .map_err(|e| Error::Io {
1086                message: format!("failed to write the prompt to codex stdin: {e}"),
1087                source: e,
1088                working_dir: working_dir.map(|p| p.to_path_buf()),
1089            })?;
1090        // Closing the write half is what tells the CLI the prompt is
1091        // complete. Without it the child waits for more input.
1092        stdin.shutdown().await.map_err(|e| Error::Io {
1093            message: format!("failed to close codex stdin: {e}"),
1094            source: e,
1095            working_dir: working_dir.map(|p| p.to_path_buf()),
1096        })
1097    };
1098
1099    // Concurrently, not sequentially: a prompt larger than the pipe buffer
1100    // blocks until the child reads it, and a child that writes to stdout
1101    // meanwhile blocks until we read that. Waiting for the write to finish
1102    // before draining stdout would deadlock both.
1103    let read_stdout = async {
1104        capture(
1105            &mut child_stdout,
1106            output_limit,
1107            OutputStream::Stdout,
1108            working_dir,
1109        )
1110        .await
1111    };
1112    let read_stderr = async {
1113        capture(
1114            &mut child_stderr,
1115            output_limit,
1116            OutputStream::Stderr,
1117            working_dir,
1118        )
1119        .await
1120    };
1121    let run = async {
1122        let ((), stdout, stderr) = tokio::try_join!(write, read_stdout, read_stderr)?;
1123        // Do not reap while pipes are still open: if cancellation wins then,
1124        // delayed group signaling must not target a recycled group-leader PID.
1125        let status = child.wait().await.map_err(|e| wait_error(e, working_dir))?;
1126        Ok::<_, Error>((stdout, stderr, status))
1127    };
1128
1129    let finished = match stop {
1130        None => Ok(run.await),
1131        // Racing the run against the caller's signal. Cancellation here is
1132        // graceful, which is the whole reason it cannot live in `Drop`:
1133        // asking a process to stop and then waiting requires awaiting.
1134        Some(stop) => tokio::select! {
1135            outcome = run => Ok(outcome),
1136            reason = stop => Err(reason),
1137        },
1138    };
1139
1140    let (stdout, stderr, status) = match finished {
1141        Ok(Ok(finished)) => finished,
1142        Ok(Err(error)) => {
1143            // A stdin or pipe failure can happen while the child continues
1144            // running. Treat it as a stop request and settle ownership before
1145            // exposing the I/O error.
1146            let cleanup = terminate_and_reap_draining(
1147                &mut child,
1148                &mut group,
1149                grace,
1150                working_dir,
1151                &mut child_stdout,
1152                &mut child_stderr,
1153            )
1154            .await;
1155            return Err(Error::after_cleanup(error, cleanup));
1156        }
1157        Err(reason) => {
1158            // The run future is gone before this branch executes, returning
1159            // ownership of `child` so cleanup can explicitly reap it.
1160            // `GroupKillGuard::terminate` reaches same-group descendants. The
1161            // direct-child kill below is the portable fallback and makes the
1162            // wait authoritative on every platform.
1163            let cleanup = terminate_and_reap_draining(
1164                &mut child,
1165                &mut group,
1166                grace,
1167                working_dir,
1168                &mut child_stdout,
1169                &mut child_stderr,
1170            )
1171            .await;
1172            return Err(Error::after_cleanup(reason.into_error(), cleanup));
1173        }
1174    };
1175
1176    // Finished on its own, so there is no group left to kill.
1177    group.disarm();
1178
1179    let stdout = String::from_utf8_lossy(&stdout).to_string();
1180    let stderr = String::from_utf8_lossy(&stderr).to_string();
1181    let exit_code = status.code().unwrap_or(-1);
1182
1183    if !status.success() {
1184        return Err(Error::from_command_failure(
1185            format!("{} {}", binary.display(), args.join(" ")),
1186            exit_code,
1187            stdout,
1188            stderr,
1189            working_dir.map(|p| p.to_path_buf()),
1190        ));
1191    }
1192
1193    Ok(CommandOutput {
1194        stdout,
1195        stderr,
1196        exit_code,
1197        success: true,
1198    })
1199}
1200
1201/// Keep both pipes open and flowing while shutdown runs. Shutdown output is
1202/// discarded in fixed-size chunks, never parsed or sent to event handlers.
1203/// The drain is dropped when cleanup finishes even if an escaped descendant
1204/// still holds a pipe open. No child wait is polled before group signaling ends.
1205pub(crate) async fn terminate_and_reap_draining<O, E>(
1206    child: &mut tokio::process::Child,
1207    group: &mut GroupKillGuard,
1208    grace: Duration,
1209    working_dir: Option<&std::path::Path>,
1210    stdout: &mut O,
1211    stderr: &mut E,
1212) -> Result<()>
1213where
1214    O: tokio::io::AsyncRead + Unpin,
1215    E: tokio::io::AsyncRead + Unpin,
1216{
1217    let drain = async {
1218        let mut stdout_sink = tokio::io::sink();
1219        let mut stderr_sink = tokio::io::sink();
1220        let _ = tokio::join!(
1221            tokio::io::copy(stdout, &mut stdout_sink),
1222            tokio::io::copy(stderr, &mut stderr_sink),
1223        );
1224        std::future::pending::<()>().await;
1225    };
1226    let result = tokio::select! {
1227        result = terminate_and_reap(child, group, grace) => {
1228            result.map(|_| ()).map_err(|e| wait_error(e, working_dir))
1229        },
1230        () = drain => unreachable!("the drain waits until shutdown finishes"),
1231    };
1232    #[cfg(test)]
1233    let result = result.and_then(|()| injected_cleanup_failure(working_dir));
1234    if result.is_err() {
1235        tracing::warn!("codex cleanup failed; the child may not have been reaped");
1236    }
1237    result
1238}
1239
1240#[cfg(test)]
1241thread_local! {
1242    static INJECT_CLEANUP_FAILURE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1243}
1244
1245/// Test-only fault injection for [`terminate_and_reap_draining`].
1246///
1247/// While armed, a cleanup on this thread that actually succeeded reports a
1248/// synthetic I/O error instead. The real termination and wait still run first,
1249/// so the fixture child is reaped either way. This exercises how callers
1250/// report a failed cleanup; it does not show that any syscall can fail.
1251/// Thread-local because `#[tokio::test]` runs each test on its own
1252/// current-thread runtime, which keeps concurrent tests isolated. Every caller
1253/// is a unix-only test, hence the `dead_code` allowance elsewhere.
1254#[cfg(test)]
1255#[cfg_attr(not(unix), allow(dead_code))]
1256pub(crate) struct CleanupFailureInjection(std::marker::PhantomData<std::rc::Rc<()>>);
1257
1258#[cfg(test)]
1259#[cfg_attr(not(unix), allow(dead_code))]
1260impl CleanupFailureInjection {
1261    pub(crate) fn arm() -> Self {
1262        INJECT_CLEANUP_FAILURE.with(|armed| armed.set(true));
1263        // The thread-local guard must stay on its originating test thread.
1264        Self(std::marker::PhantomData)
1265    }
1266}
1267
1268#[cfg(test)]
1269impl Drop for CleanupFailureInjection {
1270    fn drop(&mut self) {
1271        INJECT_CLEANUP_FAILURE.with(|armed| armed.set(false));
1272    }
1273}
1274
1275#[cfg(test)]
1276fn injected_cleanup_failure(working_dir: Option<&std::path::Path>) -> Result<()> {
1277    if INJECT_CLEANUP_FAILURE.with(std::cell::Cell::get) {
1278        return Err(wait_error(
1279            std::io::Error::other("injected cleanup failure"),
1280            working_dir,
1281        ));
1282    }
1283    Ok(())
1284}
1285
1286pub(crate) async fn terminate_and_reap(
1287    child: &mut tokio::process::Child,
1288    group: &mut GroupKillGuard,
1289    grace: Duration,
1290) -> std::io::Result<(ExitStatus, Option<ShutdownAction>)> {
1291    let (soft, mut hard) = group.terminate(grace).await?;
1292    let status = if let Some(status) = child.try_wait()? {
1293        status
1294    } else {
1295        match child.start_kill() {
1296            Ok(()) => hard = true,
1297            Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {}
1298            Err(error) => return Err(error),
1299        }
1300        child.wait().await?
1301    };
1302    // A natural exit can race a successful kill syscall. The native status
1303    // tells us whether the hard stop could have been what ended the child.
1304    let action = if hard && hard_kill_matches(status) {
1305        Some(ShutdownAction::Kill)
1306    } else {
1307        soft
1308    };
1309    Ok((status, action))
1310}
1311
1312pub(crate) fn hard_kill_matches(status: ExitStatus) -> bool {
1313    #[cfg(unix)]
1314    {
1315        use std::os::unix::process::ExitStatusExt;
1316        status.signal() == Some(libc::SIGKILL)
1317    }
1318    #[cfg(windows)]
1319    {
1320        // Both std::process::Child::kill and the app-server kill switch use 1.
1321        status.code() == Some(1)
1322    }
1323    #[cfg(not(any(unix, windows)))]
1324    {
1325        let _ = status;
1326        true
1327    }
1328}
1329
1330fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
1331    Error::Io {
1332        message: format!("failed to wait on codex: {error}"),
1333        source: error,
1334        working_dir: working_dir.map(|p| p.to_path_buf()),
1335    }
1336}
1337
1338/// Apply the client environment policy to a direct child process.
1339///
1340/// Kept in one helper because buffered and streaming execution construct
1341/// separate commands. Clearing must happen before explicit values are added.
1342pub(crate) fn apply_child_environment(
1343    cmd: &mut Command,
1344    clear_env: bool,
1345    env: &std::collections::HashMap<String, String>,
1346) {
1347    if clear_env {
1348        cmd.env_clear();
1349    }
1350    cmd.envs(env);
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355    use super::*;
1356    use crate::CodexCommand;
1357
1358    #[test]
1359    fn production_commands_use_child_command() {
1360        fn check_directory(dir: &Path) {
1361            for entry in std::fs::read_dir(dir).unwrap() {
1362                let entry = entry.unwrap();
1363                let path = entry.path();
1364                if entry.file_type().unwrap().is_dir() {
1365                    check_directory(&path);
1366                    continue;
1367                }
1368                if path.extension().and_then(|ext| ext.to_str()) != Some("rs")
1369                    || entry.file_name() == "test_support.rs"
1370                {
1371                    continue;
1372                }
1373                let source = std::fs::read_to_string(&path).unwrap();
1374                let mut test_item = false;
1375                let mut skip_body = false;
1376                for (index, line) in source.lines().enumerate() {
1377                    if skip_body {
1378                        // Rustfmt puts a top-level item's closing brace at column zero.
1379                        skip_body = line != "}";
1380                        continue;
1381                    }
1382                    test_item |= line == "#[cfg(test)]" || line.starts_with("#[cfg(all(test,");
1383                    if line.is_empty()
1384                        || line.starts_with("#[")
1385                        || line.trim_start().starts_with("//")
1386                    {
1387                        continue;
1388                    }
1389                    let shared_constructor = entry.file_name() == "exec.rs"
1390                        && line.starts_with("pub(crate) fn child_command(");
1391                    skip_body = (std::mem::take(&mut test_item) || shared_constructor)
1392                        && line.ends_with('{');
1393                    if skip_body {
1394                        continue;
1395                    }
1396                    // If this fails, use child_command for the new launch so
1397                    // it gets the same process policies as the existing paths.
1398                    assert!(
1399                        line.match_indices("Command::new(").all(|(offset, _)| {
1400                            line[..offset].ends_with(|ch: char| ch.is_alphanumeric() || ch == '_')
1401                        }),
1402                        "{}:{}: use crate::exec::child_command for production spawns",
1403                        path.display(),
1404                        index + 1
1405                    );
1406                }
1407            }
1408        }
1409
1410        check_directory(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"));
1411    }
1412
1413    #[cfg(all(unix, not(target_os = "fuchsia")))]
1414    async fn buffered_descriptor_probe(expected: &str) {
1415        use crate::test_support::{inheritable_pipe_writer, stdin_echo_codex};
1416        use std::os::fd::AsRawFd;
1417
1418        let writer = inheritable_pipe_writer();
1419        let codex = stdin_echo_codex()
1420            .env("CODEX_WRAPPER_TEST_FD", writer.as_raw_fd().to_string())
1421            .build()
1422            .unwrap();
1423        let output = crate::ExecCommand::new("probe")
1424            .execute(&codex)
1425            .await
1426            .unwrap();
1427        assert!(
1428            output.stdout.contains(&format!(r#""text":"{expected}""#)),
1429            "{output:?}"
1430        );
1431    }
1432
1433    #[cfg(any(target_os = "macos", target_os = "ios"))]
1434    #[tokio::test]
1435    async fn buffered_exec_marks_inherited_descriptors_close_on_exec() {
1436        buffered_descriptor_probe("fd-closed").await;
1437    }
1438
1439    // Fuchsia's native launcher only transfers the configured stdio.
1440    #[cfg(all(
1441        unix,
1442        not(any(target_os = "macos", target_os = "ios", target_os = "fuchsia"))
1443    ))]
1444    #[tokio::test]
1445    async fn buffered_exec_preserves_inheritable_descriptors() {
1446        buffered_descriptor_probe("fd-open").await;
1447    }
1448
1449    #[cfg(unix)]
1450    #[tokio::test]
1451    async fn spawn_reports_missing_and_non_executable_binaries() {
1452        use std::os::unix::fs::OpenOptionsExt;
1453
1454        let binary = crate::test_support::PidFile::new("unlaunchable-binary");
1455        let codex = Codex::builder().binary(binary.path()).build().unwrap();
1456        for errno in [libc::ENOENT, libc::EACCES] {
1457            if errno == libc::EACCES {
1458                std::fs::OpenOptions::new()
1459                    .write(true)
1460                    .create_new(true)
1461                    .mode(0o600)
1462                    .open(binary.path())
1463                    .unwrap();
1464            }
1465            let error = crate::VersionCommand::new()
1466                .execute(&codex)
1467                .await
1468                .unwrap_err();
1469            assert!(
1470                matches!(&error, Error::Io { message, source, working_dir: None }
1471                    if message == &format!("failed to spawn codex: {source}")
1472                    && source.raw_os_error() == Some(errno)),
1473                "expected spawn errno {errno}, got {error:?}"
1474            );
1475        }
1476    }
1477
1478    #[test]
1479    fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
1480        let codex = Codex::builder()
1481            .binary("/bin/echo")
1482            .config("features.rollout_budget=false")
1483            .enable("rollout_budget")
1484            .disable("rollout_budget")
1485            .arg("--enable=rollout_budget")
1486            .arg("--disable=rollout_budget")
1487            .arg("--disable")
1488            .arg("rollout_budget")
1489            .enable("keep-enabled")
1490            .disable("keep-disabled")
1491            .build()
1492            .expect("echo must exist");
1493        let budget = crate::RolloutBudgetConfig::builder(10_000)
1494            .build()
1495            .expect("valid budget");
1496        let expected = budget.config_override();
1497        let opening = crate::ExecCommand::new("hi")
1498            .rollout_budget(budget.clone())
1499            .args();
1500        let resumed = crate::ExecResumeCommand::new()
1501            .session_id("thread")
1502            .rollout_budget(budget)
1503            .args();
1504
1505        for args in [opening, resumed] {
1506            let assembled = assemble_args(&codex, args);
1507            assert!(assembled.iter().any(|arg| arg == &expected));
1508            assert!(
1509                !assembled.windows(2).any(|pair| {
1510                    matches!(pair[0].as_str(), "--enable" | "--disable")
1511                        && pair[1] == "rollout_budget"
1512                }),
1513                "typed budget must suppress paired client toggles: {assembled:?}"
1514            );
1515            assert!(
1516                !assembled.iter().any(|arg| {
1517                    matches!(
1518                        arg.as_str(),
1519                        "--enable=rollout_budget" | "--disable=rollout_budget"
1520                    )
1521                }),
1522                "typed budget must suppress equals-form client toggles: {assembled:?}"
1523            );
1524            assert!(
1525                assembled
1526                    .windows(2)
1527                    .any(|pair| pair == ["--enable", "keep-enabled"])
1528            );
1529            assert!(
1530                assembled
1531                    .windows(2)
1532                    .any(|pair| pair == ["--disable", "keep-disabled"])
1533            );
1534        }
1535    }
1536
1537    fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
1538        CommandOutput {
1539            stdout: stdout.to_string(),
1540            stderr: stderr.to_string(),
1541            exit_code: 0,
1542            success: true,
1543        }
1544    }
1545
1546    #[test]
1547    fn shell_quote_leaves_plain_words_alone() {
1548        assert_eq!(shell_quote("exec"), "exec");
1549        assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
1550        assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
1551    }
1552
1553    #[test]
1554    fn shell_quote_wraps_anything_a_shell_would_read() {
1555        assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
1556        assert_eq!(shell_quote("$HOME"), "'$HOME'");
1557        assert_eq!(shell_quote("a;b"), "'a;b'");
1558        assert_eq!(shell_quote("*.rs"), "'*.rs'");
1559        assert_eq!(shell_quote("it's"), r"'it'\''s'");
1560    }
1561
1562    /// An unquoted empty string would disappear from the rendered command,
1563    /// making the preview describe a different invocation than it previews.
1564    #[test]
1565    fn shell_quote_keeps_the_empty_argument_visible() {
1566        assert_eq!(shell_quote(""), "''");
1567    }
1568
1569    #[test]
1570    fn debug_short_output_not_truncated() {
1571        let output = make_output("hello", "world");
1572        let debug = format!("{output:?}");
1573        assert!(debug.contains("hello"));
1574        assert!(debug.contains("world"));
1575        assert!(!debug.contains("bytes total"));
1576    }
1577
1578    #[test]
1579    fn debug_long_output_truncated() {
1580        let long = "x".repeat(300);
1581        let output = make_output(&long, &long);
1582        let debug = format!("{output:?}");
1583        assert!(debug.contains("... (300 bytes total)"));
1584        assert!(!debug.contains(&long));
1585    }
1586
1587    /// Compatibility is explicit: callers that do not opt in keep the
1588    /// ambient environment they relied on before `clear_env` existed.
1589    #[cfg(unix)]
1590    #[tokio::test]
1591    async fn child_environment_is_inherited_by_default() {
1592        let capture = crate::test_support::EnvCapture::new("env-default");
1593        let codex = crate::test_support::env_capturing_codex(&capture)
1594            .build()
1595            .expect("bash must exist");
1596
1597        crate::ExecCommand::new("probe")
1598            .execute(&codex)
1599            .await
1600            .unwrap();
1601
1602        let environment = capture.read();
1603        assert_eq!(
1604            environment.get("PATH"),
1605            Some(&std::env::var("PATH").expect("test process must have PATH"))
1606        );
1607    }
1608
1609    /// The timeout and ordinary buffered paths use different wrapper entry
1610    /// points. Opening and resume both have to reach the same environment
1611    /// policy, and explicit values on either side of `clear_env` must survive.
1612    #[cfg(unix)]
1613    #[tokio::test]
1614    async fn cleared_environment_reaches_buffered_open_and_resume() {
1615        let capture = crate::test_support::EnvCapture::new("env-buffered");
1616        let opening_client = crate::test_support::env_capturing_codex(&capture)
1617            .clear_env()
1618            .env("CODEX_WRAPPER_EXPLICIT", "opening")
1619            .timeout(Duration::from_secs(2))
1620            .build()
1621            .expect("bash must exist");
1622
1623        crate::ExecCommand::new("probe")
1624            .execute(&opening_client)
1625            .await
1626            .unwrap();
1627        let opening_environment = capture.read();
1628        assert!(!opening_environment.contains_key("PATH"));
1629        assert_eq!(
1630            opening_environment
1631                .get("CODEX_WRAPPER_EXPLICIT")
1632                .map(String::as_str),
1633            Some("opening")
1634        );
1635        assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
1636
1637        let resume_client = crate::test_support::env_capturing_codex(&capture)
1638            .clear_env()
1639            .env("CODEX_WRAPPER_EXPLICIT", "resume")
1640            .build()
1641            .expect("bash must exist");
1642        crate::ExecResumeCommand::new()
1643            .last()
1644            .execute(&resume_client)
1645            .await
1646            .unwrap();
1647        let resume_environment = capture.read();
1648        assert!(!resume_environment.contains_key("PATH"));
1649        assert_eq!(
1650            resume_environment
1651                .get("CODEX_WRAPPER_EXPLICIT")
1652                .map(String::as_str),
1653            Some("resume")
1654        );
1655    }
1656
1657    /// Stdin delivery and graceful cancellation each construct their own
1658    /// spawn specification, so cover both instead of treating the buffered
1659    /// test as proof for them.
1660    #[cfg(unix)]
1661    #[tokio::test]
1662    async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
1663        let capture = crate::test_support::EnvCapture::new("env-specialized");
1664        let codex = crate::test_support::env_capturing_codex(&capture)
1665            .env("CODEX_WRAPPER_EXPLICIT", "specialized")
1666            .clear_env()
1667            .build()
1668            .expect("bash must exist");
1669
1670        crate::ExecCommand::new("stdin prompt")
1671            .prompt_via_stdin()
1672            .execute(&codex)
1673            .await
1674            .unwrap();
1675        let stdin_environment = capture.read();
1676        assert!(!stdin_environment.contains_key("PATH"));
1677        assert_eq!(
1678            stdin_environment
1679                .get("CODEX_WRAPPER_EXPLICIT")
1680                .map(String::as_str),
1681            Some("specialized")
1682        );
1683
1684        let never = std::future::pending::<()>();
1685        run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
1686            .await
1687            .unwrap();
1688        let cancellable_environment = capture.read();
1689        assert!(!cancellable_environment.contains_key("PATH"));
1690        assert_eq!(
1691            cancellable_environment
1692                .get("CODEX_WRAPPER_EXPLICIT")
1693                .map(String::as_str),
1694            Some("specialized")
1695        );
1696    }
1697
1698    #[cfg(unix)]
1699    #[tokio::test]
1700    async fn environment_values_do_not_leak_into_spawn_errors() {
1701        let secret = "spawn-error-must-not-leak-this";
1702        let codex = Codex::builder()
1703            .binary("/codex-wrapper/this-binary-does-not-exist")
1704            .clear_env()
1705            .env("CODEX_WRAPPER_SECRET", secret)
1706            .build()
1707            .unwrap();
1708
1709        let error = run_codex(&codex, vec!["exec".into()])
1710            .await
1711            .expect_err("the fake path must not spawn");
1712        assert!(!error.to_string().contains(secret));
1713        assert!(!format!("{error:?}").contains(secret));
1714    }
1715
1716    /// A wrapper timeout is not terminal until the direct child is reaped.
1717    #[cfg(unix)]
1718    #[tokio::test]
1719    async fn timeout_kills_the_spawned_process() {
1720        use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1721
1722        let pid_file = PidFile::new("exec-timeout");
1723        let codex = blocking_codex(&pid_file)
1724            .timeout(Duration::from_millis(500))
1725            .build()
1726            .expect("bash must exist");
1727
1728        let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
1729        assert!(
1730            matches!(result, Err(Error::Timeout { .. })),
1731            "expected timeout error, got: {result:?}"
1732        );
1733
1734        let pid = pid_file.read_pid().await;
1735        assert!(
1736            !is_running_for_test(pid),
1737            "codex ({pid}) survived the timeout"
1738        );
1739    }
1740
1741    /// The caller dropping the future is the case an operator kill or a
1742    /// graceful shutdown produces, with no wrapper timeout involved.
1743    #[cfg(unix)]
1744    #[tokio::test]
1745    async fn cancellation_kills_the_spawned_process() {
1746        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
1747
1748        let pid_file = PidFile::new("exec-cancel");
1749        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
1750
1751        let cancelled = tokio::time::timeout(
1752            Duration::from_millis(500),
1753            run_codex(&codex, vec!["exec".into(), "probe".into()]),
1754        )
1755        .await;
1756        assert!(
1757            cancelled.is_err(),
1758            "fake codex should still have been running, got: {cancelled:?}"
1759        );
1760
1761        let pid = pid_file.read_pid().await;
1762        assert!(
1763            wait_until_gone(pid).await,
1764            "codex ({pid}) survived the dropped future"
1765        );
1766    }
1767
1768    /// Minimal recording subscriber, written by hand because #63 rules out a
1769    /// new dependency and `tracing-subscriber` would be one.
1770    ///
1771    /// Installed once as the **global** default, fanning out to a per-thread
1772    /// sink. A thread-local `set_default` is not enough: tracing caches
1773    /// callsite interest globally, so a test running concurrently against no
1774    /// subscriber caches this crate's span callsites as `never` and the
1775    /// recording test then sees nothing. That produced a real flake, about one
1776    /// run in three. A single always-enabled global subscriber keeps interest
1777    /// stable, and the per-thread sink keeps tests isolated.
1778    #[cfg(unix)]
1779    mod recorder {
1780        use std::cell::RefCell;
1781        use std::sync::{Arc, Mutex, Once};
1782
1783        use tracing::field::{Field, Visit};
1784        use tracing::span::{Attributes, Id, Record};
1785        use tracing::{Event, Metadata, Subscriber};
1786
1787        type Sink = Arc<Mutex<Vec<(String, String)>>>;
1788
1789        thread_local! {
1790            static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1791        }
1792
1793        struct Global;
1794
1795        impl Global {
1796            fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
1797                SINK.with(|sink| {
1798                    if let Some(sink) = sink.borrow().as_ref() {
1799                        f(&mut sink.lock().unwrap());
1800                    }
1801                });
1802            }
1803        }
1804
1805        impl Subscriber for Global {
1806            /// Always true, so callsite interest is never cached as `never`.
1807            fn enabled(&self, _: &Metadata<'_>) -> bool {
1808                true
1809            }
1810            fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1811                Self::collect(|fields| attrs.record(&mut Collect(fields)));
1812                Id::from_u64(1)
1813            }
1814            fn record(&self, _: &Id, values: &Record<'_>) {
1815                Self::collect(|fields| values.record(&mut Collect(fields)));
1816            }
1817            fn record_follows_from(&self, _: &Id, _: &Id) {}
1818            fn event(&self, event: &Event<'_>) {
1819                Self::collect(|fields| event.record(&mut Collect(fields)));
1820            }
1821            fn enter(&self, _: &Id) {}
1822            fn exit(&self, _: &Id) {}
1823        }
1824
1825        struct Collect<'a>(&'a mut Vec<(String, String)>);
1826
1827        impl Visit for Collect<'_> {
1828            fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
1829                self.0.push((field.name().into(), format!("{value:?}")));
1830            }
1831            fn record_str(&mut self, field: &Field, value: &str) {
1832                self.0.push((field.name().into(), value.into()));
1833            }
1834            fn record_i64(&mut self, field: &Field, value: i64) {
1835                self.0.push((field.name().into(), value.to_string()));
1836            }
1837            fn record_u64(&mut self, field: &Field, value: u64) {
1838                self.0.push((field.name().into(), value.to_string()));
1839            }
1840        }
1841
1842        pub(super) struct Recorder(Sink);
1843
1844        impl Recorder {
1845            /// Start recording spans raised on this thread.
1846            pub(super) fn install() -> Self {
1847                static INIT: Once = Once::new();
1848                INIT.call_once(|| {
1849                    let _ = tracing::subscriber::set_global_default(Global);
1850                });
1851                let sink: Sink = Arc::new(Mutex::new(Vec::new()));
1852                SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
1853                Self(sink)
1854            }
1855
1856            pub(super) fn dump(&self) -> String {
1857                format!("{:?}", self.0.lock().unwrap())
1858            }
1859
1860            pub(super) fn value(&self, field: &str) -> Option<String> {
1861                self.0
1862                    .lock()
1863                    .unwrap()
1864                    .iter()
1865                    .rev()
1866                    .find(|(name, _)| name == field)
1867                    .map(|(_, value)| value.clone())
1868            }
1869        }
1870
1871        impl Drop for Recorder {
1872            fn drop(&mut self) {
1873                SINK.with(|slot| *slot.borrow_mut() = None);
1874            }
1875        }
1876    }
1877
1878    #[cfg(unix)]
1879    #[tokio::test]
1880    async fn span_records_the_subcommand_and_a_clean_outcome() {
1881        let recorder = recorder::Recorder::install();
1882
1883        let codex = Codex::builder()
1884            .binary("/bin/echo")
1885            .build()
1886            .expect("echo must exist");
1887        run_codex(&codex, vec!["exec".into()]).await.unwrap();
1888
1889        assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
1890        assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
1891        assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
1892        assert!(recorder.value("duration_ms").is_some());
1893    }
1894
1895    /// The prompt must never reach the span. It is in argv, so recording the
1896    /// arguments would leak it into any host's logs.
1897    #[cfg(unix)]
1898    #[tokio::test]
1899    async fn span_does_not_carry_the_prompt() {
1900        let recorder = recorder::Recorder::install();
1901
1902        let codex = Codex::builder()
1903            .binary("/bin/echo")
1904            .build()
1905            .expect("echo must exist");
1906        run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
1907            .await
1908            .unwrap();
1909
1910        assert!(!recorder.dump().contains("secret"), "{}", recorder.dump());
1911        assert!(recorder.value("binary").is_none());
1912        assert!(recorder.value("working_dir").is_none());
1913    }
1914
1915    /// A dropped future records an outcome rather than leaving the span open,
1916    /// so an abandoned run is distinguishable from one still in progress.
1917    #[cfg(unix)]
1918    #[tokio::test]
1919    async fn a_cancelled_run_is_recorded_as_cancelled() {
1920        let recorder = recorder::Recorder::install();
1921
1922        let pid_file = crate::test_support::PidFile::new("span-cancel");
1923        let codex = crate::test_support::blocking_codex(&pid_file)
1924            .build()
1925            .expect("bash must exist");
1926
1927        let cancelled = tokio::time::timeout(
1928            Duration::from_millis(300),
1929            run_codex(&codex, vec!["exec".into()]),
1930        )
1931        .await;
1932        assert!(cancelled.is_err(), "the run should still have been going");
1933
1934        assert_eq!(
1935            recorder.value("outcome").as_deref(),
1936            Some("cancelled"),
1937            "recorded: {}",
1938            recorder.dump()
1939        );
1940    }
1941
1942    /// A wrapper timeout is its own outcome, distinct from a caller
1943    /// cancelling: the run reached its deadline rather than being abandoned.
1944    #[cfg(unix)]
1945    #[tokio::test]
1946    async fn a_timed_out_run_is_recorded_as_timeout() {
1947        let recorder = recorder::Recorder::install();
1948
1949        let pid_file = crate::test_support::PidFile::new("span-timeout");
1950        let codex = crate::test_support::blocking_codex(&pid_file)
1951            .timeout(Duration::from_millis(300))
1952            .build()
1953            .expect("bash must exist");
1954
1955        let result = run_codex(&codex, vec!["exec".into()]).await;
1956        assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
1957
1958        assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
1959    }
1960
1961    // -----------------------------------------------------------------
1962    // Bounded capture (#132)
1963    // -----------------------------------------------------------------
1964
1965    #[cfg(unix)]
1966    fn flooding_codex(stream: &str, limit: Option<usize>) -> Codex {
1967        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1968            .join("tests")
1969            .join("fake-codex-floods.sh");
1970        let mut builder = Codex::builder()
1971            .binary("/bin/bash")
1972            .arg(script.to_str().unwrap())
1973            .env("CODEX_WRAPPER_TEST_FLOOD_STREAM", stream);
1974        if let Some(max_bytes) = limit {
1975            builder = builder.output_limit(max_bytes);
1976        }
1977        builder.build().expect("bash must exist")
1978    }
1979
1980    /// The ceiling has to hold on a single unbroken line, or it is really
1981    /// just a line-length check that a runaway one-line writer defeats.
1982    #[cfg(unix)]
1983    #[tokio::test]
1984    async fn a_stream_past_the_ceiling_fails_without_carrying_its_bytes() {
1985        for stream in ["stdout", "stderr"] {
1986            let codex = flooding_codex(stream, Some(64 * 1024));
1987            let error = crate::ExecCommand::new("hello")
1988                .execute(&codex)
1989                .await
1990                .expect_err("the flood exceeds the ceiling");
1991
1992            let Error::OutputLimitExceeded {
1993                stream: reported,
1994                limit_bytes,
1995            } = error
1996            else {
1997                panic!("expected OutputLimitExceeded for {stream}, got {error:?}");
1998            };
1999            assert_eq!(reported.to_string(), stream);
2000            assert_eq!(limit_bytes, 64 * 1024);
2001
2002            // The captured bytes must not ride along in the error, or the
2003            // ceiling has bounded nothing.
2004            let error = Error::OutputLimitExceeded {
2005                stream: reported,
2006                limit_bytes,
2007            };
2008            let rendered = format!("{error} {error:?}");
2009            assert!(!rendered.contains("xxxxxxxx"), "{rendered}");
2010            assert!(rendered.len() < 512, "error text grew with the output");
2011        }
2012    }
2013
2014    /// Off by default, so adding the control changes nothing until a host
2015    /// asks for it. This is also the measurement of what the ceiling buys:
2016    /// the same child hands back a megabyte when nothing bounds it.
2017    #[cfg(unix)]
2018    #[tokio::test]
2019    async fn without_a_ceiling_the_whole_flood_is_captured() {
2020        let codex = flooding_codex("stdout", None);
2021        let result = crate::ExecCommand::new("hello")
2022            .execute(&codex)
2023            .await
2024            .expect("an unbounded capture succeeds, however large");
2025        assert_eq!(result.stdout.len(), 128 * 8192);
2026    }
2027
2028    /// A run that stays under its ceiling is untouched.
2029    #[cfg(unix)]
2030    #[tokio::test]
2031    async fn output_within_the_ceiling_is_returned_whole() {
2032        let codex = crate::test_support::stdin_echo_codex()
2033            .output_limit(64 * 1024)
2034            .build()
2035            .expect("bash must exist");
2036        let result = crate::ExecCommand::new("a short prompt")
2037            .execute(&codex)
2038            .await
2039            .expect("well under the ceiling");
2040        // Whole means whole: the last line of the stream has to survive, not
2041        // just the first, or the ceiling is silently truncating.
2042        assert!(
2043            result.stdout.contains("thread.started"),
2044            "{}",
2045            result.stdout
2046        );
2047        assert!(
2048            result.stdout.contains("turn.completed"),
2049            "{}",
2050            result.stdout
2051        );
2052    }
2053
2054    // -----------------------------------------------------------------
2055    // Classification end to end (#85)
2056    // -----------------------------------------------------------------
2057
2058    #[cfg(unix)]
2059    fn failing_codex(case: &str) -> Codex {
2060        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2061            .join("tests")
2062            .join("fake-codex-failure.sh");
2063        Codex::builder()
2064            .binary("/bin/bash")
2065            .arg(script.to_str().unwrap())
2066            .env("CODEX_WRAPPER_TEST_FAILURE", case)
2067            .build()
2068            .expect("bash must exist")
2069    }
2070
2071    /// Classification has to happen on the spawn path, not only in the
2072    /// constructor, or a caller still gets a bare CommandFailed.
2073    #[cfg(unix)]
2074    #[tokio::test]
2075    async fn a_real_spawn_returns_a_classified_error() {
2076        use crate::error::FailureKind;
2077
2078        for (case, expected) in [
2079            ("auth", FailureKind::Auth),
2080            ("not-trusted", FailureKind::NotTrustedDirectory),
2081            ("config", FailureKind::Config),
2082            ("session", FailureKind::SessionNotFound),
2083            ("mystery", FailureKind::Unclassified),
2084        ] {
2085            let codex = failing_codex(case);
2086            let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
2087            assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
2088        }
2089    }
2090
2091    /// A deterministic failure must not be retried even when its exit code is
2092    /// on the retry list. Re-running gets the same rejection, and the auth
2093    /// case has already been retried inside the CLI before it reaches here.
2094    #[cfg(unix)]
2095    #[tokio::test]
2096    async fn a_classified_failure_is_not_retried() {
2097        let policy = crate::retry::RetryPolicy::new()
2098            .max_attempts(3)
2099            .initial_backoff(Duration::from_millis(1))
2100            .retry_on_exit_codes([1]);
2101
2102        let started = Instant::now();
2103        let codex = failing_codex("auth");
2104        let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
2105            .await
2106            .unwrap_err();
2107
2108        assert!(matches!(err, Error::Auth { .. }), "{err}");
2109        // Three attempts with backoff would be visibly slower; this asserts
2110        // the shape rather than the timing, but the timing corroborates it.
2111        assert!(
2112            started.elapsed() < Duration::from_secs(2),
2113            "looks like it retried: {:?}",
2114            started.elapsed()
2115        );
2116    }
2117
2118    /// An unclassified failure keeps the old retry behaviour.
2119    #[cfg(unix)]
2120    #[tokio::test]
2121    async fn an_unclassified_failure_still_retries() {
2122        let policy = crate::retry::RetryPolicy::new()
2123            .max_attempts(2)
2124            .initial_backoff(Duration::from_millis(1))
2125            .retry_on_exit_codes([1]);
2126
2127        let codex = failing_codex("mystery");
2128        let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
2129            .await
2130            .unwrap_err();
2131
2132        assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
2133    }
2134
2135    /// The allow-list works on the exit code, so it still applies to a
2136    /// failure that classification moved off CommandFailed.
2137    #[cfg(unix)]
2138    #[tokio::test]
2139    async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
2140        let codex = failing_codex("auth");
2141        let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
2142            .await
2143            .expect("exit code 1 was allowed");
2144
2145        assert_eq!(output.exit_code, 1);
2146        assert!(!output.success);
2147        assert!(
2148            output.stderr.contains("401 Unauthorized"),
2149            "{}",
2150            output.stderr
2151        );
2152    }
2153
2154    // -----------------------------------------------------------------
2155    // Process groups and cancellation (#78)
2156    // -----------------------------------------------------------------
2157
2158    /// A fake codex that spawns a child of its own, the way the real CLI does
2159    /// for tool use, and the pids of both.
2160    #[cfg(unix)]
2161    fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
2162        let pid_file = crate::test_support::PidFile::new(label);
2163        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2164            .join("tests")
2165            .join("fake-codex-spawns-child.sh");
2166        let codex = Codex::builder()
2167            .binary("/bin/bash")
2168            .arg(script.to_str().unwrap())
2169            .env(
2170                "CODEX_WRAPPER_TEST_PIDFILE",
2171                pid_file.path().to_str().unwrap(),
2172            )
2173            .build()
2174            .expect("bash must exist");
2175        (codex, pid_file)
2176    }
2177
2178    #[cfg(unix)]
2179    async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
2180        for _ in 0..200 {
2181            if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
2182                let parse = |prefix: &str| -> Option<u32> {
2183                    contents
2184                        .lines()
2185                        .find_map(|l| l.strip_prefix(prefix))
2186                        .and_then(|v| v.trim().parse().ok())
2187                };
2188                if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
2189                    return (parent, child);
2190                }
2191            }
2192            tokio::time::sleep(Duration::from_millis(10)).await;
2193        }
2194        panic!("the fake codex never recorded both pids");
2195    }
2196
2197    /// The point of #78. `kill_on_drop` reaps the direct child only, so before
2198    /// process groups the grandchild outlived a cancelled run.
2199    #[cfg(unix)]
2200    #[tokio::test]
2201    async fn cancelling_kills_the_whole_process_group() {
2202        use crate::test_support::wait_until_gone;
2203
2204        let (codex, pid_file) = spawning_codex("group-drop");
2205
2206        let cancelled = tokio::time::timeout(
2207            Duration::from_millis(400),
2208            run_codex(&codex, vec!["exec".into()]),
2209        )
2210        .await;
2211        assert!(cancelled.is_err(), "the run should still have been going");
2212
2213        let (parent, child) = read_pids(&pid_file).await;
2214        assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
2215        assert!(
2216            wait_until_gone(child).await,
2217            "the subprocess ({child}) survived the cancelled run"
2218        );
2219    }
2220
2221    /// The graceful path: SIGTERM, a grace period, then SIGKILL. It cannot
2222    /// live in `Drop`, which is why there is an explicit entry point.
2223    #[cfg(unix)]
2224    #[tokio::test]
2225    async fn run_codex_cancellable_stops_the_group_gracefully() {
2226        use crate::test_support::is_running_for_test;
2227
2228        let (codex, pid_file) = spawning_codex("group-cancel");
2229        let codex = Codex::builder()
2230            .binary(codex.binary())
2231            .arg(
2232                std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2233                    .join("tests")
2234                    .join("fake-codex-spawns-child.sh")
2235                    .to_str()
2236                    .unwrap(),
2237            )
2238            .env(
2239                "CODEX_WRAPPER_TEST_PIDFILE",
2240                pid_file.path().to_str().unwrap(),
2241            )
2242            .termination_grace(Duration::from_millis(50))
2243            .build()
2244            .unwrap();
2245
2246        let cancel = async {
2247            tokio::time::sleep(Duration::from_millis(300)).await;
2248        };
2249        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
2250
2251        assert!(
2252            matches!(result, Err(Error::Cancelled { .. })),
2253            "expected a cancellation, got: {result:?}"
2254        );
2255
2256        let (parent, child) = read_pids(&pid_file).await;
2257        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2258        assert!(
2259            !is_running_for_test(child),
2260            "the subprocess ({child}) survived cancellation"
2261        );
2262    }
2263
2264    #[cfg(unix)]
2265    #[tokio::test]
2266    async fn dropping_during_cancellation_grace_kills_the_group() {
2267        let fixture = crate::test_support::GracePeriodFixture::new("buffered-cancel-grace-drop");
2268        let codex = fixture.builder().build().unwrap();
2269        fixture
2270            .assert_drop_during_grace(run_codex_cancellable(
2271                &codex,
2272                vec!["exec".into()],
2273                fixture.ready(),
2274            ))
2275            .await;
2276    }
2277
2278    #[cfg(unix)]
2279    #[tokio::test]
2280    async fn dropping_during_timeout_grace_kills_the_group() {
2281        let fixture = crate::test_support::GracePeriodFixture::new("buffered-timeout-grace-drop");
2282        let codex = fixture
2283            .builder()
2284            .timeout(Duration::from_secs(2))
2285            .build()
2286            .unwrap();
2287        fixture
2288            .assert_drop_during_grace(run_codex(&codex, vec!["exec".into()]))
2289            .await;
2290    }
2291
2292    #[cfg(unix)]
2293    #[tokio::test]
2294    async fn default_shutdown_still_sends_term_and_drains_both_pipes() {
2295        let fixture = crate::test_support::InterruptFixture::new("default-term-drain");
2296        let codex = fixture.builder().build().unwrap();
2297        let result =
2298            run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()).await;
2299        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2300        assert!(fixture.marker(".term").exists());
2301        assert!(!fixture.marker(".int").exists());
2302        assert!(
2303            fixture.marker(".cleaned").exists(),
2304            "shutdown output blocked cleanup"
2305        );
2306        fixture.assert_stopped().await;
2307    }
2308
2309    #[cfg(unix)]
2310    #[tokio::test]
2311    async fn interrupt_cancellation_drains_large_shutdown_output_and_cleans_detached_tool() {
2312        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drain");
2313        let codex = fixture
2314            .builder()
2315            .termination_signal(crate::TerminationSignal::Interrupt)
2316            // The shutdown output must not be captured against this limit.
2317            .output_limit(64)
2318            .build()
2319            .unwrap();
2320        let result = run_codex_with_stdin_prompt_cancellable(
2321            &codex,
2322            vec!["exec".into(), "-".into()],
2323            "prompt",
2324            fixture.detached_ready(),
2325        )
2326        .await;
2327        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2328        assert!(fixture.marker(".int").exists());
2329        assert!(!fixture.marker(".term").exists());
2330        assert!(
2331            fixture.marker(".cleaned").exists(),
2332            "shutdown output blocked cleanup"
2333        );
2334        fixture.assert_stopped().await;
2335    }
2336
2337    #[cfg(unix)]
2338    #[tokio::test]
2339    async fn interrupt_timeout_keeps_timeout_error_after_cooperative_exit() {
2340        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-timeout");
2341        let codex = fixture
2342            .builder()
2343            .termination_signal(crate::TerminationSignal::Interrupt)
2344            .timeout(Duration::from_secs(1))
2345            .build()
2346            .unwrap();
2347        let run = run_codex(&codex, vec!["exec".into()]);
2348        tokio::pin!(run);
2349        tokio::select! {
2350            result = &mut run => panic!("run ended before readiness: {result:?}"),
2351            () = fixture.detached_ready() => {}
2352        }
2353        let result = run.await;
2354        assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
2355        assert!(fixture.marker(".int").exists());
2356        assert!(fixture.marker(".cleaned").exists());
2357        fixture.assert_stopped().await;
2358    }
2359
2360    #[cfg(unix)]
2361    #[tokio::test]
2362    async fn interrupt_ignored_uses_bounded_hard_fallback() {
2363        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-ignored");
2364        let codex = fixture
2365            .builder()
2366            .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
2367            .termination_signal(crate::TerminationSignal::Interrupt)
2368            .termination_grace(Duration::from_millis(100))
2369            .build()
2370            .unwrap();
2371        let result = tokio::time::timeout(
2372            Duration::from_secs(3),
2373            run_codex_cancellable(&codex, vec!["exec".into()], fixture.ready()),
2374        )
2375        .await
2376        .expect("hard fallback exceeded the grace budget");
2377        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2378        assert!(fixture.marker(".int").exists());
2379        assert!(!fixture.marker(".cleaned").exists());
2380        fixture.assert_stopped().await;
2381    }
2382
2383    #[cfg(unix)]
2384    #[tokio::test]
2385    async fn dropping_during_interrupt_grace_kills_immediately() {
2386        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drop");
2387        let codex = fixture
2388            .builder()
2389            .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
2390            .termination_signal(crate::TerminationSignal::Interrupt)
2391            .termination_grace(Duration::from_secs(30))
2392            .build()
2393            .unwrap();
2394        let mut run = Box::pin(run_codex_cancellable(
2395            &codex,
2396            vec!["exec".into()],
2397            fixture.ready(),
2398        ));
2399        tokio::select! {
2400            result = &mut run => panic!("run ended before its grace period: {result:?}"),
2401            () = fixture.wait_for(".int") => {}
2402        }
2403        drop(run);
2404        fixture.assert_stopped().await;
2405    }
2406
2407    #[cfg(unix)]
2408    #[tokio::test]
2409    async fn process_group_optout_skips_interrupt_and_grace() {
2410        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-optout");
2411        let codex = fixture
2412            .builder()
2413            .process_group(false)
2414            .termination_signal(crate::TerminationSignal::Interrupt)
2415            .termination_grace(Duration::from_secs(30))
2416            .build()
2417            .unwrap();
2418        let result = tokio::time::timeout(
2419            Duration::from_secs(3),
2420            run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()),
2421        )
2422        .await
2423        .expect("optout must not wait through the grace period");
2424        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2425        assert!(!fixture.marker(".int").exists());
2426        assert!(!fixture.marker(".term").exists());
2427        let (parent, child) = fixture.pids().unwrap();
2428        assert!(crate::test_support::wait_until_gone(parent).await);
2429        assert!(crate::test_support::is_running_for_test(child));
2430        // Fixture Drop cleans the deliberately surviving detached child.
2431    }
2432
2433    /// Buffered timeout uses the same settled process-group cleanup as an
2434    /// explicit cancellation signal.
2435    #[cfg(unix)]
2436    #[tokio::test]
2437    async fn timeout_stops_the_group_before_returning() {
2438        use crate::test_support::is_running_for_test;
2439
2440        let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
2441        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2442            .join("tests")
2443            .join("fake-codex-spawns-child.sh");
2444        let codex = Codex::builder()
2445            .binary("/bin/bash")
2446            .arg(script.to_str().unwrap())
2447            .env(
2448                "CODEX_WRAPPER_TEST_PIDFILE",
2449                pid_file.path().to_str().unwrap(),
2450            )
2451            .timeout(Duration::from_millis(300))
2452            .termination_grace(Duration::from_millis(10))
2453            .build()
2454            .unwrap();
2455
2456        let result = run_codex(&codex, vec!["exec".into()]).await;
2457        assert!(
2458            matches!(result, Err(Error::Timeout { .. })),
2459            "expected a timeout, got: {result:?}"
2460        );
2461
2462        let (parent, child) = read_pids(&pid_file).await;
2463        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2464        assert!(
2465            !is_running_for_test(child),
2466            "the subprocess ({child}) survived the timeout"
2467        );
2468    }
2469
2470    /// A broken stdin pipe is terminal only after the owned process group has been
2471    /// stopped. Returning the write error first would release the caller while
2472    /// the provider could still mutate the workspace.
2473    #[cfg(unix)]
2474    #[tokio::test]
2475    async fn stdin_write_failure_stops_and_reaps_before_returning() {
2476        use crate::test_support::is_running_for_test;
2477
2478        let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
2479        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2480            .join("tests")
2481            .join("fake-codex-closes-stdin-spawns-child.sh");
2482        let codex = Codex::builder()
2483            .binary("/bin/bash")
2484            .arg(script.to_str().unwrap())
2485            .env(
2486                "CODEX_WRAPPER_TEST_PIDFILE",
2487                pid_file.path().to_str().unwrap(),
2488            )
2489            .termination_grace(Duration::from_millis(10))
2490            .build()
2491            .unwrap();
2492
2493        let prompt = "x".repeat(4 * 1024 * 1024);
2494        let result = run_codex_with_stdin_prompt(
2495            &codex,
2496            crate::ExecCommand::from_stdin(&prompt).args(),
2497            &prompt,
2498        )
2499        .await;
2500        assert!(
2501            matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
2502            "expected a stdin error, got: {result:?}"
2503        );
2504
2505        let (parent, child) = read_pids(&pid_file).await;
2506        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2507        assert!(
2508            !is_running_for_test(child),
2509            "the subprocess ({child}) survived the stdin failure"
2510        );
2511    }
2512
2513    // -----------------------------------------------------------------
2514    // Failed cleanup is not reported as a settled stop
2515    //
2516    // These inject the cleanup result after the real termination and wait
2517    // have run, so they cover how a failure is reported, not that one occurs.
2518    // The real-child tests above remain the evidence for normal reaping.
2519    // -----------------------------------------------------------------
2520
2521    /// The stop reason inside a [`Error::CleanupFailed`] whose cleanup half
2522    /// is the injected failure, not some other error.
2523    #[cfg(unix)]
2524    fn injected_cleanup_reason(result: Result<CommandOutput>) -> Error {
2525        match result {
2526            Err(Error::CleanupFailed { reason, cleanup }) => {
2527                assert!(
2528                    cleanup.to_string().contains("injected cleanup failure"),
2529                    "{cleanup:?}"
2530                );
2531                *reason
2532            }
2533            other => panic!("expected CleanupFailed, got {other:?}"),
2534        }
2535    }
2536
2537    #[cfg(unix)]
2538    #[tokio::test]
2539    async fn failed_cleanup_after_cancellation_is_not_a_bare_cancel() {
2540        let pid_file = crate::test_support::PidFile::new("cleanup-failed-cancel");
2541        let codex = crate::test_support::blocking_codex(&pid_file)
2542            .termination_grace(Duration::from_millis(10))
2543            .build()
2544            .unwrap();
2545        let cancel_soon = || tokio::time::sleep(Duration::from_millis(100));
2546
2547        let injection = CleanupFailureInjection::arm();
2548        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
2549        let reason = injected_cleanup_reason(result);
2550        assert!(matches!(reason, Error::Cancelled { .. }), "{reason:?}");
2551
2552        // The same run with cleanup succeeding keeps the bare typed reason.
2553        drop(injection);
2554        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
2555        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2556    }
2557
2558    /// The timeout stays readable as the reason, the span does not record a
2559    /// settled timeout, and a policy that retries timeouts does not start a
2560    /// second process while the first is not known to be gone.
2561    #[cfg(unix)]
2562    #[tokio::test]
2563    async fn failed_cleanup_after_timeout_is_recorded_and_not_retried() {
2564        use std::sync::Arc;
2565        use std::sync::atomic::{AtomicUsize, Ordering};
2566
2567        let recorder = recorder::Recorder::install();
2568        let spawns = Arc::new(AtomicUsize::new(0));
2569        let counted = Arc::clone(&spawns);
2570        let pid_file = crate::test_support::PidFile::new("cleanup-failed-timeout");
2571        let codex = crate::test_support::blocking_codex(&pid_file)
2572            .timeout(Duration::from_millis(200))
2573            .termination_grace(Duration::from_millis(10))
2574            .on_spawn(Arc::new(move |_| {
2575                counted.fetch_add(1, Ordering::SeqCst);
2576            }))
2577            .build()
2578            .unwrap();
2579        let policy = crate::retry::RetryPolicy::new()
2580            .max_attempts(3)
2581            .initial_backoff(Duration::from_millis(1))
2582            .retry_on_timeout(true);
2583
2584        let _injection = CleanupFailureInjection::arm();
2585        let result = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy)).await;
2586        let reason = injected_cleanup_reason(result);
2587        assert!(matches!(reason, Error::Timeout { .. }), "{reason:?}");
2588        assert_eq!(spawns.load(Ordering::SeqCst), 1, "a timeout was retried");
2589        assert_eq!(
2590            recorder.value("outcome").as_deref(),
2591            Some("cleanup_failed"),
2592            "recorded: {}",
2593            recorder.dump()
2594        );
2595    }
2596
2597    /// The run's own error branch, as opposed to a stop signal, goes through
2598    /// the same construction.
2599    #[cfg(unix)]
2600    #[tokio::test]
2601    async fn failed_cleanup_after_an_output_limit_keeps_the_limit_as_reason() {
2602        let codex = flooding_codex("stdout", Some(64 * 1024));
2603
2604        let injection = CleanupFailureInjection::arm();
2605        let result = run_codex(&codex, vec!["exec".into()]).await;
2606        let reason = injected_cleanup_reason(result);
2607        assert!(
2608            matches!(
2609                reason,
2610                Error::OutputLimitExceeded {
2611                    stream: OutputStream::Stdout,
2612                    limit_bytes: 65_536,
2613                }
2614            ),
2615            "{reason:?}"
2616        );
2617
2618        drop(injection);
2619        let result = run_codex(&codex, vec!["exec".into()]).await;
2620        assert!(
2621            matches!(result, Err(Error::OutputLimitExceeded { .. })),
2622            "{result:?}"
2623        );
2624    }
2625
2626    /// A run that finishes before the signal must not be reported as
2627    /// cancelled, and must not be killed on the way out.
2628    #[cfg(unix)]
2629    #[tokio::test]
2630    async fn a_run_that_finishes_first_is_not_cancelled() {
2631        let codex = Codex::builder()
2632            .binary("/bin/echo")
2633            .build()
2634            .expect("echo must exist");
2635
2636        let never = std::future::pending::<()>();
2637        let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
2638            .await
2639            .unwrap();
2640        assert!(output.success);
2641    }
2642
2643    #[cfg(unix)]
2644    #[tokio::test]
2645    async fn spawn_observer_reports_each_buffered_child_before_returning() {
2646        use std::sync::{Arc, Mutex};
2647
2648        let seen = Arc::new(Mutex::new(Vec::new()));
2649        let sink = Arc::clone(&seen);
2650        let codex = Codex::builder()
2651            .binary("/bin/echo")
2652            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2653            .build()
2654            .expect("echo must exist");
2655
2656        let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
2657        let seen = seen.lock().unwrap();
2658        assert_eq!(seen.len(), 1);
2659        assert!(seen[0].pid > 0);
2660        assert_eq!(seen[0].pgid, Some(seen[0].pid));
2661        assert!(output.stdout.contains("probe"));
2662    }
2663
2664    #[cfg(unix)]
2665    #[tokio::test]
2666    async fn spawn_receipt_never_claims_a_shared_group() {
2667        use std::sync::{Arc, Mutex};
2668
2669        let seen = Arc::new(Mutex::new(Vec::new()));
2670        let sink = Arc::clone(&seen);
2671        let codex = Codex::builder()
2672            .binary("/bin/echo")
2673            .process_group(false)
2674            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2675            .build()
2676            .expect("echo must exist");
2677
2678        run_codex(&codex, vec!["probe".into()]).await.unwrap();
2679        assert_eq!(seen.lock().unwrap()[0].pgid, None);
2680    }
2681
2682    #[test]
2683    fn parent_death_support_matches_the_target() {
2684        assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
2685    }
2686
2687    #[cfg(unix)]
2688    #[tokio::test]
2689    async fn parent_death_policy_composes_with_spawn_observation() {
2690        use std::sync::{Arc, Mutex};
2691
2692        let seen = Arc::new(Mutex::new(Vec::new()));
2693        let sink = Arc::clone(&seen);
2694        let codex = Codex::builder()
2695            .binary("/bin/echo")
2696            .die_with_parent(true)
2697            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2698            .build()
2699            .expect("echo must exist");
2700
2701        run_codex(&codex, vec!["probe".into()]).await.unwrap();
2702        assert_eq!(seen.lock().unwrap().len(), 1);
2703    }
2704
2705    const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
2706
2707    #[test]
2708    fn pdeathsig_helper_process() {
2709        if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
2710            return;
2711        }
2712        use std::io::Write;
2713        use std::sync::Arc;
2714
2715        let codex = Codex::builder()
2716            .binary("/bin/sleep")
2717            .die_with_parent(true)
2718            .on_spawn(Arc::new(|info| {
2719                println!("PID {}", info.pid);
2720                let _ = std::io::stdout().flush();
2721            }))
2722            .build()
2723            .unwrap();
2724        let runtime = tokio::runtime::Builder::new_current_thread()
2725            .enable_all()
2726            .build()
2727            .unwrap();
2728        let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
2729    }
2730
2731    #[cfg(target_os = "linux")]
2732    #[test]
2733    fn child_dies_when_its_parent_is_sigkilled() {
2734        use std::io::{BufRead, BufReader};
2735        use std::process::{Command, Stdio};
2736
2737        let executable = std::env::current_exe().expect("test binary path");
2738        let mut helper = Command::new(executable)
2739            .args([
2740                "--exact",
2741                "exec::tests::pdeathsig_helper_process",
2742                "--nocapture",
2743            ])
2744            .env(PDEATHSIG_HELPER_ENV, "1")
2745            .stdout(Stdio::piped())
2746            .spawn()
2747            .expect("spawn helper");
2748        let stdout = helper.stdout.take().expect("piped stdout");
2749        let pid = BufReader::new(stdout)
2750            .lines()
2751            .map_while(std::result::Result::ok)
2752            .find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
2753            .expect("helper reported child pid");
2754
2755        // SAFETY: this deliberately simulates an uncatchable supervisor crash.
2756        unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
2757        let _ = helper.wait();
2758
2759        for _ in 0..50 {
2760            if !crate::test_support::is_running_for_test(pid) {
2761                return;
2762            }
2763            std::thread::sleep(Duration::from_millis(100));
2764        }
2765        panic!("child {pid} survived its SIGKILLed parent");
2766    }
2767
2768    /// Opting out is not cosmetic: without a group of its own, cancelling
2769    /// reaches the direct child only and its subprocesses survive. That is the
2770    /// terminal-attached contract, where the terminal is the supervisor and
2771    /// Ctrl-C reaches the whole run directly instead.
2772    #[cfg(unix)]
2773    #[tokio::test]
2774    async fn opting_out_of_process_groups_leaves_the_subprocess() {
2775        use crate::test_support::wait_until_gone;
2776
2777        let pid_file = crate::test_support::PidFile::new("group-optout");
2778        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2779            .join("tests")
2780            .join("fake-codex-spawns-child.sh");
2781        let codex = Codex::builder()
2782            .binary("/bin/bash")
2783            .arg(script.to_str().unwrap())
2784            .env(
2785                "CODEX_WRAPPER_TEST_PIDFILE",
2786                pid_file.path().to_str().unwrap(),
2787            )
2788            .process_group(false)
2789            .build()
2790            .expect("bash must exist");
2791
2792        let cancelled = tokio::time::timeout(
2793            Duration::from_millis(400),
2794            run_codex(&codex, vec!["exec".into()]),
2795        )
2796        .await;
2797        assert!(cancelled.is_err(), "the run should still have been going");
2798
2799        let (parent, child) = read_pids(&pid_file).await;
2800        assert!(
2801            wait_until_gone(parent).await,
2802            "kill_on_drop still reaps the direct child ({parent})"
2803        );
2804        // The point of the contrast with
2805        // `cancelling_kills_the_whole_process_group`.
2806        assert!(
2807            crate::test_support::is_running_for_test(child),
2808            "with groups off, the subprocess ({child}) is expected to survive"
2809        );
2810        // Do not leave it behind.
2811        signal_group(child, libc::SIGKILL);
2812        unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
2813    }
2814    #[cfg(unix)]
2815    struct PrivateTraceDir(std::path::PathBuf);
2816
2817    #[cfg(unix)]
2818    impl Drop for PrivateTraceDir {
2819        fn drop(&mut self) {
2820            let _ = std::fs::remove_dir_all(&self.0);
2821        }
2822    }
2823
2824    #[cfg(unix)]
2825    fn private_trace_client(body: &str) -> (PrivateTraceDir, Codex) {
2826        use std::os::unix::fs::symlink;
2827        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2828        let name = format!(
2829            "TRACE_PRIVATE_path-{}-{}-{}",
2830            std::process::id(),
2831            std::time::SystemTime::now()
2832                .duration_since(std::time::UNIX_EPOCH)
2833                .unwrap()
2834                .as_nanos(),
2835            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2836        );
2837        let dir = PrivateTraceDir(std::env::temp_dir().join(name));
2838        std::fs::create_dir(&dir.0).unwrap();
2839        let binary = dir.0.join("TRACE_PRIVATE_binary");
2840        symlink("/bin/bash", &binary).unwrap();
2841        let script = dir.0.join("TRACE_PRIVATE_script");
2842        std::fs::write(&script, body).unwrap();
2843        let codex = Codex::builder()
2844            .binary(binary)
2845            .arg(script.to_string_lossy())
2846            .arg("TRACE_PRIVATE_config")
2847            .working_dir(&dir.0)
2848            .termination_grace(Duration::ZERO)
2849            .build()
2850            .unwrap();
2851        (dir, codex)
2852    }
2853
2854    #[cfg(unix)]
2855    #[tokio::test]
2856    async fn invocation_traces_exclude_private_content_at_every_level() {
2857        let recorder = recorder::Recorder::install();
2858        let body = concat!(
2859            "cat >/dev/null\n",
2860            "printf 'TRACE_PRIVATE_output'\n",
2861            "printf 'TRACE_PRIVATE_stderr' >&2\n"
2862        );
2863        let (_dir, codex) = private_trace_client(body);
2864        let args = vec![
2865            "exec".into(),
2866            "TRACE_PRIVATE_prompt".into(),
2867            "--resume".into(),
2868            "TRACE_PRIVATE_resume".into(),
2869        ];
2870        assert!(
2871            run_codex(&codex, args.clone())
2872                .await
2873                .unwrap()
2874                .stdout
2875                .contains("TRACE_PRIVATE")
2876        );
2877        run_codex_cancellable(&codex, args.clone(), std::future::pending())
2878            .await
2879            .unwrap();
2880        run_codex_with_stdin_prompt(&codex, args.clone(), "TRACE_PRIVATE_stdin")
2881            .await
2882            .unwrap();
2883        run_codex_with_stdin_prompt_cancellable(
2884            &codex,
2885            args,
2886            "TRACE_PRIVATE_stdin",
2887            std::future::pending(),
2888        )
2889        .await
2890        .unwrap();
2891        run_codex(&codex, vec!["TRACE_PRIVATE_unknown_command".into()])
2892            .await
2893            .unwrap();
2894        assert!(
2895            recorder.value("outcome").is_some(),
2896            "subscriber must observe outcomes"
2897        );
2898        assert!(
2899            !recorder.dump().contains("TRACE_PRIVATE"),
2900            "{}",
2901            recorder.dump()
2902        );
2903        assert!(
2904            recorder.value("arg_count").is_some(),
2905            "useful argument count remains available"
2906        );
2907    }
2908
2909    #[cfg(all(unix, feature = "json"))]
2910    #[tokio::test]
2911    async fn stream_and_resume_traces_exclude_private_content() {
2912        use crate::{CodexCommand, ExecCommand, ExecResumeCommand};
2913        let recorder = recorder::Recorder::install();
2914        // Existing verified wire shapes, with synthetic content and identifiers.
2915        let body = format!(
2916            "cat >/dev/null\n{}",
2917            include_str!("../tests/fake-codex.sh")
2918                .replace("thread_test", "TRACE_PRIVATE_thread")
2919                .replace("hello", "TRACE_PRIVATE_output")
2920        );
2921        let (_dir, codex) = private_trace_client(&body);
2922        let cmd = ExecCommand::new("TRACE_PRIVATE_prompt");
2923        let mut observed = 0;
2924        crate::streaming::stream_exec(&codex, &cmd, |_| observed += 1)
2925            .await
2926            .unwrap();
2927        crate::streaming::stream_exec_cancellable(&codex, &cmd, std::future::pending(), |_| {})
2928            .await
2929            .unwrap();
2930        let stdin_cmd = ExecCommand::new("TRACE_PRIVATE_stdin").prompt_via_stdin();
2931        crate::streaming::stream_exec(&codex, &stdin_cmd, |_| {})
2932            .await
2933            .unwrap();
2934        let resume = ExecResumeCommand::new()
2935            .session_id("TRACE_PRIVATE_resume")
2936            .prompt("TRACE_PRIVATE_prompt");
2937        crate::streaming::stream_exec_resume(&codex, &resume, |_| {})
2938            .await
2939            .unwrap();
2940        crate::streaming::stream_exec_resume_cancellable(
2941            &codex,
2942            &resume,
2943            std::future::pending(),
2944            |_| {},
2945        )
2946        .await
2947        .unwrap();
2948        assert!(observed > 0, "protocol delivery remains intact");
2949        assert!(
2950            cmd.to_command_string(&codex).contains("TRACE_PRIVATE"),
2951            "explicit preview stays caller-controlled"
2952        );
2953        assert!(
2954            !recorder.dump().contains("TRACE_PRIVATE"),
2955            "{}",
2956            recorder.dump()
2957        );
2958    }
2959
2960    #[cfg(unix)]
2961    #[tokio::test]
2962    async fn failure_and_retry_traces_exclude_rendered_errors_and_output() {
2963        let recorder = recorder::Recorder::install();
2964        let (_dir, mut codex) = private_trace_client(
2965            "printf 'TRACE_PRIVATE_output'; printf 'TRACE_PRIVATE_stderr' >&2; exit 7",
2966        );
2967        codex.retry_policy = Some(
2968            crate::RetryPolicy::new()
2969                .max_attempts(2)
2970                .initial_backoff(Duration::ZERO)
2971                .retry_on_exit_codes([7]),
2972        );
2973        let error = run_codex(&codex, vec!["exec".into(), "TRACE_PRIVATE_prompt".into()])
2974            .await
2975            .unwrap_err();
2976        assert!(
2977            error.to_string().contains("TRACE_PRIVATE"),
2978            "explicit error retains diagnostics"
2979        );
2980        codex.retry_policy = None;
2981        codex.output_limit = Some(8);
2982        assert!(matches!(
2983            run_codex(&codex, vec!["exec".into()]).await,
2984            Err(Error::OutputLimitExceeded { .. })
2985        ));
2986        assert!(
2987            !recorder.dump().contains("TRACE_PRIVATE"),
2988            "{}",
2989            recorder.dump()
2990        );
2991        assert!(
2992            recorder.value("attempt").is_some(),
2993            "retry event must be captured"
2994        );
2995    }
2996
2997    #[cfg(all(unix, feature = "app-server"))]
2998    #[tokio::test]
2999    async fn app_server_startup_trace_excludes_private_arguments() {
3000        let recorder = recorder::Recorder::install();
3001        let codex = Codex::builder()
3002            .binary("/bin/false")
3003            .arg("TRACE_PRIVATE_configuration")
3004            .build()
3005            .unwrap();
3006        assert!(
3007            crate::app_server::AppServer::builder(&codex)
3008                .start()
3009                .await
3010                .is_err()
3011        );
3012        assert!(
3013            !recorder.dump().contains("TRACE_PRIVATE"),
3014            "{}",
3015            recorder.dump()
3016        );
3017        assert!(
3018            recorder.value("arg_count").is_some(),
3019            "startup event must be captured"
3020        );
3021    }
3022    #[cfg(unix)]
3023    #[tokio::test]
3024    async fn output_limit_trace_omits_captured_prefix() {
3025        let recorder = recorder::Recorder::install();
3026        // Separate writes let the reader retain a prefix before the breach.
3027        let (_dir, mut codex) = private_trace_client(
3028            "printf 'TRACE_PRIVATE_output'; sleep 0.05; head -c 4096 /dev/zero",
3029        );
3030        codex.output_limit = Some(64);
3031        assert!(matches!(
3032            run_codex(&codex, vec!["exec".into()]).await,
3033            Err(Error::OutputLimitExceeded { .. })
3034        ));
3035        assert!(
3036            recorder.value("captured_bytes").is_some(),
3037            "capture warning was observed"
3038        );
3039        assert!(
3040            !recorder.dump().contains("TRACE_PRIVATE"),
3041            "{}",
3042            recorder.dump()
3043        );
3044    }
3045}