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}
244
245/// Shared append-only manifest of executed `--to-host` declarations.
246pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
247
248/// Shared handle to the transport behind `REMOTE` blocks. Staged here (not
249/// threaded through every `run_steps_*` signature) so existing callers keep
250/// compiling: `None` means remote execution is unavailable and every
251/// `REMOTE` step bails naming the NET plugin.
252pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
253
254/// Standard chunk size for all I/O handlers.
255pub const CHUNK_SIZE: usize = 8192;
256
257/// Minimum ring buffer capacity. Actual capacity scales with needle length.
258const MIN_RING_CAPACITY: usize = 1024;
259
260/// Sliding window for streaming pattern matching in stream assertions.
261/// Maintains a ring buffer and detects matches inline as chunks pass through.
262pub(crate) struct SlidingWindow {
263    pub(crate) needle: Vec<u8>,
264    ring: VecDeque<u8>,
265    pub matched: bool,
266}
267
268impl SlidingWindow {
269    pub fn new(needle: Vec<u8>) -> Self {
270        Self {
271            ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
272            needle,
273            matched: false,
274        }
275    }
276
277    pub fn push_chunk(&mut self, chunk: &[u8]) {
278        if self.matched {
279            return;
280        }
281        // Eviction limit scales with needle length, never below MIN_RING_CAPACITY
282        let limit = self.needle.len().max(MIN_RING_CAPACITY);
283        for &byte in chunk {
284            self.ring.push_back(byte);
285            if self.ring.len() > limit {
286                self.ring.pop_front();
287            }
288            self.check_match();
289        }
290    }
291
292    /// Replace needle without discarding ring history.
293    /// Re-evaluates current ring against updated needle.
294    pub fn update_needle(&mut self, new_needle: Vec<u8>) {
295        if self.matched {
296            return;
297        }
298        self.needle = new_needle;
299        self.check_match();
300    }
301
302    fn check_match(&mut self) {
303        if self.matched || self.ring.len() < self.needle.len() {
304            return;
305        }
306        let start = self.ring.len() - self.needle.len();
307        if self
308            .ring
309            .iter()
310            .skip(start)
311            .zip(self.needle.iter())
312            .all(|(a, b)| a == b)
313        {
314            self.matched = true;
315        }
316    }
317
318    /// Return the ring buffer contents for debugging.
319    pub fn ring_buffer(&self) -> Vec<u8> {
320        self.ring.iter().copied().collect()
321    }
322}
323
324#[derive(Clone)]
325pub(super) enum StreamHandle {
326    Stream(SharedOutput),
327    /// Live OS kernel pipe writer handed to one concurrent producer.
328    /// Only `RUN` consumes this directly; DSL commands never observe it
329    /// because `with_io` bridges OS entries to shared handles for them.
330    #[cfg(not(miri))]
331    Os(OsPipeWriter),
332}
333
334impl StreamHandle {
335    pub(super) fn to_stdout(&self) -> CommandStdout {
336        match self {
337            StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
338            #[cfg(not(miri))]
339            StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
340        }
341    }
342
343    pub(super) fn to_stderr(&self) -> CommandStderr {
344        match self {
345            StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
346            #[cfg(not(miri))]
347            StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
348        }
349    }
350}
351
352pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
353where
354    F: FnOnce(&mut dyn Write) -> Result<()>,
355{
356    match handle {
357        Some(StreamHandle::Stream(writer)) => {
358            if let Ok(mut guard) = writer.lock() {
359                op(&mut *guard)?;
360            }
361            Ok(())
362        }
363        // DSL commands never observe a live OS handle: `with_io` bridges
364        // OS entries to shared handles for them, and promotion only fires
365        // for single RUN bodies. This arm is defensive only.
366        #[cfg(not(miri))]
367        Some(StreamHandle::Os(_)) => {
368            bail!("cannot write DSL output to a live OS pipe")
369        }
370        // `None` inherits host stdout: only explicit `Stream` bindings
371        // reroute DSL output.
372        None => {
373            let mut stdout = io::stdout();
374            op(&mut stdout)
375        }
376    }
377}
378
379/// Slice-based byte adapter over pipe halves for host (`#[oxdock_func]`)
380///
381/// stateful functions. All byte movement goes through the standard traits
382/// on caller-owned buffers : `Read::read(&mut [u8])` and
383/// `Write::write(&[u8])` : so hosts can hand pipes directly to `serde_json`,
384/// `flate2`, `tar`, and friends with a single reused stack buffer and zero
385/// per-chunk allocation. `0` read means EOF exactly like `std::io`; never
386/// slurp a stream into one `Vec` (unbounded memory growth : stream it).
387/// `flush()` delegates to backend flush semantics, which for script pipes
388/// is a no-op that loses nothing: every `write()` wakes readers itself.
389///
390/// A host read blocks the calling task thread exactly like a DSL reader;
391/// EOF and half-close map identically to DSL consumers. Take-once applies
392/// like everywhere else: bridging an OS backend takes once, repeats bail.
393pub struct PipeStream {
394    reader: Option<SharedInput>,
395    writer: Option<SharedOutput>,
396}
397
398impl PipeStream {
399    /// Read-half adapter (e.g. over [`StepCtx::pipe_reader`](super::steps::StepCtx::pipe_reader)).
400    pub fn reader(reader: SharedInput) -> Self {
401        Self {
402            reader: Some(reader),
403            writer: None,
404        }
405    }
406
407    /// Write-half adapter (e.g. over [`StepCtx::pipe_writer`](super::steps::StepCtx::pipe_writer)).
408    pub fn writer(writer: SharedOutput) -> Self {
409        Self {
410            reader: None,
411            writer: Some(writer),
412        }
413    }
414
415    /// Both halves (e.g. a filter with separate in/out pipes).
416    pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
417        Self {
418            reader: Some(reader),
419            writer: Some(writer),
420        }
421    }
422}
423
424impl std::io::Read for PipeStream {
425    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
426        let Some(reader) = &self.reader else {
427            return Err(std::io::Error::new(
428                std::io::ErrorKind::NotConnected,
429                "pipe stream has no reader half",
430            ));
431        };
432        let mut guard = reader
433            .lock()
434            .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
435        guard.read(buf)
436    }
437}
438
439impl std::io::Write for PipeStream {
440    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
441        let Some(writer) = &self.writer else {
442            return Err(std::io::Error::new(
443                std::io::ErrorKind::NotConnected,
444                "pipe stream has no writer half",
445            ));
446        };
447        let mut guard = writer
448            .lock()
449            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
450        guard.write(buf)
451    }
452
453    fn flush(&mut self) -> std::io::Result<()> {
454        let Some(writer) = &self.writer else {
455            return Err(std::io::Error::new(
456                std::io::ErrorKind::NotConnected,
457                "pipe stream has no writer half",
458            ));
459        };
460        let mut guard = writer
461            .lock()
462            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
463        guard.flush()
464    }
465}
466
467/// Hard cap for `ASSERT_EQ stdout` exact accumulators, mirroring the
468/// `SpillBuffer` spill threshold: exact stream matching is a test-time
469/// opt-in, and unbounded trials must use pipe targets or harness captures.
470pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
471
472/// Cumulative stdout record for one execution generation backing
473/// `ASSERT_EQ stdout`. Unlike `SlidingWindow` nothing is ever evicted;
474/// once the cap is exceeded the entry latches `overflowed` and stops
475/// growing, and the asserting step reports it with remediation guidance.
476pub(crate) struct ExactCapture {
477    pub(crate) bytes: Vec<u8>,
478    pub(crate) overflowed: bool,
479}
480
481impl ExactCapture {
482    pub fn new() -> Self {
483        Self {
484            bytes: Vec::new(),
485            overflowed: false,
486        }
487    }
488
489    pub fn push_chunk(&mut self, chunk: &[u8]) {
490        if self.overflowed {
491            return;
492        }
493        if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
494            self.overflowed = true;
495            return;
496        }
497        self.bytes.extend_from_slice(chunk);
498    }
499}
500
501/// Which host stream a tee forwards to when no capture sink is configured.
502#[derive(Clone, Copy, PartialEq, Eq, Debug)]
503pub enum TeeStream {
504    Stdout,
505    Stderr,
506}
507
508/// One live output fragment: the bytes from a single tee write plus
509/// which host stream they belong to. Carried from the synchronous
510/// execution threads to the MCP forwarder over a bounded channel.
511#[derive(Clone, Debug)]
512pub struct StreamChunk {
513    /// Which host stream produced these bytes.
514    pub kind: TeeStream,
515    /// Raw bytes as written. Decoded lossily at the forward edge.
516    pub bytes: Vec<u8>,
517}
518
519/// Live-stream tap for a tool call. Cloned into every per-call tee:
520/// each default-routed write `try_send`s one chunk. Bounded channel,
521/// so a chatty tool cannot grow the queue without bound; overflow
522/// chunks are dropped and counted. Explicit `WITH_IO` redirections
523/// bypass the tee entirely, so redirected bytes never stream.
524#[derive(Clone, Debug)]
525pub struct StreamHook {
526    /// Bounded egress. `try_send` only: never blocks script execution.
527    pub tx: std::sync::mpsc::SyncSender<StreamChunk>,
528    /// Chunks dropped on a full channel. Read after the call for the
529    /// transit note; lossy transit never affects the tail buffers.
530    pub dropped: std::sync::Arc<std::sync::atomic::AtomicUsize>,
531}
532
533/// Wraps the configured stdout sink so every byte written to it is also
534/// pushed to all registered SlidingWindow observers for stream assertions.
535/// When no sink is configured (`inner` is `None`) bytes are forwarded to
536/// real stdout so interactive CLI output still reaches the terminal.
537struct TeeWriter {
538    inner: Option<SharedOutput>,
539    stream: TeeStream,
540    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
541    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
542    hook: Option<StreamHook>,
543}
544
545impl Write for TeeWriter {
546    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
547        // Forward to downstream (streaming)
548        match &self.inner {
549            Some(inner) => {
550                let mut guard = inner
551                    .lock()
552                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
553                guard.write_all(buf)?;
554            }
555            None => match self.stream {
556                TeeStream::Stdout => io::stdout().write_all(buf)?,
557                TeeStream::Stderr => io::stderr().write_all(buf)?,
558            },
559        }
560        // Push to ALL registered assertion windows (O(1) per byte per window)
561        if let Ok(mut windows) = self.windows.lock() {
562            for window in windows.values_mut() {
563                window.push_chunk(buf);
564            }
565        }
566        if let Ok(mut exact) = self.exact.lock() {
567            for capture in exact.values_mut() {
568                capture.push_chunk(buf);
569            }
570        }
571        // Live tap: default-routed bytes stream to the MCP forwarder.
572        // `try_send` only, so a slow client never blocks execution;
573        // overflow drops and counts. Redirected bytes never reach this
574        // tee, so explicit `WITH_IO` stays silent by construction.
575        if let Some(hook) = &self.hook {
576            let chunk = StreamChunk {
577                kind: self.stream,
578                bytes: buf.to_vec(),
579            };
580            if hook.tx.try_send(chunk).is_err() {
581                hook.dropped
582                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
583            }
584        }
585        Ok(buf.len())
586    }
587
588    fn flush(&mut self) -> io::Result<()> {
589        match &self.inner {
590            Some(inner) => {
591                let mut guard = inner
592                    .lock()
593                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
594                guard.flush()?;
595            }
596            None => match self.stream {
597                TeeStream::Stdout => io::stdout().flush()?,
598                TeeStream::Stderr => io::stderr().flush()?,
599            },
600        }
601        Ok(())
602    }
603}
604
605/// Installs the tee around `sink` (or real stdout when absent).
606pub(crate) fn teed_stdout(
607    sink: Option<SharedOutput>,
608    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
609    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
610    hook: Option<StreamHook>,
611) -> SharedOutput {
612    Arc::new(Mutex::new(TeeWriter {
613        inner: sink,
614        stream: TeeStream::Stdout,
615        windows,
616        exact,
617        hook,
618    }))
619}
620
621/// Installs the tee around `sink` (or real stderr when absent) for
622/// `ASSERT_CONTAINS stderr` substring observers. Exact matching is not
623/// offered over stderr; use pipe targets or harness captures instead.
624pub(crate) fn teed_stderr(
625    sink: Option<SharedOutput>,
626    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
627    hook: Option<StreamHook>,
628) -> SharedOutput {
629    Arc::new(Mutex::new(TeeWriter {
630        inner: sink,
631        stream: TeeStream::Stderr,
632        windows,
633        exact: Arc::new(Mutex::new(HashMap::new())),
634        hook,
635    }))
636}
637
638impl ExecIo {
639    pub fn new() -> Self {
640        Self::default()
641    }
642
643    pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
644        self.stdin = stdin;
645    }
646
647    pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
648        self.stdout = stdout.clone();
649        if self.stderr.is_none() {
650            self.stderr = stdout;
651        }
652    }
653
654    pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
655        self.stderr = stderr;
656    }
657
658    /// Stage this run's pump-worker count. Chainable.
659    pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
660        self.worker_counter = counter;
661        self
662    }
663
664    /// This run's shared pump-worker count.
665    pub fn worker_counter(&self) -> Arc<AtomicU64> {
666        Arc::clone(&self.worker_counter)
667    }
668
669    /// Stage the `INTERPRETER()` path for this run. Chainable. Embedding
670    /// hosts whose engine runs in-process (no CLI binary as the current
671    /// executable) point this at their CLI so child reinvocation leaves
672    /// the process boundary intact.
673    pub fn set_interpreter<S: Into<String>>(&mut self, path: S) -> &mut Self {
674        self.interpreter_override = Some(path.into());
675        self
676    }
677
678    /// The staged interpreter path, if any. `None` selects the
679    /// `current_exe` default.
680    pub fn interpreter_override(&self) -> Option<String> {
681        self.interpreter_override.clone()
682    }
683
684    /// Stage the transport behind one `REMOTE` target. Chainable; the NET
685    /// plugin registers one session per inventory target at CLI startup
686    /// and tests stage mocks. Registration is inert (no process spawns
687    /// until a block entry runs).
688    pub fn set_remote_runner_for_target(
689        &mut self,
690        target: String,
691        runner: RemoteRunnerArc,
692    ) -> &mut Self {
693        self.remote_runners.insert(target, runner);
694        self
695    }
696
697    /// The staged remote transport for `target`, if any. `REMOTE`
698    /// interception bails when the target has no runner.
699    pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
700        self.remote_runners.get(target).cloned()
701    }
702
703    /// Legacy single-runner staging: registers under the empty target.
704    /// Prefer [`set_remote_runner_for_target`](Self::set_remote_runner_for_target).
705    pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
706        self.set_remote_runner_for_target(String::new(), runner)
707    }
708
709    /// Mark this run as executing inside a remote guest serve loop. In
710    /// guest mode, flagged `COPY --from-host` / `--to-host` steps are
711    /// transfer declarations already fulfilled by the session, so they
712    /// acknowledge as no-ops instead of re-copying. Never set on hosts:
713    /// the parser rejects flagged copies outside `REMOTE` bodies, and
714    /// hosts never execute `REMOTE` bodies.
715    pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
716        self.remote_guest = guest;
717        self
718    }
719
720    /// Whether flagged `COPY` transfer declarations acknowledge as no-ops.
721    pub fn is_remote_guest(&self) -> bool {
722        self.remote_guest
723    }
724
725    /// Stage the shared push-manifest sink for a guest serve loop.
726    /// Chainable. Executed flagged `COPY` steps append here; the serve
727    /// loop packs exactly these entries after the engine joins.
728    pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
729        self.push_manifest_sink = Some(sink);
730        self
731    }
732
733    /// The staged push-manifest sink, if any.
734    pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
735        self.push_manifest_sink.clone()
736    }
737
738    pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
739        let key = key.into();
740        self.inherit_env_removed.remove(&key);
741        self.inherit_env_overrides.insert(key, value.into());
742    }
743
744    pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
745        let key = key.into();
746        self.inherit_env_overrides.remove(&key);
747        self.inherit_env_removed.insert(key);
748    }
749
750    pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
751        self.inherit_env_overrides.get(key)
752    }
753
754    pub fn inherit_env_is_removed(&self, key: &str) -> bool {
755        self.inherit_env_removed.contains(key)
756    }
757
758    pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
759        &self.inherit_env_overrides
760    }
761
762    /// Ensure a handle is materialized for one binding site (see
763    /// [`PipeRegistry::ensure_handle`]). Main-flow bindings call this with
764    /// the per-step trigger; task bodies are pre-decided by the spawn-time
765    /// pin walk, making this a no-op there.
766    pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
767        PipeRegistry::ensure_handle(handle, promote)
768    }
769
770    /// Snapshot of one handle for `INSPECT()` diagnostics.
771    pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
772        PipeRegistry::inspect_pipe(handle)
773    }
774
775    /// Non-destructive snapshot of a script handle's buffered bytes for
776    /// pipe-content assertions.
777    ///
778    /// Public so out-of-crate harnesses can assert on script-owned pipes
779    /// after a run completes, via the `PIPE` values in the returned
780    /// bindings. Only meaningful once writers detached (post-run);
781    /// unbound handles and OS pairs bail loudly.
782    pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
783        PipeRegistry::peek_pipe_content(handle)
784    }
785
786    /// Pin a keeper slot on a script backend. `None` for OS-materialized
787    /// and unbound handles. Callers ensure the handle first so OS
788    /// promotion is honored and this never forces a backend into
789    /// existence.
790    pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
791        PipeRegistry::pin_keeper(handle)
792    }
793
794    /// Resolve a stdin binding to a runnable handle plus the script
795    /// backend (for timeout-bounded bridge reads; `None` for OS pairs).
796    pub(super) fn resolve_stdin(
797        &self,
798        handle: &PipeHandle,
799        direct: bool,
800        promote: bool,
801    ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
802        PipeRegistry::resolve_stdin(handle, direct, promote)
803    }
804
805    /// Resolve a stdout binding to a runnable handle plus the script
806    /// backend (for the bridge's socket-EOF force-close).
807    pub(super) fn resolve_stdout(
808        &self,
809        handle: &PipeHandle,
810        direct: bool,
811        promote: bool,
812    ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
813        PipeRegistry::resolve_stdout(handle, direct, promote)
814    }
815
816    /// Resolve a stderr binding to a runnable handle.
817    pub(super) fn resolve_stderr(
818        &self,
819        handle: &PipeHandle,
820        direct: bool,
821        promote: bool,
822    ) -> Result<StreamHandle> {
823        PipeRegistry::resolve_stderr(handle, direct, promote)
824    }
825
826    pub fn stdin(&self) -> Option<SharedInput> {
827        self.stdin.clone()
828    }
829
830    pub fn stdout(&self) -> Option<SharedOutput> {
831        self.stdout.clone()
832    }
833
834    pub fn stderr(&self) -> Option<SharedOutput> {
835        self.stderr.clone().or_else(|| self.stdout.clone())
836    }
837}
838
839pub(super) fn assemble_default_io(
840    stdin: Option<SharedInput>,
841    stdout: Option<SharedOutput>,
842) -> ExecIo {
843    let mut io = ExecIo::new();
844    io.set_stdin(stdin);
845    io.set_stdout(stdout.clone());
846    io.set_stderr(stdout);
847    io
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    /// One tee plus its hook channel, drop counter, and backing sink.
855    type TestTee = (
856        TeeWriter,
857        std::sync::mpsc::Receiver<StreamChunk>,
858        Arc<std::sync::atomic::AtomicUsize>,
859        Arc<Mutex<Vec<u8>>>,
860    );
861
862    fn tee_with_hook(stream: TeeStream, bound: usize) -> TestTee {
863        let vec: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::<u8>::new()));
864        let sink: SharedOutput = vec.clone();
865        let (tx, rx) = std::sync::mpsc::sync_channel(bound);
866        let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
867        let tee = TeeWriter {
868            inner: Some(sink),
869            stream,
870            windows: Arc::new(Mutex::new(HashMap::new())),
871            exact: Arc::new(Mutex::new(HashMap::new())),
872            hook: Some(StreamHook {
873                tx,
874                dropped: dropped.clone(),
875            }),
876        };
877        (tee, rx, dropped, vec)
878    }
879
880    #[test]
881    fn hook_receives_stderr_kind_and_sink_still_gets_bytes() {
882        let (mut tee, rx, dropped, sink) = tee_with_hook(TeeStream::Stderr, 8);
883        tee.write_all(b"oops\n").expect("write");
884        tee.flush().expect("flush");
885        let chunk = rx.try_recv().expect("one chunk streamed");
886        assert_eq!(chunk.kind, TeeStream::Stderr);
887        assert_eq!(chunk.bytes, b"oops\n");
888        assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 0);
889        let guard = sink.lock().expect("sink lock");
890        assert_eq!(guard.as_slice(), b"oops\n");
891    }
892
893    #[test]
894    fn full_channel_drops_and_counts_without_blocking() {
895        let (mut tee, rx, dropped, _sink) = tee_with_hook(TeeStream::Stdout, 1);
896        tee.write_all(b"first\n").expect("write");
897        tee.write_all(b"second\n")
898            .expect("write must not block on full");
899        assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 1);
900        let kept = rx.try_recv().expect("first chunk kept");
901        assert_eq!(kept.bytes, b"first\n");
902    }
903}