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