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::time::{Duration, Instant};
6
7use tokio::process::Command;
8use tracing::{Instrument, Span, debug, field, info_span};
9
10use crate::Codex;
11use crate::error::{Error, Result};
12
13/// Build the span covering one invocation.
14///
15/// The fields carry what identifies a run, never what it contains: no prompt
16/// and no environment. Both routinely hold content a host would not want in
17/// its logs, and a span is recorded whenever any subscriber is installed.
18pub(crate) fn command_span(name: &'static str, codex: &Codex, args: &[String]) -> Span {
19    let working_dir = codex
20        .working_dir
21        .as_ref()
22        .map_or_else(|| "(inherited)".to_string(), |p| p.display().to_string());
23
24    info_span!(
25        parent: Span::current(),
26        "codex",
27        otel.name = name,
28        subcommand = args.first().map_or("(none)", String::as_str),
29        binary = %codex.binary.display(),
30        working_dir = %working_dir,
31        outcome = field::Empty,
32        exit_code = field::Empty,
33        duration_ms = field::Empty,
34    )
35}
36
37/// Records how a run ended on its span, including when it does not end at all.
38///
39/// The dropped-future case is the one worth the machinery. Cancellation kills
40/// the process and runs nothing else, so without this the span would close
41/// with no outcome and an abandoned run would be indistinguishable from one
42/// still in progress. The span is passed in and held rather than read from
43/// [`Span::current`]: current-span tracking is the subscriber's job, and a
44/// subscriber that does not implement it would silently drop every record,
45/// including the drop-time one this exists for.
46pub(crate) struct SpanOutcome {
47    span: Span,
48    started: Instant,
49    settled: bool,
50}
51
52impl SpanOutcome {
53    pub(crate) fn start(span: Span) -> Self {
54        Self {
55            span,
56            started: Instant::now(),
57            settled: false,
58        }
59    }
60
61    pub(crate) fn settle(&mut self, outcome: &'static str, exit_code: Option<i32>) {
62        self.settled = true;
63        self.span.record("outcome", outcome);
64        self.span
65            .record("duration_ms", self.started.elapsed().as_millis() as u64);
66        if let Some(code) = exit_code {
67            self.span.record("exit_code", code);
68        }
69    }
70
71    fn settle_from_ref(&mut self, result: &Result<CommandOutput>) {
72        self.settle_from(result);
73    }
74
75    fn settle_from(&mut self, result: &Result<CommandOutput>) {
76        match result {
77            Ok(output) => self.settle("ok", Some(output.exit_code)),
78            Err(Error::Timeout { .. }) => self.settle("timeout", None),
79            // Covers the classified failures too, which are no longer
80            // CommandFailed but did still come from a process exit.
81            Err(e) => match e.exit_code() {
82                Some(code) => self.settle("failed", Some(code)),
83                None => self.settle("error", None),
84            },
85        }
86    }
87}
88
89impl Drop for SpanOutcome {
90    fn drop(&mut self) {
91        if !self.settled {
92            self.settle("cancelled", None);
93        }
94    }
95}
96
97/// Put the child in its own process group, so the whole run can be signalled
98/// as a unit.
99///
100/// `kill_on_drop` reaps the direct child only, and codex spawns its own
101/// subprocesses for tool use. Without a group of its own, cancelling leaves
102/// those running (#78).
103#[cfg(unix)]
104pub(crate) fn own_process_group(cmd: &mut Command, enabled: bool) {
105    if enabled {
106        cmd.process_group(0);
107    }
108}
109
110#[cfg(not(unix))]
111pub(crate) fn own_process_group(_cmd: &mut Command, _enabled: bool) {}
112
113/// Whether [`CodexBuilder::die_with_parent`](crate::CodexBuilder::die_with_parent)
114/// has a kernel-level effect on this platform.
115///
116/// This is true only on Linux, where `PR_SET_PDEATHSIG` is available. A
117/// supervisor that needs portable containment should use
118/// [`CodexBuilder::on_spawn`](crate::CodexBuilder::on_spawn) to maintain its
119/// own watchdog on other targets.
120#[must_use]
121pub const fn die_with_parent_supported() -> bool {
122    cfg!(target_os = "linux")
123}
124
125/// Ask the kernel to SIGKILL the child when its immediate parent dies.
126///
127/// The parent pid is captured before the fork. After arming the signal in the
128/// child, the hook checks it again and exits if the parent changed in the
129/// fork-to-prctl window. Every call here is async-signal-safe because this hook
130/// runs after `fork` and before `exec`.
131#[cfg(unix)]
132fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
133    let parent = std::process::id();
134    move || {
135        #[cfg(target_os = "linux")]
136        {
137            // SAFETY: prctl, getppid, and _exit are async-signal-safe calls.
138            unsafe {
139                if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
140                    return Err(std::io::Error::last_os_error());
141                }
142                if libc::getppid() as u32 != parent {
143                    libc::_exit(1);
144                }
145            }
146        }
147        #[cfg(not(target_os = "linux"))]
148        {
149            let _ = parent;
150        }
151        Ok(())
152    }
153}
154
155/// Apply the parent-death policy to a spawn command.
156pub(crate) fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
157    #[cfg(unix)]
158    if enabled {
159        // SAFETY: `pdeathsig_hook` uses only async-signal-safe operations.
160        unsafe {
161            cmd.pre_exec(pdeathsig_hook());
162        }
163    }
164    #[cfg(not(unix))]
165    {
166        let _ = (cmd, enabled);
167    }
168}
169
170/// Arm group cleanup and notify the observer from one process receipt.
171pub(crate) fn arm_and_notify(
172    process_group: bool,
173    pid: Option<u32>,
174    on_spawn: Option<&crate::SpawnObserver>,
175) -> GroupKillGuard {
176    if let (Some(pid), Some(observer)) = (pid, on_spawn) {
177        observer(crate::SpawnInfo {
178            pid,
179            pgid: process_group.then_some(pid),
180        });
181    }
182    GroupKillGuard::new(process_group.then_some(pid).flatten())
183}
184
185/// Signal a process group, given the group leader's pid.
186///
187/// Unix only: there is no non-unix counterpart, because every caller of this
188/// is itself gated on unix. A stub would only be dead code.
189///
190/// Negating the pid is what makes this reach the group rather than the leader
191/// alone. Errors are ignored: the only interesting failure is that the group
192/// is already gone, which is the desired state.
193#[cfg(unix)]
194pub(crate) fn signal_group(pid: u32, signal: i32) {
195    let Ok(pid) = i32::try_from(pid) else {
196        return;
197    };
198    // SAFETY: `kill` with a negative pid signals a process group. Passing a
199    // pid the OS has already reaped is defined and simply fails.
200    unsafe {
201        libc::kill(-pid, signal);
202    }
203}
204
205/// SIGKILLs the run's process group when dropped.
206///
207/// `kill_on_drop` handles the direct child; this is what reaches the
208/// subprocesses codex started. Drop cannot await, so this is the abrupt path.
209/// For a graceful one, see
210/// [`ExecCommand::execute_cancellable`](crate::ExecCommand::execute_cancellable).
211pub(crate) struct GroupKillGuard {
212    pid: Option<u32>,
213}
214
215impl GroupKillGuard {
216    pub(crate) fn new(pid: Option<u32>) -> Self {
217        Self { pid }
218    }
219
220    /// Stop killing on drop, once the run has finished on its own.
221    pub(crate) fn disarm(&mut self) {
222        self.pid = None;
223    }
224
225    /// Ask the group to stop, then insist after `grace`.
226    ///
227    /// Async, so it can wait, which is why it cannot live in `Drop`.
228    #[cfg(unix)]
229    pub(crate) async fn terminate(&mut self, grace: Duration) {
230        let Some(pid) = self.pid.take() else {
231            return;
232        };
233        signal_group(pid, libc::SIGTERM);
234        tokio::time::sleep(grace).await;
235        signal_group(pid, libc::SIGKILL);
236    }
237
238    /// No process groups here, so there is nothing to ask politely. The
239    /// child still dies with the dropped future via `kill_on_drop`.
240    #[cfg(not(unix))]
241    pub(crate) async fn terminate(&mut self, _grace: Duration) {
242        let _ = self.pid.take();
243    }
244}
245
246impl Drop for GroupKillGuard {
247    fn drop(&mut self) {
248        // Taken unconditionally so the field is read on every platform, not
249        // just the one that can act on it.
250        if let Some(pid) = self.pid.take() {
251            #[cfg(unix)]
252            signal_group(pid, libc::SIGKILL);
253            #[cfg(not(unix))]
254            let _ = pid;
255        }
256    }
257}
258
259/// Raw output from a Codex CLI invocation.
260///
261/// Contains captured stdout/stderr, the process exit code, and a convenience
262/// `success` flag.
263#[derive(Clone)]
264pub struct CommandOutput {
265    /// Standard output as a UTF-8 string.
266    pub stdout: String,
267    /// Standard error as a UTF-8 string.
268    pub stderr: String,
269    /// Process exit code (`-1` if the process was killed by a signal).
270    pub exit_code: i32,
271    /// `true` when the process exited with code 0.
272    pub success: bool,
273}
274
275const DEBUG_TRUNCATE_LEN: usize = 200;
276
277fn truncate_for_debug(s: &str) -> String {
278    if s.len() > DEBUG_TRUNCATE_LEN {
279        format!("{}... ({} bytes total)", &s[..DEBUG_TRUNCATE_LEN], s.len())
280    } else {
281        s.to_string()
282    }
283}
284
285impl fmt::Debug for CommandOutput {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        f.debug_struct("CommandOutput")
288            .field("stdout", &truncate_for_debug(&self.stdout))
289            .field("stderr", &truncate_for_debug(&self.stderr))
290            .field("exit_code", &self.exit_code)
291            .field("success", &self.success)
292            .finish()
293    }
294}
295
296/// Run a codex command with the given arguments.
297///
298/// If the [`Codex`] client has a retry policy set, transient errors will be
299/// retried according to that policy. A per-command retry policy can be passed
300/// to override the client default.
301pub async fn run_codex(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
302    run_codex_with_retry(codex, args, None).await
303}
304
305/// Run a codex command with an optional per-command retry policy override.
306pub async fn run_codex_with_retry(
307    codex: &Codex,
308    args: Vec<String>,
309    retry_override: Option<&crate::retry::RetryPolicy>,
310) -> Result<CommandOutput> {
311    let policy = retry_override.or(codex.retry_policy.as_ref());
312
313    match policy {
314        Some(policy) => {
315            // A parent span so the retry events and each attempt's own span
316            // nest under one run rather than arriving as unrelated lines.
317            let span = info_span!(
318                "codex.retry",
319                subcommand = args.first().map_or("(none)", String::as_str),
320                max_attempts = policy.max_attempts,
321            );
322            crate::retry::with_retry(policy, || run_codex_once(codex, args.clone()))
323                .instrument(span)
324                .await
325        }
326        None => run_codex_once(codex, args).await,
327    }
328}
329
330/// Assemble the full argument list for an invocation: the client's global
331/// args first, since they precede the subcommand, then the command's own.
332///
333/// Both spawn paths and [`CodexCommand::to_command_string`] go through here,
334/// so a previewed command cannot drift from the one that actually runs.
335///
336/// [`CodexCommand::to_command_string`]: crate::command::CodexCommand::to_command_string
337pub(crate) fn assemble_args(codex: &Codex, args: Vec<String>) -> Vec<String> {
338    let mut command_args = Vec::with_capacity(codex.global_args.len() + args.len());
339    let protects_rollout_budget = args
340        .windows(2)
341        .any(|pair| pair[0] == "-c" && crate::RolloutBudgetConfig::is_config_override(&pair[1]));
342    let mut global_args = codex.global_args.iter().peekable();
343    while let Some(arg) = global_args.next() {
344        if protects_rollout_budget
345            && matches!(arg.as_str(), "--enable" | "--disable")
346            && global_args
347                .peek()
348                .is_some_and(|feature| feature.as_str() == "rollout_budget")
349        {
350            global_args.next();
351            continue;
352        }
353        if protects_rollout_budget
354            && matches!(
355                arg.as_str(),
356                "--enable=rollout_budget" | "--disable=rollout_budget"
357            )
358        {
359            continue;
360        }
361        command_args.push(arg.clone());
362    }
363    command_args.extend(args);
364    command_args
365}
366
367/// Render an invocation as a copy-pasteable shell command.
368pub(crate) fn command_string(codex: &Codex, args: Vec<String>) -> String {
369    let mut out = shell_quote(&codex.binary.display().to_string());
370    for arg in assemble_args(codex, args) {
371        out.push(' ');
372        out.push_str(&shell_quote(&arg));
373    }
374    out
375}
376
377/// Quote a single argument for a POSIX shell, if it needs it.
378///
379/// The empty string is quoted: unquoted it would vanish from the rendered
380/// command, turning a preview into something that runs differently from what
381/// it describes.
382pub(crate) fn shell_quote(arg: &str) -> String {
383    if arg.is_empty() {
384        return "''".to_string();
385    }
386    if arg.contains(|c: char| c.is_whitespace() || "\"'$\\`|;<>&()[]{}*?!~#".contains(c)) {
387        return format!("'{}'", arg.replace('\'', r"'\''"));
388    }
389    arg.to_string()
390}
391
392async fn run_codex_once(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
393    let span = command_span("codex.exec", codex, &args);
394    let outcome_span = span.clone();
395    let command_args = assemble_args(codex, args);
396
397    async move {
398        debug!(binary = %codex.binary.display(), args = ?command_args, "executing codex command");
399
400        let mut outcome = SpanOutcome::start(outcome_span);
401        let result = match codex.timeout {
402            Some(timeout) => {
403                run_internal_inner(
404                    SpawnSpec {
405                        binary: &codex.binary,
406                        args: &command_args,
407                        env: &codex.env,
408                        clear_env: codex.clear_env,
409                        working_dir: codex.working_dir.as_deref(),
410                        stdin_prompt: None,
411                        process_group: codex.process_group,
412                        die_with_parent: codex.die_with_parent,
413                        on_spawn: codex.on_spawn.as_ref(),
414                    },
415                    Some(timeout_stop(timeout)),
416                    codex.termination_grace,
417                )
418                .await
419            }
420            None => {
421                run_internal_inner(
422                    SpawnSpec {
423                        binary: &codex.binary,
424                        args: &command_args,
425                        env: &codex.env,
426                        clear_env: codex.clear_env,
427                        working_dir: codex.working_dir.as_deref(),
428                        stdin_prompt: None,
429                        process_group: codex.process_group,
430                        die_with_parent: codex.die_with_parent,
431                        on_spawn: codex.on_spawn.as_ref(),
432                    },
433                    None,
434                    Duration::ZERO,
435                )
436                .await
437            }
438        };
439        outcome.settle_from(&result);
440        result
441    }
442    .instrument(span)
443    .await
444}
445
446/// Run a codex command, stopping it gracefully if `cancel` resolves first.
447///
448/// On cancellation the run's process group is sent SIGTERM, given the client's
449/// [`termination_grace`](crate::CodexBuilder::termination_grace), then killed.
450/// Signalling the group rather than the pid is what reaches the subprocesses
451/// codex started for tool use; killing only the direct child leaves those
452/// running (#78).
453///
454/// Dropping the future instead is still safe, and still kills the group, but
455/// abruptly: `Drop` cannot wait out a grace period.
456///
457/// Retry does not apply. A cancelled run is a decision, not a transient
458/// failure.
459///
460/// On platforms without process groups this degrades to killing the child.
461pub async fn run_codex_cancellable<C>(
462    codex: &Codex,
463    args: Vec<String>,
464    cancel: C,
465) -> Result<CommandOutput>
466where
467    C: std::future::Future<Output = ()> + Send,
468{
469    let span = command_span("codex.exec", codex, &args);
470    let outcome_span = span.clone();
471    let command_args = assemble_args(codex, args);
472
473    async move {
474        debug!(binary = %codex.binary.display(), args = ?command_args, "executing cancellable codex command");
475
476        let mut outcome = SpanOutcome::start(outcome_span);
477        let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
478        let result = run_internal_inner(
479            SpawnSpec {
480                binary: &codex.binary,
481                args: &command_args,
482                env: &codex.env,
483                clear_env: codex.clear_env,
484                working_dir: codex.working_dir.as_deref(),
485                stdin_prompt: None,
486                process_group: codex.process_group,
487                die_with_parent: codex.die_with_parent,
488                on_spawn: codex.on_spawn.as_ref(),
489            },
490            Some(stop),
491            codex.termination_grace,
492        )
493        .await;
494
495        match &result {
496            Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
497            other => outcome.settle_from_ref(other),
498        }
499        result
500    }
501    .instrument(span)
502    .await
503}
504
505/// Run a codex command and allow specific non-zero exit codes.
506pub async fn run_codex_allow_exit_codes(
507    codex: &Codex,
508    args: Vec<String>,
509    allowed_codes: &[i32],
510) -> Result<CommandOutput> {
511    let output = run_codex(codex, args).await;
512
513    match output {
514        // Matched on the exit code rather than the variant: classification
515        // moves some failures off CommandFailed, and an allowed code is
516        // allowed whatever the wrapper made of the message.
517        Err(e)
518            if e.exit_code()
519                .is_some_and(|code| allowed_codes.contains(&code)) =>
520        {
521            let exit_code = e.exit_code().unwrap_or(-1);
522            let (stdout, stderr) = match &e {
523                Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
524                Error::Auth { message, .. }
525                | Error::Config { message, .. }
526                | Error::NotTrustedDirectory { message, .. }
527                | Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
528                _ => (String::new(), String::new()),
529            };
530            Ok(CommandOutput {
531                stdout,
532                stderr,
533                exit_code,
534                success: false,
535            })
536        }
537        other => other,
538    }
539}
540
541/// Run a codex command, writing `prompt` to the child's stdin.
542///
543/// For `codex exec -`, where the prompt is delivered on stdin rather than as
544/// an argument. The prompt is written and the handle dropped, so the CLI sees
545/// EOF and stops waiting for more.
546///
547/// Retry does not apply. The policy is deliberately ignored rather than
548/// honored: a retry would have to write the prompt again, and the first
549/// attempt has already moved the caller's data into a pipe that cannot be
550/// rewound. Silently retrying with an empty stdin would be worse than not
551/// retrying at all.
552pub async fn run_codex_with_stdin_prompt(
553    codex: &Codex,
554    args: Vec<String>,
555    prompt: &str,
556) -> Result<CommandOutput> {
557    let span = command_span("codex.exec", codex, &args);
558    let outcome_span = span.clone();
559    let command_args = assemble_args(codex, args);
560
561    async move {
562        debug!(
563            binary = %codex.binary.display(),
564            args = ?command_args,
565            prompt_bytes = prompt.len(),
566            "executing codex command with a stdin prompt"
567        );
568
569        let mut outcome = SpanOutcome::start(outcome_span);
570        let stop = codex.timeout.map(timeout_stop);
571        let result = run_internal_inner(
572            SpawnSpec {
573                binary: &codex.binary,
574                args: &command_args,
575                env: &codex.env,
576                clear_env: codex.clear_env,
577                working_dir: codex.working_dir.as_deref(),
578                stdin_prompt: Some(prompt),
579                process_group: codex.process_group,
580                die_with_parent: codex.die_with_parent,
581                on_spawn: codex.on_spawn.as_ref(),
582            },
583            stop,
584            codex.termination_grace,
585        )
586        .await;
587        outcome.settle_from(&result);
588        result
589    }
590    .instrument(span)
591    .await
592}
593
594/// Run a codex command with a stdin prompt and an explicit cancellation signal.
595///
596/// Cancellation and the client's timeout both terminate the owned process
597/// group and await the direct child before returning. Retry does not apply.
598pub async fn run_codex_with_stdin_prompt_cancellable<C>(
599    codex: &Codex,
600    args: Vec<String>,
601    prompt: &str,
602    cancel: C,
603) -> Result<CommandOutput>
604where
605    C: std::future::Future<Output = ()> + Send,
606{
607    let span = command_span("codex.exec", codex, &args);
608    let outcome_span = span.clone();
609    let command_args = assemble_args(codex, args);
610
611    async move {
612        debug!(
613            binary = %codex.binary.display(),
614            args = ?command_args,
615            prompt_bytes = prompt.len(),
616            "executing cancellable codex command with a stdin prompt"
617        );
618
619        let mut outcome = SpanOutcome::start(outcome_span);
620        let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
621        let result = run_internal_inner(
622            SpawnSpec {
623                binary: &codex.binary,
624                args: &command_args,
625                env: &codex.env,
626                clear_env: codex.clear_env,
627                working_dir: codex.working_dir.as_deref(),
628                stdin_prompt: Some(prompt),
629                process_group: codex.process_group,
630                die_with_parent: codex.die_with_parent,
631                on_spawn: codex.on_spawn.as_ref(),
632            },
633            Some(stop),
634            codex.termination_grace,
635        )
636        .await;
637
638        match &result {
639            Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
640            other => outcome.settle_from_ref(other),
641        }
642        result
643    }
644    .instrument(span)
645    .await
646}
647
648#[derive(Clone, Copy, Debug)]
649enum StopReason {
650    Cancelled { grace_seconds: u64 },
651    Timeout { timeout_seconds: u64 },
652}
653
654impl StopReason {
655    fn into_error(self) -> Error {
656        match self {
657            Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
658            Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
659        }
660    }
661}
662
663type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
664
665fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
666    Box::pin(async move {
667        tokio::time::sleep(timeout).await;
668        StopReason::Timeout {
669            timeout_seconds: timeout.as_secs(),
670        }
671    })
672}
673
674fn cancellation_or_timeout<'a, C>(
675    cancel: C,
676    timeout: Option<Duration>,
677    grace: Duration,
678) -> StopFuture<'a>
679where
680    C: std::future::Future<Output = ()> + Send + 'a,
681{
682    Box::pin(async move {
683        match timeout {
684            Some(timeout) => tokio::select! {
685                () = cancel => StopReason::Cancelled {
686                    grace_seconds: grace.as_secs(),
687                },
688                () = tokio::time::sleep(timeout) => StopReason::Timeout {
689                    timeout_seconds: timeout.as_secs(),
690                },
691            },
692            None => {
693                cancel.await;
694                StopReason::Cancelled {
695                    grace_seconds: grace.as_secs(),
696                }
697            }
698        }
699    })
700}
701
702/// Everything one spawn needs, gathered so the signature stays readable.
703struct SpawnSpec<'a> {
704    binary: &'a std::path::Path,
705    args: &'a [String],
706    env: &'a std::collections::HashMap<String, String>,
707    /// Whether the child starts without the wrapper's ambient environment.
708    clear_env: bool,
709    working_dir: Option<&'a std::path::Path>,
710    /// A prompt to deliver on stdin, for `codex exec -`.
711    stdin_prompt: Option<&'a str>,
712    /// Whether the run leads its own process group.
713    process_group: bool,
714    /// Whether the child should die with its immediate parent on Linux.
715    die_with_parent: bool,
716    /// Who to notify immediately after a successful spawn.
717    on_spawn: Option<&'a crate::SpawnObserver>,
718}
719
720async fn run_internal_inner(
721    spec: SpawnSpec<'_>,
722    stop: Option<StopFuture<'_>>,
723    grace: Duration,
724) -> Result<CommandOutput> {
725    let SpawnSpec {
726        binary,
727        args,
728        env,
729        clear_env,
730        working_dir,
731        stdin_prompt,
732        process_group,
733        die_with_parent,
734        on_spawn,
735    } = spec;
736    let mut cmd = Command::new(binary);
737    cmd.args(args);
738
739    // Pipe stdin only when there is a prompt to write. Otherwise close it, so
740    // the child neither inherits nor blocks on the parent's.
741    if stdin_prompt.is_some() {
742        cmd.stdin(std::process::Stdio::piped());
743    } else {
744        cmd.stdin(std::process::Stdio::null());
745    }
746
747    // Kill the child if this future is dropped: on timeout, on caller
748    // cancellation, or on task abort. Without this, tokio detaches the child
749    // and codex keeps running with no handle left to stop it.
750    cmd.kill_on_drop(true);
751    own_process_group(&mut cmd, process_group);
752    apply_die_with_parent(&mut cmd, die_with_parent);
753
754    if let Some(dir) = working_dir {
755        cmd.current_dir(dir);
756    }
757
758    apply_child_environment(&mut cmd, clear_env, env);
759
760    // Always spawn rather than using `Command::output`: the pid is needed to
761    // signal the process group, and `output` does not surrender it. It also
762    // forces stdin to null, which the stdin-prompt path cannot use.
763    cmd.stdout(std::process::Stdio::piped());
764    cmd.stderr(std::process::Stdio::piped());
765
766    let mut child = cmd.spawn().map_err(|e| Error::Io {
767        message: format!("failed to spawn codex: {e}"),
768        source: e,
769        working_dir: working_dir.map(|p| p.to_path_buf()),
770    })?;
771
772    // Armed for the whole run. If this future is dropped, its Drop signals the
773    // group, which is what reaches the subprocesses codex started.
774    // Only meaningful when the run leads its own group. Sharing the parent's
775    // means signalling it would hit the parent too.
776    let mut group = arm_and_notify(process_group, child.id(), on_spawn);
777    let child_stdin = child.stdin.take();
778    let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
779    let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
780
781    let write = async move {
782        let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
783            return Ok(());
784        };
785        use tokio::io::AsyncWriteExt;
786        stdin
787            .write_all(prompt.as_bytes())
788            .await
789            .map_err(|e| Error::Io {
790                message: format!("failed to write the prompt to codex stdin: {e}"),
791                source: e,
792                working_dir: working_dir.map(|p| p.to_path_buf()),
793            })?;
794        // Closing the write half is what tells the CLI the prompt is
795        // complete. Without it the child waits for more input.
796        stdin.shutdown().await.map_err(|e| Error::Io {
797            message: format!("failed to close codex stdin: {e}"),
798            source: e,
799            working_dir: working_dir.map(|p| p.to_path_buf()),
800        })
801    };
802
803    // Concurrently, not sequentially: a prompt larger than the pipe buffer
804    // blocks until the child reads it, and a child that writes to stdout
805    // meanwhile blocks until we read that. Waiting for the write to finish
806    // before draining stdout would deadlock both.
807    let read_stdout = async move {
808        use tokio::io::AsyncReadExt;
809        let mut bytes = Vec::new();
810        child_stdout
811            .read_to_end(&mut bytes)
812            .await
813            .map(|_| bytes)
814            .map_err(|e| Error::Io {
815                message: format!("failed to read codex stdout: {e}"),
816                source: e,
817                working_dir: working_dir.map(|p| p.to_path_buf()),
818            })
819    };
820    let read_stderr = async move {
821        use tokio::io::AsyncReadExt;
822        let mut bytes = Vec::new();
823        child_stderr
824            .read_to_end(&mut bytes)
825            .await
826            .map(|_| bytes)
827            .map_err(|e| Error::Io {
828                message: format!("failed to read codex stderr: {e}"),
829                source: e,
830                working_dir: working_dir.map(|p| p.to_path_buf()),
831            })
832    };
833    let wait = async { child.wait().await.map_err(|e| wait_error(e, working_dir)) };
834    let run = async {
835        let ((), stdout, stderr, status) = tokio::try_join!(write, read_stdout, read_stderr, wait)?;
836        Ok::<_, Error>((stdout, stderr, status))
837    };
838
839    let finished = match stop {
840        None => Ok(run.await),
841        // Racing the run against the caller's signal. Cancellation here is
842        // graceful, which is the whole reason it cannot live in `Drop`:
843        // asking a process to stop and then waiting requires awaiting.
844        Some(stop) => tokio::select! {
845            outcome = run => Ok(outcome),
846            reason = stop => Err(reason),
847        },
848    };
849
850    let (stdout, stderr, status) = match finished {
851        Ok(Ok(finished)) => finished,
852        Ok(Err(error)) => {
853            // A stdin or pipe failure can happen while the child continues
854            // running. Treat it as a stop request and settle ownership before
855            // exposing the I/O error.
856            terminate_and_reap(&mut child, &mut group, grace, working_dir).await?;
857            return Err(error);
858        }
859        Err(reason) => {
860            // The run future is gone before this branch executes, returning
861            // ownership of `child` so cleanup can explicitly reap it.
862            // `GroupKillGuard::terminate` reaches descendants on Unix. The
863            // direct-child kill below is the portable fallback and makes the
864            // wait authoritative on every platform.
865            terminate_and_reap(&mut child, &mut group, grace, working_dir).await?;
866            return Err(reason.into_error());
867        }
868    };
869
870    // Finished on its own, so there is no group left to kill.
871    group.disarm();
872
873    let stdout = String::from_utf8_lossy(&stdout).to_string();
874    let stderr = String::from_utf8_lossy(&stderr).to_string();
875    let exit_code = status.code().unwrap_or(-1);
876
877    if !status.success() {
878        return Err(Error::from_command_failure(
879            format!("{} {}", binary.display(), args.join(" ")),
880            exit_code,
881            stdout,
882            stderr,
883            working_dir.map(|p| p.to_path_buf()),
884        ));
885    }
886
887    Ok(CommandOutput {
888        stdout,
889        stderr,
890        exit_code,
891        success: true,
892    })
893}
894
895async fn terminate_and_reap(
896    child: &mut tokio::process::Child,
897    group: &mut GroupKillGuard,
898    grace: Duration,
899    working_dir: Option<&std::path::Path>,
900) -> Result<()> {
901    group.terminate(grace).await;
902    if child
903        .try_wait()
904        .map_err(|e| wait_error(e, working_dir))?
905        .is_none()
906        && let Err(error) = child.start_kill()
907        && error.kind() != std::io::ErrorKind::InvalidInput
908    {
909        return Err(wait_error(error, working_dir));
910    }
911    child.wait().await.map_err(|e| wait_error(e, working_dir))?;
912    Ok(())
913}
914
915fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
916    Error::Io {
917        message: format!("failed to wait on codex: {error}"),
918        source: error,
919        working_dir: working_dir.map(|p| p.to_path_buf()),
920    }
921}
922
923/// Apply the client environment policy to a direct child process.
924///
925/// Kept in one helper because buffered and streaming execution construct
926/// separate commands. Clearing must happen before explicit values are added.
927pub(crate) fn apply_child_environment(
928    cmd: &mut Command,
929    clear_env: bool,
930    env: &std::collections::HashMap<String, String>,
931) {
932    if clear_env {
933        cmd.env_clear();
934    }
935    cmd.envs(env);
936}
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941    use crate::CodexCommand;
942
943    #[test]
944    fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
945        let codex = Codex::builder()
946            .binary("/bin/echo")
947            .config("features.rollout_budget=false")
948            .enable("rollout_budget")
949            .disable("rollout_budget")
950            .arg("--enable=rollout_budget")
951            .arg("--disable=rollout_budget")
952            .arg("--disable")
953            .arg("rollout_budget")
954            .enable("keep-enabled")
955            .disable("keep-disabled")
956            .build()
957            .expect("echo must exist");
958        let budget = crate::RolloutBudgetConfig::builder(10_000)
959            .build()
960            .expect("valid budget");
961        let expected = budget.config_override();
962        let opening = crate::ExecCommand::new("hi")
963            .rollout_budget(budget.clone())
964            .args();
965        let resumed = crate::ExecResumeCommand::new()
966            .session_id("thread")
967            .rollout_budget(budget)
968            .args();
969
970        for args in [opening, resumed] {
971            let assembled = assemble_args(&codex, args);
972            assert!(assembled.iter().any(|arg| arg == &expected));
973            assert!(
974                !assembled.windows(2).any(|pair| {
975                    matches!(pair[0].as_str(), "--enable" | "--disable")
976                        && pair[1] == "rollout_budget"
977                }),
978                "typed budget must suppress paired client toggles: {assembled:?}"
979            );
980            assert!(
981                !assembled.iter().any(|arg| {
982                    matches!(
983                        arg.as_str(),
984                        "--enable=rollout_budget" | "--disable=rollout_budget"
985                    )
986                }),
987                "typed budget must suppress equals-form client toggles: {assembled:?}"
988            );
989            assert!(
990                assembled
991                    .windows(2)
992                    .any(|pair| pair == ["--enable", "keep-enabled"])
993            );
994            assert!(
995                assembled
996                    .windows(2)
997                    .any(|pair| pair == ["--disable", "keep-disabled"])
998            );
999        }
1000    }
1001
1002    fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
1003        CommandOutput {
1004            stdout: stdout.to_string(),
1005            stderr: stderr.to_string(),
1006            exit_code: 0,
1007            success: true,
1008        }
1009    }
1010
1011    #[test]
1012    fn shell_quote_leaves_plain_words_alone() {
1013        assert_eq!(shell_quote("exec"), "exec");
1014        assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
1015        assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
1016    }
1017
1018    #[test]
1019    fn shell_quote_wraps_anything_a_shell_would_read() {
1020        assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
1021        assert_eq!(shell_quote("$HOME"), "'$HOME'");
1022        assert_eq!(shell_quote("a;b"), "'a;b'");
1023        assert_eq!(shell_quote("*.rs"), "'*.rs'");
1024        assert_eq!(shell_quote("it's"), r"'it'\''s'");
1025    }
1026
1027    /// An unquoted empty string would disappear from the rendered command,
1028    /// making the preview describe a different invocation than it previews.
1029    #[test]
1030    fn shell_quote_keeps_the_empty_argument_visible() {
1031        assert_eq!(shell_quote(""), "''");
1032    }
1033
1034    #[test]
1035    fn debug_short_output_not_truncated() {
1036        let output = make_output("hello", "world");
1037        let debug = format!("{output:?}");
1038        assert!(debug.contains("hello"));
1039        assert!(debug.contains("world"));
1040        assert!(!debug.contains("bytes total"));
1041    }
1042
1043    #[test]
1044    fn debug_long_output_truncated() {
1045        let long = "x".repeat(300);
1046        let output = make_output(&long, &long);
1047        let debug = format!("{output:?}");
1048        assert!(debug.contains("... (300 bytes total)"));
1049        assert!(!debug.contains(&long));
1050    }
1051
1052    /// Compatibility is explicit: callers that do not opt in keep the
1053    /// ambient environment they relied on before `clear_env` existed.
1054    #[cfg(unix)]
1055    #[tokio::test]
1056    async fn child_environment_is_inherited_by_default() {
1057        let capture = crate::test_support::EnvCapture::new("env-default");
1058        let codex = crate::test_support::env_capturing_codex(&capture)
1059            .build()
1060            .expect("bash must exist");
1061
1062        crate::ExecCommand::new("probe")
1063            .execute(&codex)
1064            .await
1065            .unwrap();
1066
1067        let environment = capture.read();
1068        assert_eq!(
1069            environment.get("PATH"),
1070            Some(&std::env::var("PATH").expect("test process must have PATH"))
1071        );
1072    }
1073
1074    /// The timeout and ordinary buffered paths use different wrapper entry
1075    /// points. Opening and resume both have to reach the same environment
1076    /// policy, and explicit values on either side of `clear_env` must survive.
1077    #[cfg(unix)]
1078    #[tokio::test]
1079    async fn cleared_environment_reaches_buffered_open_and_resume() {
1080        let capture = crate::test_support::EnvCapture::new("env-buffered");
1081        let opening_client = crate::test_support::env_capturing_codex(&capture)
1082            .clear_env()
1083            .env("CODEX_WRAPPER_EXPLICIT", "opening")
1084            .timeout(Duration::from_secs(2))
1085            .build()
1086            .expect("bash must exist");
1087
1088        crate::ExecCommand::new("probe")
1089            .execute(&opening_client)
1090            .await
1091            .unwrap();
1092        let opening_environment = capture.read();
1093        assert!(!opening_environment.contains_key("PATH"));
1094        assert_eq!(
1095            opening_environment
1096                .get("CODEX_WRAPPER_EXPLICIT")
1097                .map(String::as_str),
1098            Some("opening")
1099        );
1100        assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
1101
1102        let resume_client = crate::test_support::env_capturing_codex(&capture)
1103            .clear_env()
1104            .env("CODEX_WRAPPER_EXPLICIT", "resume")
1105            .build()
1106            .expect("bash must exist");
1107        crate::ExecResumeCommand::new()
1108            .last()
1109            .execute(&resume_client)
1110            .await
1111            .unwrap();
1112        let resume_environment = capture.read();
1113        assert!(!resume_environment.contains_key("PATH"));
1114        assert_eq!(
1115            resume_environment
1116                .get("CODEX_WRAPPER_EXPLICIT")
1117                .map(String::as_str),
1118            Some("resume")
1119        );
1120    }
1121
1122    /// Stdin delivery and graceful cancellation each construct their own
1123    /// spawn specification, so cover both instead of treating the buffered
1124    /// test as proof for them.
1125    #[cfg(unix)]
1126    #[tokio::test]
1127    async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
1128        let capture = crate::test_support::EnvCapture::new("env-specialized");
1129        let codex = crate::test_support::env_capturing_codex(&capture)
1130            .env("CODEX_WRAPPER_EXPLICIT", "specialized")
1131            .clear_env()
1132            .build()
1133            .expect("bash must exist");
1134
1135        crate::ExecCommand::new("stdin prompt")
1136            .prompt_via_stdin()
1137            .execute(&codex)
1138            .await
1139            .unwrap();
1140        let stdin_environment = capture.read();
1141        assert!(!stdin_environment.contains_key("PATH"));
1142        assert_eq!(
1143            stdin_environment
1144                .get("CODEX_WRAPPER_EXPLICIT")
1145                .map(String::as_str),
1146            Some("specialized")
1147        );
1148
1149        let never = std::future::pending::<()>();
1150        run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
1151            .await
1152            .unwrap();
1153        let cancellable_environment = capture.read();
1154        assert!(!cancellable_environment.contains_key("PATH"));
1155        assert_eq!(
1156            cancellable_environment
1157                .get("CODEX_WRAPPER_EXPLICIT")
1158                .map(String::as_str),
1159            Some("specialized")
1160        );
1161    }
1162
1163    #[cfg(unix)]
1164    #[tokio::test]
1165    async fn environment_values_do_not_leak_into_spawn_errors() {
1166        let secret = "spawn-error-must-not-leak-this";
1167        let codex = Codex::builder()
1168            .binary("/codex-wrapper/this-binary-does-not-exist")
1169            .clear_env()
1170            .env("CODEX_WRAPPER_SECRET", secret)
1171            .build()
1172            .unwrap();
1173
1174        let error = run_codex(&codex, vec!["exec".into()])
1175            .await
1176            .expect_err("the fake path must not spawn");
1177        assert!(!error.to_string().contains(secret));
1178        assert!(!format!("{error:?}").contains(secret));
1179    }
1180
1181    /// A wrapper timeout is not terminal until the direct child is reaped.
1182    #[cfg(unix)]
1183    #[tokio::test]
1184    async fn timeout_kills_the_spawned_process() {
1185        use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1186
1187        let pid_file = PidFile::new("exec-timeout");
1188        let codex = blocking_codex(&pid_file)
1189            .timeout(Duration::from_millis(500))
1190            .build()
1191            .expect("bash must exist");
1192
1193        let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
1194        assert!(
1195            matches!(result, Err(Error::Timeout { .. })),
1196            "expected timeout error, got: {result:?}"
1197        );
1198
1199        let pid = pid_file.read_pid().await;
1200        assert!(
1201            !is_running_for_test(pid),
1202            "codex ({pid}) survived the timeout"
1203        );
1204    }
1205
1206    /// The caller dropping the future is the case an operator kill or a
1207    /// graceful shutdown produces, with no wrapper timeout involved.
1208    #[cfg(unix)]
1209    #[tokio::test]
1210    async fn cancellation_kills_the_spawned_process() {
1211        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
1212
1213        let pid_file = PidFile::new("exec-cancel");
1214        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
1215
1216        let cancelled = tokio::time::timeout(
1217            Duration::from_millis(500),
1218            run_codex(&codex, vec!["exec".into(), "probe".into()]),
1219        )
1220        .await;
1221        assert!(
1222            cancelled.is_err(),
1223            "fake codex should still have been running, got: {cancelled:?}"
1224        );
1225
1226        let pid = pid_file.read_pid().await;
1227        assert!(
1228            wait_until_gone(pid).await,
1229            "codex ({pid}) survived the dropped future"
1230        );
1231    }
1232
1233    /// Minimal recording subscriber, written by hand because #63 rules out a
1234    /// new dependency and `tracing-subscriber` would be one.
1235    ///
1236    /// Installed once as the **global** default, fanning out to a per-thread
1237    /// sink. A thread-local `set_default` is not enough: tracing caches
1238    /// callsite interest globally, so a test running concurrently against no
1239    /// subscriber caches this crate's span callsites as `never` and the
1240    /// recording test then sees nothing. That produced a real flake, about one
1241    /// run in three. A single always-enabled global subscriber keeps interest
1242    /// stable, and the per-thread sink keeps tests isolated.
1243    #[cfg(unix)]
1244    mod recorder {
1245        use std::cell::RefCell;
1246        use std::sync::{Arc, Mutex, Once};
1247
1248        use tracing::field::{Field, Visit};
1249        use tracing::span::{Attributes, Id, Record};
1250        use tracing::{Event, Metadata, Subscriber};
1251
1252        type Sink = Arc<Mutex<Vec<(String, String)>>>;
1253
1254        thread_local! {
1255            static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1256        }
1257
1258        struct Global;
1259
1260        impl Global {
1261            fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
1262                SINK.with(|sink| {
1263                    if let Some(sink) = sink.borrow().as_ref() {
1264                        f(&mut sink.lock().unwrap());
1265                    }
1266                });
1267            }
1268        }
1269
1270        impl Subscriber for Global {
1271            /// Always true, so callsite interest is never cached as `never`.
1272            fn enabled(&self, _: &Metadata<'_>) -> bool {
1273                true
1274            }
1275            fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1276                Self::collect(|fields| attrs.record(&mut Collect(fields)));
1277                Id::from_u64(1)
1278            }
1279            fn record(&self, _: &Id, values: &Record<'_>) {
1280                Self::collect(|fields| values.record(&mut Collect(fields)));
1281            }
1282            fn record_follows_from(&self, _: &Id, _: &Id) {}
1283            fn event(&self, _: &Event<'_>) {}
1284            fn enter(&self, _: &Id) {}
1285            fn exit(&self, _: &Id) {}
1286        }
1287
1288        struct Collect<'a>(&'a mut Vec<(String, String)>);
1289
1290        impl Visit for Collect<'_> {
1291            fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
1292                self.0.push((field.name().into(), format!("{value:?}")));
1293            }
1294            fn record_str(&mut self, field: &Field, value: &str) {
1295                self.0.push((field.name().into(), value.into()));
1296            }
1297            fn record_i64(&mut self, field: &Field, value: i64) {
1298                self.0.push((field.name().into(), value.to_string()));
1299            }
1300            fn record_u64(&mut self, field: &Field, value: u64) {
1301                self.0.push((field.name().into(), value.to_string()));
1302            }
1303        }
1304
1305        pub(super) struct Recorder(Sink);
1306
1307        impl Recorder {
1308            /// Start recording spans raised on this thread.
1309            pub(super) fn install() -> Self {
1310                static INIT: Once = Once::new();
1311                INIT.call_once(|| {
1312                    let _ = tracing::subscriber::set_global_default(Global);
1313                });
1314                let sink: Sink = Arc::new(Mutex::new(Vec::new()));
1315                SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
1316                Self(sink)
1317            }
1318
1319            pub(super) fn dump(&self) -> String {
1320                format!("{:?}", self.0.lock().unwrap())
1321            }
1322
1323            pub(super) fn value(&self, field: &str) -> Option<String> {
1324                self.0
1325                    .lock()
1326                    .unwrap()
1327                    .iter()
1328                    .rev()
1329                    .find(|(name, _)| name == field)
1330                    .map(|(_, value)| value.clone())
1331            }
1332        }
1333
1334        impl Drop for Recorder {
1335            fn drop(&mut self) {
1336                SINK.with(|slot| *slot.borrow_mut() = None);
1337            }
1338        }
1339    }
1340
1341    #[cfg(unix)]
1342    #[tokio::test]
1343    async fn span_records_the_subcommand_and_a_clean_outcome() {
1344        let recorder = recorder::Recorder::install();
1345
1346        let codex = Codex::builder()
1347            .binary("/bin/echo")
1348            .build()
1349            .expect("echo must exist");
1350        run_codex(&codex, vec!["exec".into()]).await.unwrap();
1351
1352        assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
1353        assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
1354        assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
1355        assert!(recorder.value("duration_ms").is_some());
1356    }
1357
1358    /// The prompt must never reach the span. It is in argv, so recording the
1359    /// arguments would leak it into any host's logs.
1360    #[cfg(unix)]
1361    #[tokio::test]
1362    async fn span_does_not_carry_the_prompt() {
1363        let recorder = recorder::Recorder::install();
1364
1365        let codex = Codex::builder()
1366            .binary("/bin/echo")
1367            .build()
1368            .expect("echo must exist");
1369        run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
1370            .await
1371            .unwrap();
1372
1373        let recorded = format!("{:?}", recorder.value("subcommand"));
1374        assert!(!recorded.contains("secret"));
1375        for field in ["binary", "working_dir", "outcome", "exit_code"] {
1376            let value = recorder.value(field).unwrap_or_default();
1377            assert!(
1378                !value.contains("secret"),
1379                "{field} leaked the prompt: {value}"
1380            );
1381        }
1382    }
1383
1384    /// A dropped future records an outcome rather than leaving the span open,
1385    /// so an abandoned run is distinguishable from one still in progress.
1386    #[cfg(unix)]
1387    #[tokio::test]
1388    async fn a_cancelled_run_is_recorded_as_cancelled() {
1389        let recorder = recorder::Recorder::install();
1390
1391        let pid_file = crate::test_support::PidFile::new("span-cancel");
1392        let codex = crate::test_support::blocking_codex(&pid_file)
1393            .build()
1394            .expect("bash must exist");
1395
1396        let cancelled = tokio::time::timeout(
1397            Duration::from_millis(300),
1398            run_codex(&codex, vec!["exec".into()]),
1399        )
1400        .await;
1401        assert!(cancelled.is_err(), "the run should still have been going");
1402
1403        assert_eq!(
1404            recorder.value("outcome").as_deref(),
1405            Some("cancelled"),
1406            "recorded: {}",
1407            recorder.dump()
1408        );
1409    }
1410
1411    /// A wrapper timeout is its own outcome, distinct from a caller
1412    /// cancelling: the run reached its deadline rather than being abandoned.
1413    #[cfg(unix)]
1414    #[tokio::test]
1415    async fn a_timed_out_run_is_recorded_as_timeout() {
1416        let recorder = recorder::Recorder::install();
1417
1418        let pid_file = crate::test_support::PidFile::new("span-timeout");
1419        let codex = crate::test_support::blocking_codex(&pid_file)
1420            .timeout(Duration::from_millis(300))
1421            .build()
1422            .expect("bash must exist");
1423
1424        let result = run_codex(&codex, vec!["exec".into()]).await;
1425        assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
1426
1427        assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
1428    }
1429
1430    // -----------------------------------------------------------------
1431    // Classification end to end (#85)
1432    // -----------------------------------------------------------------
1433
1434    #[cfg(unix)]
1435    fn failing_codex(case: &str) -> Codex {
1436        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1437            .join("tests")
1438            .join("fake-codex-failure.sh");
1439        Codex::builder()
1440            .binary("/bin/bash")
1441            .arg(script.to_str().unwrap())
1442            .env("CODEX_WRAPPER_TEST_FAILURE", case)
1443            .build()
1444            .expect("bash must exist")
1445    }
1446
1447    /// Classification has to happen on the spawn path, not only in the
1448    /// constructor, or a caller still gets a bare CommandFailed.
1449    #[cfg(unix)]
1450    #[tokio::test]
1451    async fn a_real_spawn_returns_a_classified_error() {
1452        use crate::error::FailureKind;
1453
1454        for (case, expected) in [
1455            ("auth", FailureKind::Auth),
1456            ("not-trusted", FailureKind::NotTrustedDirectory),
1457            ("config", FailureKind::Config),
1458            ("session", FailureKind::SessionNotFound),
1459            ("mystery", FailureKind::Unclassified),
1460        ] {
1461            let codex = failing_codex(case);
1462            let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
1463            assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
1464        }
1465    }
1466
1467    /// A deterministic failure must not be retried even when its exit code is
1468    /// on the retry list. Re-running gets the same rejection, and the auth
1469    /// case has already been retried inside the CLI before it reaches here.
1470    #[cfg(unix)]
1471    #[tokio::test]
1472    async fn a_classified_failure_is_not_retried() {
1473        let policy = crate::retry::RetryPolicy::new()
1474            .max_attempts(3)
1475            .initial_backoff(Duration::from_millis(1))
1476            .retry_on_exit_codes([1]);
1477
1478        let started = Instant::now();
1479        let codex = failing_codex("auth");
1480        let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
1481            .await
1482            .unwrap_err();
1483
1484        assert!(matches!(err, Error::Auth { .. }), "{err}");
1485        // Three attempts with backoff would be visibly slower; this asserts
1486        // the shape rather than the timing, but the timing corroborates it.
1487        assert!(
1488            started.elapsed() < Duration::from_secs(2),
1489            "looks like it retried: {:?}",
1490            started.elapsed()
1491        );
1492    }
1493
1494    /// An unclassified failure keeps the old retry behaviour.
1495    #[cfg(unix)]
1496    #[tokio::test]
1497    async fn an_unclassified_failure_still_retries() {
1498        let policy = crate::retry::RetryPolicy::new()
1499            .max_attempts(2)
1500            .initial_backoff(Duration::from_millis(1))
1501            .retry_on_exit_codes([1]);
1502
1503        let codex = failing_codex("mystery");
1504        let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
1505            .await
1506            .unwrap_err();
1507
1508        assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
1509    }
1510
1511    /// The allow-list works on the exit code, so it still applies to a
1512    /// failure that classification moved off CommandFailed.
1513    #[cfg(unix)]
1514    #[tokio::test]
1515    async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
1516        let codex = failing_codex("auth");
1517        let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
1518            .await
1519            .expect("exit code 1 was allowed");
1520
1521        assert_eq!(output.exit_code, 1);
1522        assert!(!output.success);
1523        assert!(
1524            output.stderr.contains("401 Unauthorized"),
1525            "{}",
1526            output.stderr
1527        );
1528    }
1529
1530    // -----------------------------------------------------------------
1531    // Process groups and cancellation (#78)
1532    // -----------------------------------------------------------------
1533
1534    /// A fake codex that spawns a child of its own, the way the real CLI does
1535    /// for tool use, and the pids of both.
1536    #[cfg(unix)]
1537    fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
1538        let pid_file = crate::test_support::PidFile::new(label);
1539        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1540            .join("tests")
1541            .join("fake-codex-spawns-child.sh");
1542        let codex = Codex::builder()
1543            .binary("/bin/bash")
1544            .arg(script.to_str().unwrap())
1545            .env(
1546                "CODEX_WRAPPER_TEST_PIDFILE",
1547                pid_file.path().to_str().unwrap(),
1548            )
1549            .build()
1550            .expect("bash must exist");
1551        (codex, pid_file)
1552    }
1553
1554    #[cfg(unix)]
1555    async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
1556        for _ in 0..200 {
1557            if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
1558                let parse = |prefix: &str| -> Option<u32> {
1559                    contents
1560                        .lines()
1561                        .find_map(|l| l.strip_prefix(prefix))
1562                        .and_then(|v| v.trim().parse().ok())
1563                };
1564                if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
1565                    return (parent, child);
1566                }
1567            }
1568            tokio::time::sleep(Duration::from_millis(10)).await;
1569        }
1570        panic!("the fake codex never recorded both pids");
1571    }
1572
1573    /// The point of #78. `kill_on_drop` reaps the direct child only, so before
1574    /// process groups the grandchild outlived a cancelled run.
1575    #[cfg(unix)]
1576    #[tokio::test]
1577    async fn cancelling_kills_the_whole_process_group() {
1578        use crate::test_support::wait_until_gone;
1579
1580        let (codex, pid_file) = spawning_codex("group-drop");
1581
1582        let cancelled = tokio::time::timeout(
1583            Duration::from_millis(400),
1584            run_codex(&codex, vec!["exec".into()]),
1585        )
1586        .await;
1587        assert!(cancelled.is_err(), "the run should still have been going");
1588
1589        let (parent, child) = read_pids(&pid_file).await;
1590        assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
1591        assert!(
1592            wait_until_gone(child).await,
1593            "the subprocess ({child}) survived the cancelled run"
1594        );
1595    }
1596
1597    /// The graceful path: SIGTERM, a grace period, then SIGKILL. It cannot
1598    /// live in `Drop`, which is why there is an explicit entry point.
1599    #[cfg(unix)]
1600    #[tokio::test]
1601    async fn run_codex_cancellable_stops_the_group_gracefully() {
1602        use crate::test_support::is_running_for_test;
1603
1604        let (codex, pid_file) = spawning_codex("group-cancel");
1605        let codex = Codex::builder()
1606            .binary(codex.binary())
1607            .arg(
1608                std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1609                    .join("tests")
1610                    .join("fake-codex-spawns-child.sh")
1611                    .to_str()
1612                    .unwrap(),
1613            )
1614            .env(
1615                "CODEX_WRAPPER_TEST_PIDFILE",
1616                pid_file.path().to_str().unwrap(),
1617            )
1618            .termination_grace(Duration::from_millis(50))
1619            .build()
1620            .unwrap();
1621
1622        let cancel = async {
1623            tokio::time::sleep(Duration::from_millis(300)).await;
1624        };
1625        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
1626
1627        assert!(
1628            matches!(result, Err(Error::Cancelled { .. })),
1629            "expected a cancellation, got: {result:?}"
1630        );
1631
1632        let (parent, child) = read_pids(&pid_file).await;
1633        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1634        assert!(
1635            !is_running_for_test(child),
1636            "the subprocess ({child}) survived cancellation"
1637        );
1638    }
1639
1640    /// Buffered timeout uses the same settled process-tree cleanup as an
1641    /// explicit cancellation signal.
1642    #[cfg(unix)]
1643    #[tokio::test]
1644    async fn timeout_stops_the_group_before_returning() {
1645        use crate::test_support::is_running_for_test;
1646
1647        let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
1648        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1649            .join("tests")
1650            .join("fake-codex-spawns-child.sh");
1651        let codex = Codex::builder()
1652            .binary("/bin/bash")
1653            .arg(script.to_str().unwrap())
1654            .env(
1655                "CODEX_WRAPPER_TEST_PIDFILE",
1656                pid_file.path().to_str().unwrap(),
1657            )
1658            .timeout(Duration::from_millis(300))
1659            .termination_grace(Duration::from_millis(10))
1660            .build()
1661            .unwrap();
1662
1663        let result = run_codex(&codex, vec!["exec".into()]).await;
1664        assert!(
1665            matches!(result, Err(Error::Timeout { .. })),
1666            "expected a timeout, got: {result:?}"
1667        );
1668
1669        let (parent, child) = read_pids(&pid_file).await;
1670        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1671        assert!(
1672            !is_running_for_test(child),
1673            "the subprocess ({child}) survived the timeout"
1674        );
1675    }
1676
1677    /// A broken stdin pipe is terminal only after the process tree has been
1678    /// stopped. Returning the write error first would release the caller while
1679    /// the provider could still mutate the workspace.
1680    #[cfg(unix)]
1681    #[tokio::test]
1682    async fn stdin_write_failure_stops_and_reaps_before_returning() {
1683        use crate::test_support::is_running_for_test;
1684
1685        let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
1686        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1687            .join("tests")
1688            .join("fake-codex-closes-stdin-spawns-child.sh");
1689        let codex = Codex::builder()
1690            .binary("/bin/bash")
1691            .arg(script.to_str().unwrap())
1692            .env(
1693                "CODEX_WRAPPER_TEST_PIDFILE",
1694                pid_file.path().to_str().unwrap(),
1695            )
1696            .termination_grace(Duration::from_millis(10))
1697            .build()
1698            .unwrap();
1699
1700        let prompt = "x".repeat(4 * 1024 * 1024);
1701        let result = run_codex_with_stdin_prompt(
1702            &codex,
1703            crate::ExecCommand::from_stdin(&prompt).args(),
1704            &prompt,
1705        )
1706        .await;
1707        assert!(
1708            matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
1709            "expected a stdin error, got: {result:?}"
1710        );
1711
1712        let (parent, child) = read_pids(&pid_file).await;
1713        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1714        assert!(
1715            !is_running_for_test(child),
1716            "the subprocess ({child}) survived the stdin failure"
1717        );
1718    }
1719
1720    /// A run that finishes before the signal must not be reported as
1721    /// cancelled, and must not be killed on the way out.
1722    #[cfg(unix)]
1723    #[tokio::test]
1724    async fn a_run_that_finishes_first_is_not_cancelled() {
1725        let codex = Codex::builder()
1726            .binary("/bin/echo")
1727            .build()
1728            .expect("echo must exist");
1729
1730        let never = std::future::pending::<()>();
1731        let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
1732            .await
1733            .unwrap();
1734        assert!(output.success);
1735    }
1736
1737    #[cfg(unix)]
1738    #[tokio::test]
1739    async fn spawn_observer_reports_each_buffered_child_before_returning() {
1740        use std::sync::{Arc, Mutex};
1741
1742        let seen = Arc::new(Mutex::new(Vec::new()));
1743        let sink = Arc::clone(&seen);
1744        let codex = Codex::builder()
1745            .binary("/bin/echo")
1746            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1747            .build()
1748            .expect("echo must exist");
1749
1750        let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
1751        let seen = seen.lock().unwrap();
1752        assert_eq!(seen.len(), 1);
1753        assert!(seen[0].pid > 0);
1754        assert_eq!(seen[0].pgid, Some(seen[0].pid));
1755        assert!(output.stdout.contains("probe"));
1756    }
1757
1758    #[cfg(unix)]
1759    #[tokio::test]
1760    async fn spawn_receipt_never_claims_a_shared_group() {
1761        use std::sync::{Arc, Mutex};
1762
1763        let seen = Arc::new(Mutex::new(Vec::new()));
1764        let sink = Arc::clone(&seen);
1765        let codex = Codex::builder()
1766            .binary("/bin/echo")
1767            .process_group(false)
1768            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1769            .build()
1770            .expect("echo must exist");
1771
1772        run_codex(&codex, vec!["probe".into()]).await.unwrap();
1773        assert_eq!(seen.lock().unwrap()[0].pgid, None);
1774    }
1775
1776    #[test]
1777    fn parent_death_support_matches_the_target() {
1778        assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
1779    }
1780
1781    #[cfg(unix)]
1782    #[tokio::test]
1783    async fn parent_death_policy_composes_with_spawn_observation() {
1784        use std::sync::{Arc, Mutex};
1785
1786        let seen = Arc::new(Mutex::new(Vec::new()));
1787        let sink = Arc::clone(&seen);
1788        let codex = Codex::builder()
1789            .binary("/bin/echo")
1790            .die_with_parent(true)
1791            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1792            .build()
1793            .expect("echo must exist");
1794
1795        run_codex(&codex, vec!["probe".into()]).await.unwrap();
1796        assert_eq!(seen.lock().unwrap().len(), 1);
1797    }
1798
1799    const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
1800
1801    #[test]
1802    fn pdeathsig_helper_process() {
1803        if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
1804            return;
1805        }
1806        use std::io::Write;
1807        use std::sync::Arc;
1808
1809        let codex = Codex::builder()
1810            .binary("/bin/sleep")
1811            .die_with_parent(true)
1812            .on_spawn(Arc::new(|info| {
1813                println!("PID {}", info.pid);
1814                let _ = std::io::stdout().flush();
1815            }))
1816            .build()
1817            .unwrap();
1818        let runtime = tokio::runtime::Builder::new_current_thread()
1819            .enable_all()
1820            .build()
1821            .unwrap();
1822        let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
1823    }
1824
1825    #[cfg(target_os = "linux")]
1826    #[test]
1827    fn child_dies_when_its_parent_is_sigkilled() {
1828        use std::io::{BufRead, BufReader};
1829        use std::process::{Command, Stdio};
1830
1831        let executable = std::env::current_exe().expect("test binary path");
1832        let mut helper = Command::new(executable)
1833            .args([
1834                "--exact",
1835                "exec::tests::pdeathsig_helper_process",
1836                "--nocapture",
1837            ])
1838            .env(PDEATHSIG_HELPER_ENV, "1")
1839            .stdout(Stdio::piped())
1840            .spawn()
1841            .expect("spawn helper");
1842        let stdout = helper.stdout.take().expect("piped stdout");
1843        let pid = BufReader::new(stdout)
1844            .lines()
1845            .map_while(std::result::Result::ok)
1846            .find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
1847            .expect("helper reported child pid");
1848
1849        // SAFETY: this deliberately simulates an uncatchable supervisor crash.
1850        unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
1851        let _ = helper.wait();
1852
1853        for _ in 0..50 {
1854            if !crate::test_support::is_running_for_test(pid) {
1855                return;
1856            }
1857            std::thread::sleep(Duration::from_millis(100));
1858        }
1859        panic!("child {pid} survived its SIGKILLed parent");
1860    }
1861
1862    /// Opting out is not cosmetic: without a group of its own, cancelling
1863    /// reaches the direct child only and its subprocesses survive. That is the
1864    /// terminal-attached contract, where the terminal is the supervisor and
1865    /// Ctrl-C reaches the whole run directly instead.
1866    #[cfg(unix)]
1867    #[tokio::test]
1868    async fn opting_out_of_process_groups_leaves_the_subprocess() {
1869        use crate::test_support::wait_until_gone;
1870
1871        let pid_file = crate::test_support::PidFile::new("group-optout");
1872        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1873            .join("tests")
1874            .join("fake-codex-spawns-child.sh");
1875        let codex = Codex::builder()
1876            .binary("/bin/bash")
1877            .arg(script.to_str().unwrap())
1878            .env(
1879                "CODEX_WRAPPER_TEST_PIDFILE",
1880                pid_file.path().to_str().unwrap(),
1881            )
1882            .process_group(false)
1883            .build()
1884            .expect("bash must exist");
1885
1886        let cancelled = tokio::time::timeout(
1887            Duration::from_millis(400),
1888            run_codex(&codex, vec!["exec".into()]),
1889        )
1890        .await;
1891        assert!(cancelled.is_err(), "the run should still have been going");
1892
1893        let (parent, child) = read_pids(&pid_file).await;
1894        assert!(
1895            wait_until_gone(parent).await,
1896            "kill_on_drop still reaps the direct child ({parent})"
1897        );
1898        // The point of the contrast with
1899        // `cancelling_kills_the_whole_process_group`.
1900        assert!(
1901            crate::test_support::is_running_for_test(child),
1902            "with groups off, the subprocess ({child}) is expected to survive"
1903        );
1904        // Do not leave it behind.
1905        signal_group(child, libc::SIGKILL);
1906        unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
1907    }
1908}