Skip to main content

oxdock_core/exec/
io.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2use std::io::{self, Write};
3use std::sync::{Arc, Mutex, atomic::AtomicU64};
4
5use anyhow::Result;
6use oxdock_diagnostics::DiagnosticResult;
7#[cfg(not(miri))]
8use oxdock_pipe::OsPipeWriter;
9use oxdock_pipe::{
10    KeeperGuard, Materialized, PipeHandle, PipeInfo, PipeInner, SharedInput, SharedOutput,
11    inspect as inspect_handle, materialize, peek as peek_handle, script_backend,
12};
13use oxdock_process::{CommandStderr, CommandStdin, CommandStdout};
14
15/// Fan-out writer for background tasks: every default-routed byte goes
16/// to the parent handle exactly as an unwrapped write would, and a copy
17/// lands in the task's tail ring for `TASK_POLL`. Parent semantics are
18/// preserved verbatim (Stream sink, inherited host stdio, OS-pipe bail),
19/// so the only observable difference is the retained copy.
20pub(super) struct TaskTee {
21    parent: Option<StreamHandle>,
22    tails: Arc<Mutex<super::state::TaskTails>>,
23    stream: TeeStream,
24}
25
26impl TaskTee {
27    /// Wrap a worker handle: `None` parent inherits host stdio, matching
28    /// `write_stdout`/`write_stderr` behavior for the unwrapped case.
29    pub(super) fn wrap(
30        parent: Option<StreamHandle>,
31        tails: &Arc<Mutex<super::state::TaskTails>>,
32        stream: TeeStream,
33    ) -> Option<StreamHandle> {
34        Some(StreamHandle::Stream(Arc::new(Mutex::new(Self {
35            parent,
36            tails: Arc::clone(tails),
37            stream,
38        }))))
39    }
40}
41
42impl Write for TaskTee {
43    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
44        match &self.parent {
45            Some(StreamHandle::Stream(writer)) => {
46                if let Ok(mut guard) = writer.lock() {
47                    guard.write_all(buf)?;
48                }
49            }
50            #[cfg(not(miri))]
51            Some(StreamHandle::Os(_)) => {
52                return Err(io::Error::other(
53                    "cannot write DSL output to a live OS pipe",
54                ));
55            }
56            None => match self.stream {
57                TeeStream::Stdout => io::stdout().write_all(buf)?,
58                TeeStream::Stderr => io::stderr().write_all(buf)?,
59            },
60        }
61        if let Ok(mut tails) = self.tails.lock() {
62            tails.push(self.stream, buf);
63        }
64        Ok(buf.len())
65    }
66
67    fn flush(&mut self) -> io::Result<()> {
68        Ok(())
69    }
70}
71
72/// Handle-scoped pipe resolution. No central index exists: every method
73/// below takes the `PIPE` value's backend cell, materializing it on first
74/// binding (first-binding-wins under the cell lock) and adapting later
75/// bindings through the existing machinery. The `ExecIo` receiver carries
76/// no pipe state; methods live here (rather than as free functions) so
77/// call sites keep their `cx.state.io.*` shape.
78#[derive(Clone, Default)]
79pub(super) struct PipeRegistry;
80
81/// Loud take-twice error for OS handles: a second consumer or producer on
82/// one end can never steal the descriptor, and (unlike the old recycling
83/// behavior) never silently receives a fresh pair either : the remedy is a
84/// fresh declaration. No rebind rule exists by design: no rule can tell
85/// sequential loop reuse apart from concurrent fan-in sharing.
86#[cfg(not(miri))]
87fn spent_handle() -> oxdock_diagnostics::Diagnostic {
88    super::diagnostics::std_pipe_handle_spent()
89}
90
91impl PipeRegistry {
92    /// First-binding-wins materialization for one binding site: an unbound
93    /// handle decides its kind from `promote` (the caller supplies full
94    /// usage context); a decided handle is returned unchanged. Callers
95    /// adapt mismatches through resolution below, never here.
96    pub(super) fn ensure_handle(handle: &PipeHandle, promote: bool) -> DiagnosticResult<()> {
97        materialize(handle, promote)?;
98        Ok(())
99    }
100
101    /// Non-destructive snapshot of a script handle's buffered bytes for
102    /// pipe-content assertions. Delegates to the backend without creating:
103    /// unbound handles and OS pairs bail loudly instead of yielding empty
104    /// content.
105    ///
106    /// Public so out-of-crate harnesses can assert on script-owned pipes
107    /// after a run completes, via the `PIPE` values in the returned
108    /// bindings. Only meaningful once writers detached (post-run).
109    pub fn peek_pipe_content(handle: &PipeHandle) -> DiagnosticResult<Vec<u8>> {
110        peek_handle(handle)
111    }
112
113    /// Snapshot one handle for `INSPECT()` diagnostics.
114    pub(super) fn inspect_pipe(handle: &PipeHandle) -> PipeInfo {
115        inspect_handle(handle)
116    }
117
118    /// Pin a keeper slot on a script backend so transient writer churn can
119    /// never observe zero writers. Returns `None` for OS-materialized and
120    /// unbound handles, which need no pin. Callers ensure the handle
121    /// first so OS promotion is honored and this never forces a script
122    /// backend into existence.
123    pub(super) fn pin_keeper(handle: &PipeHandle) -> DiagnosticResult<Option<KeeperGuard>> {
124        Ok(script_backend(handle).map(KeeperGuard::new))
125    }
126
127    /// Resolve a stdin binding against a decided handle. Script backends
128    /// hand out a shared reader (plus the backend for timeout-bounded
129    /// bridge reads); OS pairs hand the take-once reader to `RUN` directly
130    /// and bridge it to a shared handle for DSL commands. A second take
131    /// on one end bails loudly with the fresh-declaration remedy instead
132    /// of stealing the descriptor.
133    pub(super) fn resolve_stdin(
134        handle: &PipeHandle,
135        direct: bool,
136        promote: bool,
137    ) -> DiagnosticResult<(CommandStdin, Option<Arc<PipeInner>>)> {
138        // `direct` serves only the OS-pipe arms below, which are
139        // compiled out under Miri.
140        let _ = direct;
141        match materialize(handle, promote)? {
142            Materialized::Script(backend) => {
143                Ok((CommandStdin::Stream(backend.reader_handle()), Some(backend)))
144            }
145            #[cfg(not(miri))]
146            Materialized::Os(entry) => {
147                if direct {
148                    return Ok((CommandStdin::OsPipe(entry.reader.clone()), None));
149                }
150                let owned = entry.reader.take().map_err(|_| spent_handle())?;
151                Ok((
152                    CommandStdin::Stream(Arc::new(std::sync::Mutex::new(owned))),
153                    None,
154                ))
155            }
156        }
157    }
158
159    /// Resolve a stdout binding. Mirrors
160    /// [`PipeRegistry::resolve_stdin`] with `StreamHandle` outputs so
161    /// `RUN` keeps zero copy `Stdio` handoff, plus the script backend for
162    /// the bridge's socket-EOF force-close.
163    pub(super) fn resolve_stdout(
164        handle: &PipeHandle,
165        direct: bool,
166        promote: bool,
167    ) -> DiagnosticResult<(StreamHandle, Option<Arc<PipeInner>>)> {
168        // `direct` serves only the OS-pipe arms below, which are
169        // compiled out under Miri.
170        let _ = direct;
171        match materialize(handle, promote)? {
172            Materialized::Script(backend) => {
173                Ok((StreamHandle::Stream(backend.writer_handle()), Some(backend)))
174            }
175            #[cfg(not(miri))]
176            Materialized::Os(entry) => {
177                if direct {
178                    return Ok((StreamHandle::Os(entry.writer.clone()), None));
179                }
180                let owned = entry.writer.take().map_err(|_| spent_handle())?;
181                Ok((
182                    StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))),
183                    None,
184                ))
185            }
186        }
187    }
188
189    /// Resolve a stderr binding. Mirrors
190    /// [`PipeRegistry::resolve_stdout`]: `RUN` keeps zero copy handoff,
191    /// DSL commands get a bridged shared handle. Binding `stdout` and
192    /// `stderr` to one live OS handle takes the same slot twice, so the
193    /// second take bails deterministically; merge in shell via `2>&1`
194    /// instead.
195    pub(super) fn resolve_stderr(
196        handle: &PipeHandle,
197        direct: bool,
198        promote: bool,
199    ) -> DiagnosticResult<StreamHandle> {
200        // `direct` serves only the OS-pipe arms below, which are
201        // compiled out under Miri.
202        let _ = direct;
203        match materialize(handle, promote)? {
204            Materialized::Script(backend) => Ok(StreamHandle::Stream(backend.writer_handle())),
205            #[cfg(not(miri))]
206            Materialized::Os(entry) => {
207                if direct {
208                    return Ok(StreamHandle::Os(entry.writer.clone()));
209                }
210                let owned = entry.writer.take().map_err(|_| spent_handle())?;
211                Ok(StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))))
212            }
213        }
214    }
215}
216
217#[derive(Clone, Default)]
218pub struct ExecIo {
219    stdin: Option<SharedInput>,
220    stdout: Option<SharedOutput>,
221    stderr: Option<SharedOutput>,
222    inherit_env_overrides: HashMap<String, String>,
223    inherit_env_removed: HashSet<String>,
224    remote_runners: HashMap<String, RemoteRunnerArc>,
225    remote_guest: bool,
226    /// Shared sink for the guest execution manifest: when staged, executed
227    /// flagged `COPY` steps append their evaluated pairs here as well as
228    /// to state, so a serve loop holding only `ExecIo` can pack exactly
229    /// what ran. `None` on hosts (nothing records).
230    push_manifest_sink: Option<PushManifestSink>,
231    /// Shared pump-worker count for this run. The root hub adopts it
232    /// and forks inherit it, so one run's workers attribute to exactly
233    /// one counter even as tasks fan out.
234    worker_counter: Arc<AtomicU64>,
235    /// Host override for `INTERPRETER()`: the path returned instead of
236    /// the current executable. Staged by embedding hosts (and doc
237    /// conformance) whose in-process binary is not a CLI; `None` keeps
238    /// the `current_exe` default.
239    interpreter_override: Option<String>,
240    /// Verbatim CLI tail after the script position (#226): surfaced
241    /// script-side via `STD::ARGV()`. Staged by the CLI from
242    /// `Options.script_args`; embedding hosts stage their own argv.
243    script_args: Vec<String>,
244}
245
246/// Shared append-only manifest of executed `--to-host` declarations.
247pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
248
249/// Shared handle to the transport behind `REMOTE` blocks. Staged here (not
250/// threaded through every `run_steps_*` signature) so existing callers keep
251/// compiling: `None` means remote execution is unavailable and every
252/// `REMOTE` step bails naming the NET plugin.
253pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
254
255/// Standard chunk size for all I/O handlers.
256pub const CHUNK_SIZE: usize = 8192;
257
258/// Minimum ring buffer capacity. Actual capacity scales with needle length.
259const MIN_RING_CAPACITY: usize = 1024;
260
261/// Sliding window for streaming pattern matching in stream assertions.
262/// Maintains a ring buffer and detects matches inline as chunks pass through.
263pub(crate) struct SlidingWindow {
264    pub(crate) needle: Vec<u8>,
265    ring: VecDeque<u8>,
266    pub matched: bool,
267}
268
269impl SlidingWindow {
270    pub fn new(needle: Vec<u8>) -> Self {
271        Self {
272            ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
273            needle,
274            matched: false,
275        }
276    }
277
278    pub fn push_chunk(&mut self, chunk: &[u8]) {
279        if self.matched {
280            return;
281        }
282        // Eviction limit scales with needle length, never below MIN_RING_CAPACITY
283        let limit = self.needle.len().max(MIN_RING_CAPACITY);
284        for &byte in chunk {
285            self.ring.push_back(byte);
286            if self.ring.len() > limit {
287                self.ring.pop_front();
288            }
289            self.check_match();
290        }
291    }
292
293    /// Replace needle without discarding ring history.
294    /// Re-evaluates current ring against updated needle.
295    pub fn update_needle(&mut self, new_needle: Vec<u8>) {
296        if self.matched {
297            return;
298        }
299        self.needle = new_needle;
300        self.check_match();
301    }
302
303    fn check_match(&mut self) {
304        if self.matched || self.ring.len() < self.needle.len() {
305            return;
306        }
307        let start = self.ring.len() - self.needle.len();
308        if self
309            .ring
310            .iter()
311            .skip(start)
312            .zip(self.needle.iter())
313            .all(|(a, b)| a == b)
314        {
315            self.matched = true;
316        }
317    }
318
319    /// Return the ring buffer contents for debugging.
320    pub fn ring_buffer(&self) -> Vec<u8> {
321        self.ring.iter().copied().collect()
322    }
323}
324
325#[derive(Clone)]
326pub(super) enum StreamHandle {
327    Stream(SharedOutput),
328    /// Live OS kernel pipe writer handed to one concurrent producer.
329    /// Only `RUN` consumes this directly; DSL commands never observe it
330    /// because `with_io` bridges OS entries to shared handles for them.
331    #[cfg(not(miri))]
332    Os(OsPipeWriter),
333}
334
335impl StreamHandle {
336    pub(super) fn to_stdout(&self) -> CommandStdout {
337        match self {
338            StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
339            #[cfg(not(miri))]
340            StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
341        }
342    }
343
344    pub(super) fn to_stderr(&self) -> CommandStderr {
345        match self {
346            StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
347            #[cfg(not(miri))]
348            StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
349        }
350    }
351}
352
353pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
354where
355    F: FnOnce(&mut dyn Write) -> Result<()>,
356{
357    match handle {
358        Some(StreamHandle::Stream(writer)) => {
359            if let Ok(mut guard) = writer.lock() {
360                op(&mut *guard)?;
361            }
362            Ok(())
363        }
364        // DSL commands never observe a live OS handle: `with_io` bridges
365        // OS entries to shared handles for them, and promotion only fires
366        // for single RUN bodies. This arm is defensive only.
367        #[cfg(not(miri))]
368        Some(StreamHandle::Os(_)) => Err(anyhow::Error::new(
369            super::diagnostics::eval_write_live_pipe("stdout"),
370        )),
371        // `None` inherits host stdout: only explicit `Stream` bindings
372        // reroute DSL output.
373        None => {
374            let mut stdout = io::stdout();
375            op(&mut stdout)
376        }
377    }
378}
379
380pub(super) fn write_stderr<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
381where
382    F: FnOnce(&mut dyn Write) -> Result<()>,
383{
384    match handle {
385        Some(StreamHandle::Stream(writer)) => {
386            if let Ok(mut guard) = writer.lock() {
387                op(&mut *guard)?;
388            }
389            Ok(())
390        }
391        #[cfg(not(miri))]
392        Some(StreamHandle::Os(_)) => Err(anyhow::Error::new(
393            super::diagnostics::eval_write_live_pipe("stderr"),
394        )),
395        None => {
396            let mut stderr = io::stderr();
397            op(&mut stderr)
398        }
399    }
400}
401
402/// Slice-based byte adapter over pipe halves for host (`#[oxdock_func]`)
403///
404/// stateful functions. All byte movement goes through the standard traits
405/// on caller-owned buffers : `Read::read(&mut [u8])` and
406/// `Write::write(&[u8])` : so hosts can hand pipes directly to `serde_json`,
407/// `flate2`, `tar`, and friends with a single reused stack buffer and zero
408/// per-chunk allocation. `0` read means EOF exactly like `std::io`; never
409/// slurp a stream into one `Vec` (unbounded memory growth : stream it).
410/// `flush()` delegates to backend flush semantics, which for script pipes
411/// is a no-op that loses nothing: every `write()` wakes readers itself.
412///
413/// A host read blocks the calling task thread exactly like a DSL reader;
414/// EOF and half-close map identically to DSL consumers. Take-once applies
415/// like everywhere else: bridging an OS backend takes once, repeats bail.
416pub struct PipeStream {
417    reader: Option<SharedInput>,
418    writer: Option<SharedOutput>,
419}
420
421impl PipeStream {
422    /// Read-half adapter (e.g. over [`StepCtx::pipe_reader`](super::steps::StepCtx::pipe_reader)).
423    pub fn reader(reader: SharedInput) -> Self {
424        Self {
425            reader: Some(reader),
426            writer: None,
427        }
428    }
429
430    /// Write-half adapter (e.g. over [`StepCtx::pipe_writer`](super::steps::StepCtx::pipe_writer)).
431    pub fn writer(writer: SharedOutput) -> Self {
432        Self {
433            reader: None,
434            writer: Some(writer),
435        }
436    }
437
438    /// Both halves (e.g. a filter with separate in/out pipes).
439    pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
440        Self {
441            reader: Some(reader),
442            writer: Some(writer),
443        }
444    }
445}
446
447impl std::io::Read for PipeStream {
448    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
449        let Some(reader) = &self.reader else {
450            return Err(std::io::Error::new(
451                std::io::ErrorKind::NotConnected,
452                "pipe stream has no reader half",
453            ));
454        };
455        let mut guard = reader
456            .lock()
457            .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
458        guard.read(buf)
459    }
460}
461
462impl std::io::Write for PipeStream {
463    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
464        let Some(writer) = &self.writer else {
465            return Err(std::io::Error::new(
466                std::io::ErrorKind::NotConnected,
467                "pipe stream has no writer half",
468            ));
469        };
470        let mut guard = writer
471            .lock()
472            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
473        guard.write(buf)
474    }
475
476    fn flush(&mut self) -> std::io::Result<()> {
477        let Some(writer) = &self.writer else {
478            return Err(std::io::Error::new(
479                std::io::ErrorKind::NotConnected,
480                "pipe stream has no writer half",
481            ));
482        };
483        let mut guard = writer
484            .lock()
485            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
486        guard.flush()
487    }
488}
489
490/// Hard cap for `ASSERT_EQ`/`ASSERT_NE stdout` exact accumulators, mirroring the
491/// `SpillBuffer` spill threshold: exact stream matching is a test-time
492/// opt-in, and unbounded trials must use pipe targets or harness captures.
493pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
494
495/// Cumulative stdout record for one execution generation backing
496/// `ASSERT_EQ`/`ASSERT_NE stdout`. Unlike `SlidingWindow` nothing is ever evicted;
497/// once the cap is exceeded the entry latches `overflowed` and stops
498/// growing, and the asserting step reports it with remediation guidance.
499pub(crate) struct ExactCapture {
500    pub(crate) bytes: Vec<u8>,
501    pub(crate) overflowed: bool,
502}
503
504impl ExactCapture {
505    pub fn new() -> Self {
506        Self {
507            bytes: Vec::new(),
508            overflowed: false,
509        }
510    }
511
512    pub fn push_chunk(&mut self, chunk: &[u8]) {
513        if self.overflowed {
514            return;
515        }
516        if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
517            self.overflowed = true;
518            return;
519        }
520        self.bytes.extend_from_slice(chunk);
521    }
522}
523
524/// Which host stream a tee forwards to when no capture sink is configured.
525#[derive(Clone, Copy, PartialEq, Eq, Debug)]
526pub enum TeeStream {
527    Stdout,
528    Stderr,
529}
530
531/// One live output fragment: the bytes from a single tee write plus
532/// which host stream they belong to. Carried from the synchronous
533/// execution threads to the MCP forwarder over a bounded channel.
534#[derive(Clone, Debug)]
535pub struct StreamChunk {
536    /// Which host stream produced these bytes.
537    pub kind: TeeStream,
538    /// Raw bytes as written. Decoded lossily at the forward edge.
539    pub bytes: Vec<u8>,
540}
541
542/// Live-stream tap for a tool call. Cloned into every per-call tee:
543/// each default-routed write `try_send`s one chunk. Bounded channel,
544/// so a chatty tool cannot grow the queue without bound; overflow
545/// chunks are dropped and counted. Explicit `WITH_IO` redirections
546/// bypass the tee entirely, so redirected bytes never stream.
547#[derive(Clone, Debug)]
548pub struct StreamHook {
549    /// Bounded egress. `try_send` only: never blocks script execution.
550    pub tx: std::sync::mpsc::SyncSender<StreamChunk>,
551    /// Chunks dropped on a full channel. Read after the call for the
552    /// transit note; lossy transit never affects the tail buffers.
553    pub dropped: std::sync::Arc<std::sync::atomic::AtomicUsize>,
554}
555
556/// Wraps the configured stdout sink so every byte written to it is also
557/// pushed to all registered SlidingWindow observers for stream assertions.
558/// When no sink is configured (`inner` is `None`) bytes are forwarded to
559/// real stdout so interactive CLI output still reaches the terminal.
560struct TeeWriter {
561    inner: Option<SharedOutput>,
562    stream: TeeStream,
563    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
564    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
565    hook: Option<StreamHook>,
566}
567
568impl Write for TeeWriter {
569    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
570        // Forward to downstream (streaming)
571        match &self.inner {
572            Some(inner) => {
573                let mut guard = inner
574                    .lock()
575                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
576                guard.write_all(buf)?;
577            }
578            None => match self.stream {
579                TeeStream::Stdout => io::stdout().write_all(buf)?,
580                TeeStream::Stderr => io::stderr().write_all(buf)?,
581            },
582        }
583        // Push to ALL registered assertion windows (O(1) per byte per window)
584        if let Ok(mut windows) = self.windows.lock() {
585            for window in windows.values_mut() {
586                window.push_chunk(buf);
587            }
588        }
589        if let Ok(mut exact) = self.exact.lock() {
590            for capture in exact.values_mut() {
591                capture.push_chunk(buf);
592            }
593        }
594        // Live tap: default-routed bytes stream to the MCP forwarder.
595        // `try_send` only, so a slow client never blocks execution;
596        // overflow drops and counts. Redirected bytes never reach this
597        // tee, so explicit `WITH_IO` stays silent by construction.
598        if let Some(hook) = &self.hook {
599            let chunk = StreamChunk {
600                kind: self.stream,
601                bytes: buf.to_vec(),
602            };
603            if hook.tx.try_send(chunk).is_err() {
604                hook.dropped
605                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
606            }
607        }
608        Ok(buf.len())
609    }
610
611    fn flush(&mut self) -> io::Result<()> {
612        match &self.inner {
613            Some(inner) => {
614                let mut guard = inner
615                    .lock()
616                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
617                guard.flush()?;
618            }
619            None => match self.stream {
620                TeeStream::Stdout => io::stdout().flush()?,
621                TeeStream::Stderr => io::stderr().flush()?,
622            },
623        }
624        Ok(())
625    }
626}
627
628/// Installs the tee around `sink` (or real stdout when absent).
629pub(crate) fn teed_stdout(
630    sink: Option<SharedOutput>,
631    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
632    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
633    hook: Option<StreamHook>,
634) -> SharedOutput {
635    Arc::new(Mutex::new(TeeWriter {
636        inner: sink,
637        stream: TeeStream::Stdout,
638        windows,
639        exact,
640        hook,
641    }))
642}
643
644/// Installs the tee around `sink` (or real stderr when absent) for
645/// `ASSERT_CONTAINS stderr` substring observers. Exact matching is not
646/// offered over stderr; use pipe targets or harness captures instead.
647pub(crate) fn teed_stderr(
648    sink: Option<SharedOutput>,
649    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
650    hook: Option<StreamHook>,
651) -> SharedOutput {
652    Arc::new(Mutex::new(TeeWriter {
653        inner: sink,
654        stream: TeeStream::Stderr,
655        windows,
656        exact: Arc::new(Mutex::new(HashMap::new())),
657        hook,
658    }))
659}
660
661impl ExecIo {
662    pub fn new() -> Self {
663        Self::default()
664    }
665
666    pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
667        self.stdin = stdin;
668    }
669
670    pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
671        self.stdout = stdout.clone();
672        if self.stderr.is_none() {
673            self.stderr = stdout;
674        }
675    }
676
677    pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
678        self.stderr = stderr;
679    }
680
681    /// Stage this run's pump-worker count. Chainable.
682    pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
683        self.worker_counter = counter;
684        self
685    }
686
687    /// This run's shared pump-worker count.
688    pub fn worker_counter(&self) -> Arc<AtomicU64> {
689        Arc::clone(&self.worker_counter)
690    }
691
692    /// Stage the `INTERPRETER()` path for this run. Chainable. Embedding
693    /// hosts whose engine runs in-process (no CLI binary as the current
694    /// executable) point this at their CLI so child reinvocation leaves
695    /// the process boundary intact.
696    pub fn set_interpreter<S: Into<String>>(&mut self, path: S) -> &mut Self {
697        self.interpreter_override = Some(path.into());
698        self
699    }
700
701    /// The staged interpreter path, if any. `None` selects the
702    /// `current_exe` default.
703    pub fn interpreter_override(&self) -> Option<String> {
704        self.interpreter_override.clone()
705    }
706
707    /// Stage this run's script args for `STD::ARGV()`. Chainable.
708    /// Callers pass the post-separator tail: the CLI strips one leading
709    /// `--` before staging, so embedded hosts stage already-stripped args.
710    pub fn set_script_args<I, S>(&mut self, args: I) -> &mut Self
711    where
712        I: IntoIterator<Item = S>,
713        S: Into<String>,
714    {
715        self.script_args = args.into_iter().map(Into::into).collect();
716        self
717    }
718
719    /// The staged script args for this run.
720    pub fn script_args(&self) -> &[String] {
721        &self.script_args
722    }
723
724    /// Stage the transport behind one `REMOTE` target. Chainable; the NET
725    /// plugin registers one session per inventory target at CLI startup
726    /// and tests stage mocks. Registration is inert (no process spawns
727    /// until a block entry runs).
728    pub fn set_remote_runner_for_target(
729        &mut self,
730        target: String,
731        runner: RemoteRunnerArc,
732    ) -> &mut Self {
733        self.remote_runners.insert(target, runner);
734        self
735    }
736
737    /// The staged remote transport for `target`, if any. `REMOTE`
738    /// interception bails when the target has no runner.
739    pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
740        self.remote_runners.get(target).cloned()
741    }
742
743    /// Legacy single-runner staging: registers under the empty target.
744    /// Prefer [`set_remote_runner_for_target`](Self::set_remote_runner_for_target).
745    pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
746        self.set_remote_runner_for_target(String::new(), runner)
747    }
748
749    /// Mark this run as executing inside a remote guest serve loop. In
750    /// guest mode, flagged `COPY --from-host` / `--to-host` steps are
751    /// transfer declarations already fulfilled by the session, so they
752    /// acknowledge as no-ops instead of re-copying. Never set on hosts:
753    /// the parser rejects flagged copies outside `REMOTE` bodies, and
754    /// hosts never execute `REMOTE` bodies.
755    pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
756        self.remote_guest = guest;
757        self
758    }
759
760    /// Whether flagged `COPY` transfer declarations acknowledge as no-ops.
761    pub fn is_remote_guest(&self) -> bool {
762        self.remote_guest
763    }
764
765    /// Stage the shared push-manifest sink for a guest serve loop.
766    /// Chainable. Executed flagged `COPY` steps append here; the serve
767    /// loop packs exactly these entries after the engine joins.
768    pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
769        self.push_manifest_sink = Some(sink);
770        self
771    }
772
773    /// The staged push-manifest sink, if any.
774    pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
775        self.push_manifest_sink.clone()
776    }
777
778    pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
779        let key = key.into();
780        self.inherit_env_removed.remove(&key);
781        self.inherit_env_overrides.insert(key, value.into());
782    }
783
784    pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
785        let key = key.into();
786        self.inherit_env_overrides.remove(&key);
787        self.inherit_env_removed.insert(key);
788    }
789
790    pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
791        self.inherit_env_overrides.get(key)
792    }
793
794    pub fn inherit_env_is_removed(&self, key: &str) -> bool {
795        self.inherit_env_removed.contains(key)
796    }
797
798    pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
799        &self.inherit_env_overrides
800    }
801
802    /// Ensure a handle is materialized for one binding site (see
803    /// [`PipeRegistry::ensure_handle`]). Main-flow bindings call this with
804    /// the per-step trigger; task bodies are pre-decided by the spawn-time
805    /// pin walk, making this a no-op there.
806    pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> DiagnosticResult<()> {
807        PipeRegistry::ensure_handle(handle, promote)
808    }
809
810    /// Snapshot of one handle for `INSPECT()` diagnostics.
811    pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
812        PipeRegistry::inspect_pipe(handle)
813    }
814
815    /// Non-destructive snapshot of a script handle's buffered bytes for
816    /// pipe-content assertions.
817    ///
818    /// Public so out-of-crate harnesses can assert on script-owned pipes
819    /// after a run completes, via the `PIPE` values in the returned
820    /// bindings. Only meaningful once writers detached (post-run);
821    /// unbound handles and OS pairs bail loudly.
822    pub fn peek_pipe_content(&self, handle: &PipeHandle) -> DiagnosticResult<Vec<u8>> {
823        PipeRegistry::peek_pipe_content(handle)
824    }
825
826    /// Pin a keeper slot on a script backend. `None` for OS-materialized
827    /// and unbound handles. Callers ensure the handle first so OS
828    /// promotion is honored and this never forces a backend into
829    /// existence.
830    pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> DiagnosticResult<Option<KeeperGuard>> {
831        PipeRegistry::pin_keeper(handle)
832    }
833
834    /// Resolve a stdin binding to a runnable handle plus the script
835    /// backend (for timeout-bounded bridge reads; `None` for OS pairs).
836    pub(super) fn resolve_stdin(
837        &self,
838        handle: &PipeHandle,
839        direct: bool,
840        promote: bool,
841    ) -> DiagnosticResult<(CommandStdin, Option<Arc<PipeInner>>)> {
842        PipeRegistry::resolve_stdin(handle, direct, promote)
843    }
844
845    /// Resolve a stdout binding to a runnable handle plus the script
846    /// backend (for the bridge's socket-EOF force-close).
847    pub(super) fn resolve_stdout(
848        &self,
849        handle: &PipeHandle,
850        direct: bool,
851        promote: bool,
852    ) -> DiagnosticResult<(StreamHandle, Option<Arc<PipeInner>>)> {
853        PipeRegistry::resolve_stdout(handle, direct, promote)
854    }
855
856    /// Resolve a stderr binding to a runnable handle.
857    pub(super) fn resolve_stderr(
858        &self,
859        handle: &PipeHandle,
860        direct: bool,
861        promote: bool,
862    ) -> DiagnosticResult<StreamHandle> {
863        PipeRegistry::resolve_stderr(handle, direct, promote)
864    }
865
866    pub fn stdin(&self) -> Option<SharedInput> {
867        self.stdin.clone()
868    }
869
870    pub fn stdout(&self) -> Option<SharedOutput> {
871        self.stdout.clone()
872    }
873
874    pub fn stderr(&self) -> Option<SharedOutput> {
875        self.stderr.clone().or_else(|| self.stdout.clone())
876    }
877}
878
879pub(super) fn assemble_default_io(
880    stdin: Option<SharedInput>,
881    stdout: Option<SharedOutput>,
882) -> ExecIo {
883    let mut io = ExecIo::new();
884    io.set_stdin(stdin);
885    io.set_stdout(stdout.clone());
886    io.set_stderr(stdout);
887    io
888}
889
890#[cfg(test)]
891mod tests {
892    use super::*;
893
894    /// One tee plus its hook channel, drop counter, and backing sink.
895    type TestTee = (
896        TeeWriter,
897        std::sync::mpsc::Receiver<StreamChunk>,
898        Arc<std::sync::atomic::AtomicUsize>,
899        Arc<Mutex<Vec<u8>>>,
900    );
901
902    fn tee_with_hook(stream: TeeStream, bound: usize) -> TestTee {
903        let vec: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::<u8>::new()));
904        let sink: SharedOutput = vec.clone();
905        let (tx, rx) = std::sync::mpsc::sync_channel(bound);
906        let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
907        let tee = TeeWriter {
908            inner: Some(sink),
909            stream,
910            windows: Arc::new(Mutex::new(HashMap::new())),
911            exact: Arc::new(Mutex::new(HashMap::new())),
912            hook: Some(StreamHook {
913                tx,
914                dropped: dropped.clone(),
915            }),
916        };
917        (tee, rx, dropped, vec)
918    }
919
920    #[test]
921    fn hook_receives_stderr_kind_and_sink_still_gets_bytes() {
922        let (mut tee, rx, dropped, sink) = tee_with_hook(TeeStream::Stderr, 8);
923        tee.write_all(b"oops\n").expect("write");
924        tee.flush().expect("flush");
925        let chunk = rx.try_recv().expect("one chunk streamed");
926        assert_eq!(chunk.kind, TeeStream::Stderr);
927        assert_eq!(chunk.bytes, b"oops\n");
928        assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 0);
929        let guard = sink.lock().expect("sink lock");
930        assert_eq!(guard.as_slice(), b"oops\n");
931    }
932
933    #[test]
934    fn full_channel_drops_and_counts_without_blocking() {
935        let (mut tee, rx, dropped, _sink) = tee_with_hook(TeeStream::Stdout, 1);
936        tee.write_all(b"first\n").expect("write");
937        tee.write_all(b"second\n")
938            .expect("write must not block on full");
939        assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 1);
940        let kept = rx.try_recv().expect("first chunk kept");
941        assert_eq!(kept.bytes, b"first\n");
942    }
943}