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