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};
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/// Handle-scoped pipe resolution. No central index exists: every method
17/// below takes the `PIPE` value's backend cell, materializing it on first
18/// binding (first-binding-wins under the cell lock) and adapting later
19/// bindings through the existing machinery. The `ExecIo` receiver carries
20/// no pipe state; methods live here (rather than as free functions) so
21/// call sites keep their `cx.state.io.*` shape.
22#[derive(Clone, Default)]
23pub(super) struct PipeRegistry;
24
25/// Loud take-twice error for OS handles: a second consumer or producer on
26/// one end can never steal the descriptor, and (unlike the old recycling
27/// behavior) never silently receives a fresh pair either : the remedy is a
28/// fresh declaration. No rebind rule exists by design: no rule can tell
29/// sequential loop reuse apart from concurrent fan-in sharing.
30#[cfg(not(miri))]
31fn spent_handle(idx: usize) -> anyhow::Error {
32    anyhow::anyhow!(
33        "step {}: OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session",
34        idx + 1,
35    )
36}
37
38impl PipeRegistry {
39    /// First-binding-wins materialization for one binding site: an unbound
40    /// handle decides its kind from `promote` (the caller supplies full
41    /// usage context); a decided handle is returned unchanged. Callers
42    /// adapt mismatches through resolution below, never here.
43    pub(super) fn ensure_handle(handle: &PipeHandle, promote: bool) -> Result<()> {
44        materialize(handle, promote)?;
45        Ok(())
46    }
47
48    /// Non-destructive snapshot of a script handle's buffered bytes for
49    /// pipe-content assertions. Delegates to the backend without creating:
50    /// unbound handles and OS pairs bail loudly instead of yielding empty
51    /// content.
52    ///
53    /// Public so out-of-crate harnesses can assert on script-owned pipes
54    /// after a run completes, via the `PIPE` values in the returned
55    /// bindings. Only meaningful once writers detached (post-run).
56    pub fn peek_pipe_content(handle: &PipeHandle) -> Result<Vec<u8>> {
57        peek_handle(handle)
58    }
59
60    /// Snapshot one handle for `INSPECT()` diagnostics.
61    pub(super) fn inspect_pipe(handle: &PipeHandle) -> PipeInfo {
62        inspect_handle(handle)
63    }
64
65    /// Pin a keeper slot on a script backend so transient writer churn can
66    /// never observe zero writers. Returns `None` for OS-materialized and
67    /// unbound handles, which need no pin. Callers ensure the handle
68    /// first so OS promotion is honored and this never forces a script
69    /// backend into existence.
70    pub(super) fn pin_keeper(handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
71        Ok(script_backend(handle).map(KeeperGuard::new))
72    }
73
74    /// Resolve a stdin binding against a decided handle. Script backends
75    /// hand out a shared reader (plus the backend for timeout-bounded
76    /// bridge reads); OS pairs hand the take-once reader to `RUN` directly
77    /// and bridge it to a shared handle for DSL commands. A second take
78    /// on one end bails loudly with the fresh-declaration remedy instead
79    /// of stealing the descriptor.
80    pub(super) fn resolve_stdin(
81        idx: usize,
82        handle: &PipeHandle,
83        direct: bool,
84        promote: bool,
85    ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
86        // `idx` and `direct` serve only the OS-pipe arms below, which are
87        // compiled out under Miri.
88        let _ = idx;
89        let _ = direct;
90        match materialize(handle, promote)? {
91            Materialized::Script(backend) => {
92                Ok((CommandStdin::Stream(backend.reader_handle()), Some(backend)))
93            }
94            #[cfg(not(miri))]
95            Materialized::Os(entry) => {
96                if direct {
97                    return Ok((CommandStdin::OsPipe(entry.reader.clone()), None));
98                }
99                let owned = entry.reader.take().map_err(|_| spent_handle(idx))?;
100                Ok((
101                    CommandStdin::Stream(Arc::new(std::sync::Mutex::new(owned))),
102                    None,
103                ))
104            }
105        }
106    }
107
108    /// Resolve a stdout binding. Mirrors
109    /// [`PipeRegistry::resolve_stdin`] with `StreamHandle` outputs so
110    /// `RUN` keeps zero copy `Stdio` handoff, plus the script backend for
111    /// the bridge's socket-EOF force-close.
112    pub(super) fn resolve_stdout(
113        idx: usize,
114        handle: &PipeHandle,
115        direct: bool,
116        promote: bool,
117    ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
118        // `idx` and `direct` serve only the OS-pipe arms below, which are
119        // compiled out under Miri.
120        let _ = idx;
121        let _ = direct;
122        match materialize(handle, promote)? {
123            Materialized::Script(backend) => {
124                Ok((StreamHandle::Stream(backend.writer_handle()), Some(backend)))
125            }
126            #[cfg(not(miri))]
127            Materialized::Os(entry) => {
128                if direct {
129                    return Ok((StreamHandle::Os(entry.writer.clone()), None));
130                }
131                let owned = entry.writer.take().map_err(|_| spent_handle(idx))?;
132                Ok((
133                    StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))),
134                    None,
135                ))
136            }
137        }
138    }
139
140    /// Resolve a stderr binding. Mirrors
141    /// [`PipeRegistry::resolve_stdout`]: `RUN` keeps zero copy handoff,
142    /// DSL commands get a bridged shared handle. Binding `stdout` and
143    /// `stderr` to one live OS handle takes the same slot twice, so the
144    /// second take bails deterministically; merge in shell via `2>&1`
145    /// instead.
146    pub(super) fn resolve_stderr(
147        idx: usize,
148        handle: &PipeHandle,
149        direct: bool,
150        promote: bool,
151    ) -> Result<StreamHandle> {
152        // `idx` and `direct` serve only the OS-pipe arms below, which are
153        // compiled out under Miri.
154        let _ = idx;
155        let _ = direct;
156        match materialize(handle, promote)? {
157            Materialized::Script(backend) => Ok(StreamHandle::Stream(backend.writer_handle())),
158            #[cfg(not(miri))]
159            Materialized::Os(entry) => {
160                if direct {
161                    return Ok(StreamHandle::Os(entry.writer.clone()));
162                }
163                let owned = entry.writer.take().map_err(|_| spent_handle(idx))?;
164                Ok(StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))))
165            }
166        }
167    }
168}
169
170#[derive(Clone, Default)]
171pub struct ExecIo {
172    stdin: Option<SharedInput>,
173    stdout: Option<SharedOutput>,
174    stderr: Option<SharedOutput>,
175    inherit_env_overrides: HashMap<String, String>,
176    inherit_env_removed: HashSet<String>,
177    remote_runners: HashMap<String, RemoteRunnerArc>,
178    remote_guest: bool,
179    /// Shared sink for the guest execution manifest: when staged, executed
180    /// flagged `COPY` steps append their evaluated pairs here as well as
181    /// to state, so a serve loop holding only `ExecIo` can pack exactly
182    /// what ran. `None` on hosts (nothing records).
183    push_manifest_sink: Option<PushManifestSink>,
184}
185
186/// Shared append-only manifest of executed `--to-host` declarations.
187pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
188
189/// Shared handle to the transport behind `REMOTE` blocks. Staged here (not
190/// threaded through every `run_steps_*` signature) so existing callers keep
191/// compiling: `None` means remote execution is unavailable and every
192/// `REMOTE` step bails naming the NET plugin.
193pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
194
195/// Standard chunk size for all I/O handlers.
196pub const CHUNK_SIZE: usize = 8192;
197
198/// Minimum ring buffer capacity. Actual capacity scales with needle length.
199const MIN_RING_CAPACITY: usize = 1024;
200
201/// Sliding window for streaming pattern matching in stream assertions.
202/// Maintains a ring buffer and detects matches inline as chunks pass through.
203pub(crate) struct SlidingWindow {
204    pub(crate) needle: Vec<u8>,
205    ring: VecDeque<u8>,
206    pub matched: bool,
207}
208
209impl SlidingWindow {
210    pub fn new(needle: Vec<u8>) -> Self {
211        Self {
212            ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
213            needle,
214            matched: false,
215        }
216    }
217
218    pub fn push_chunk(&mut self, chunk: &[u8]) {
219        if self.matched {
220            return;
221        }
222        // Eviction limit scales with needle length, never below MIN_RING_CAPACITY
223        let limit = self.needle.len().max(MIN_RING_CAPACITY);
224        for &byte in chunk {
225            self.ring.push_back(byte);
226            if self.ring.len() > limit {
227                self.ring.pop_front();
228            }
229            self.check_match();
230        }
231    }
232
233    /// Replace needle without discarding ring history.
234    /// Re-evaluates current ring against updated needle.
235    pub fn update_needle(&mut self, new_needle: Vec<u8>) {
236        if self.matched {
237            return;
238        }
239        self.needle = new_needle;
240        self.check_match();
241    }
242
243    fn check_match(&mut self) {
244        if self.matched || self.ring.len() < self.needle.len() {
245            return;
246        }
247        let start = self.ring.len() - self.needle.len();
248        if self
249            .ring
250            .iter()
251            .skip(start)
252            .zip(self.needle.iter())
253            .all(|(a, b)| a == b)
254        {
255            self.matched = true;
256        }
257    }
258
259    /// Return the ring buffer contents for debugging.
260    pub fn ring_buffer(&self) -> Vec<u8> {
261        self.ring.iter().copied().collect()
262    }
263}
264
265#[derive(Clone)]
266pub(super) enum StreamHandle {
267    Stream(SharedOutput),
268    /// Live OS kernel pipe writer handed to one concurrent producer.
269    /// Only `RUN` consumes this directly; DSL commands never observe it
270    /// because `with_io` bridges OS entries to shared handles for them.
271    #[cfg(not(miri))]
272    Os(OsPipeWriter),
273}
274
275impl StreamHandle {
276    pub(super) fn to_stdout(&self) -> CommandStdout {
277        match self {
278            StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
279            #[cfg(not(miri))]
280            StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
281        }
282    }
283
284    pub(super) fn to_stderr(&self) -> CommandStderr {
285        match self {
286            StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
287            #[cfg(not(miri))]
288            StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
289        }
290    }
291}
292
293pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
294where
295    F: FnOnce(&mut dyn Write) -> Result<()>,
296{
297    match handle {
298        Some(StreamHandle::Stream(writer)) => {
299            if let Ok(mut guard) = writer.lock() {
300                op(&mut *guard)?;
301            }
302            Ok(())
303        }
304        // DSL commands never observe a live OS handle: `with_io` bridges
305        // OS entries to shared handles for them, and promotion only fires
306        // for single RUN bodies. This arm is defensive only.
307        #[cfg(not(miri))]
308        Some(StreamHandle::Os(_)) => {
309            bail!("cannot write DSL output to a live OS pipe")
310        }
311        // `None` inherits host stdout: only explicit `Stream` bindings
312        // reroute DSL output.
313        None => {
314            let mut stdout = io::stdout();
315            op(&mut stdout)
316        }
317    }
318}
319
320/// Slice-based byte adapter over pipe halves for host (`#[oxdock_func]`)
321///
322/// stateful functions. All byte movement goes through the standard traits
323/// on caller-owned buffers : `Read::read(&mut [u8])` and
324/// `Write::write(&[u8])` : so hosts can hand pipes directly to `serde_json`,
325/// `flate2`, `tar`, and friends with a single reused stack buffer and zero
326/// per-chunk allocation. `0` read means EOF exactly like `std::io`; never
327/// slurp a stream into one `Vec` (unbounded memory growth : stream it).
328/// `flush()` delegates to backend flush semantics, which for script pipes
329/// is a no-op that loses nothing: every `write()` wakes readers itself.
330///
331/// A host read blocks the calling task thread exactly like a DSL reader;
332/// EOF and half-close map identically to DSL consumers. Take-once applies
333/// like everywhere else: bridging an OS backend takes once, repeats bail.
334pub struct PipeStream {
335    reader: Option<SharedInput>,
336    writer: Option<SharedOutput>,
337}
338
339impl PipeStream {
340    /// Read-half adapter (e.g. over [`StepCtx::pipe_reader`](super::steps::StepCtx::pipe_reader)).
341    pub fn reader(reader: SharedInput) -> Self {
342        Self {
343            reader: Some(reader),
344            writer: None,
345        }
346    }
347
348    /// Write-half adapter (e.g. over [`StepCtx::pipe_writer`](super::steps::StepCtx::pipe_writer)).
349    pub fn writer(writer: SharedOutput) -> Self {
350        Self {
351            reader: None,
352            writer: Some(writer),
353        }
354    }
355
356    /// Both halves (e.g. a filter with separate in/out pipes).
357    pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
358        Self {
359            reader: Some(reader),
360            writer: Some(writer),
361        }
362    }
363}
364
365impl std::io::Read for PipeStream {
366    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
367        let Some(reader) = &self.reader else {
368            return Err(std::io::Error::new(
369                std::io::ErrorKind::NotConnected,
370                "pipe stream has no reader half",
371            ));
372        };
373        let mut guard = reader
374            .lock()
375            .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
376        guard.read(buf)
377    }
378}
379
380impl std::io::Write for PipeStream {
381    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
382        let Some(writer) = &self.writer else {
383            return Err(std::io::Error::new(
384                std::io::ErrorKind::NotConnected,
385                "pipe stream has no writer half",
386            ));
387        };
388        let mut guard = writer
389            .lock()
390            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
391        guard.write(buf)
392    }
393
394    fn flush(&mut self) -> std::io::Result<()> {
395        let Some(writer) = &self.writer else {
396            return Err(std::io::Error::new(
397                std::io::ErrorKind::NotConnected,
398                "pipe stream has no writer half",
399            ));
400        };
401        let mut guard = writer
402            .lock()
403            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
404        guard.flush()
405    }
406}
407
408/// Hard cap for `ASSERT_EQ stdout` exact accumulators, mirroring the
409/// `SpillBuffer` spill threshold: exact stream matching is a test-time
410/// opt-in, and unbounded trials must use pipe targets or harness captures.
411pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
412
413/// Cumulative stdout record for one execution generation backing
414/// `ASSERT_EQ stdout`. Unlike `SlidingWindow` nothing is ever evicted;
415/// once the cap is exceeded the entry latches `overflowed` and stops
416/// growing, and the asserting step reports it with remediation guidance.
417pub(crate) struct ExactCapture {
418    pub(crate) bytes: Vec<u8>,
419    pub(crate) overflowed: bool,
420}
421
422impl ExactCapture {
423    pub fn new() -> Self {
424        Self {
425            bytes: Vec::new(),
426            overflowed: false,
427        }
428    }
429
430    pub fn push_chunk(&mut self, chunk: &[u8]) {
431        if self.overflowed {
432            return;
433        }
434        if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
435            self.overflowed = true;
436            return;
437        }
438        self.bytes.extend_from_slice(chunk);
439    }
440}
441
442/// Which host stream a tee forwards to when no capture sink is configured.
443#[derive(Clone, Copy)]
444enum TeeStream {
445    Stdout,
446    Stderr,
447}
448
449/// Wraps the configured stdout sink so every byte written to it is also
450/// pushed to all registered SlidingWindow observers for stream assertions.
451/// When no sink is configured (`inner` is `None`) bytes are forwarded to
452/// real stdout so interactive CLI output still reaches the terminal.
453struct TeeWriter {
454    inner: Option<SharedOutput>,
455    stream: TeeStream,
456    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
457    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
458}
459
460impl Write for TeeWriter {
461    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
462        // Forward to downstream (streaming)
463        match &self.inner {
464            Some(inner) => {
465                let mut guard = inner
466                    .lock()
467                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
468                guard.write_all(buf)?;
469            }
470            None => match self.stream {
471                TeeStream::Stdout => io::stdout().write_all(buf)?,
472                TeeStream::Stderr => io::stderr().write_all(buf)?,
473            },
474        }
475        // Push to ALL registered assertion windows (O(1) per byte per window)
476        if let Ok(mut windows) = self.windows.lock() {
477            for window in windows.values_mut() {
478                window.push_chunk(buf);
479            }
480        }
481        if let Ok(mut exact) = self.exact.lock() {
482            for capture in exact.values_mut() {
483                capture.push_chunk(buf);
484            }
485        }
486        Ok(buf.len())
487    }
488
489    fn flush(&mut self) -> io::Result<()> {
490        match &self.inner {
491            Some(inner) => {
492                let mut guard = inner
493                    .lock()
494                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
495                guard.flush()?;
496            }
497            None => match self.stream {
498                TeeStream::Stdout => io::stdout().flush()?,
499                TeeStream::Stderr => io::stderr().flush()?,
500            },
501        }
502        Ok(())
503    }
504}
505
506/// Installs the tee around `sink` (or real stdout when absent).
507pub(crate) fn teed_stdout(
508    sink: Option<SharedOutput>,
509    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
510    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
511) -> SharedOutput {
512    Arc::new(Mutex::new(TeeWriter {
513        inner: sink,
514        stream: TeeStream::Stdout,
515        windows,
516        exact,
517    }))
518}
519
520/// Installs the tee around `sink` (or real stderr when absent) for
521/// `ASSERT_CONTAINS stderr` substring observers. Exact matching is not
522/// offered over stderr; use pipe targets or harness captures for that.
523pub(crate) fn teed_stderr(
524    sink: Option<SharedOutput>,
525    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
526) -> SharedOutput {
527    Arc::new(Mutex::new(TeeWriter {
528        inner: sink,
529        stream: TeeStream::Stderr,
530        windows,
531        exact: Arc::new(Mutex::new(HashMap::new())),
532    }))
533}
534
535impl ExecIo {
536    pub fn new() -> Self {
537        Self::default()
538    }
539
540    pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
541        self.stdin = stdin;
542    }
543
544    pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
545        self.stdout = stdout.clone();
546        if self.stderr.is_none() {
547            self.stderr = stdout;
548        }
549    }
550
551    pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
552        self.stderr = stderr;
553    }
554
555    /// Stage the transport behind one `REMOTE` target. Chainable; the NET
556    /// plugin registers one session per inventory target at CLI startup
557    /// and tests stage mocks. Registration is inert (no process spawns
558    /// until a block entry runs).
559    pub fn set_remote_runner_for_target(
560        &mut self,
561        target: String,
562        runner: RemoteRunnerArc,
563    ) -> &mut Self {
564        self.remote_runners.insert(target, runner);
565        self
566    }
567
568    /// The staged remote transport for `target`, if any. `REMOTE`
569    /// interception bails when the target has no runner.
570    pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
571        self.remote_runners.get(target).cloned()
572    }
573
574    /// Legacy single-runner staging: registers under the empty target.
575    /// Prefer [`set_remote_runner_for_target`](Self::set_remote_runner_for_target).
576    pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
577        self.set_remote_runner_for_target(String::new(), runner)
578    }
579
580    /// Mark this run as executing inside a remote guest serve loop. In
581    /// guest mode, flagged `COPY --from-host` / `--to-host` steps are
582    /// transfer declarations already fulfilled by the session, so they
583    /// acknowledge as no-ops instead of re-copying. Never set on hosts:
584    /// the parser rejects flagged copies outside `REMOTE` bodies, and
585    /// hosts never execute `REMOTE` bodies.
586    pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
587        self.remote_guest = guest;
588        self
589    }
590
591    /// Whether flagged `COPY` transfer declarations acknowledge as no-ops.
592    pub fn is_remote_guest(&self) -> bool {
593        self.remote_guest
594    }
595
596    /// Stage the shared push-manifest sink for a guest serve loop.
597    /// Chainable. Executed flagged `COPY` steps append here; the serve
598    /// loop packs exactly these entries after the engine joins.
599    pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
600        self.push_manifest_sink = Some(sink);
601        self
602    }
603
604    /// The staged push-manifest sink, if any.
605    pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
606        self.push_manifest_sink.clone()
607    }
608
609    pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
610        let key = key.into();
611        self.inherit_env_removed.remove(&key);
612        self.inherit_env_overrides.insert(key, value.into());
613    }
614
615    pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
616        let key = key.into();
617        self.inherit_env_overrides.remove(&key);
618        self.inherit_env_removed.insert(key);
619    }
620
621    pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
622        self.inherit_env_overrides.get(key)
623    }
624
625    pub fn inherit_env_is_removed(&self, key: &str) -> bool {
626        self.inherit_env_removed.contains(key)
627    }
628
629    pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
630        &self.inherit_env_overrides
631    }
632
633    /// Ensure a handle is materialized for one binding site (see
634    /// [`PipeRegistry::ensure_handle`]). Main-flow bindings call this with
635    /// the per-step trigger; task bodies are pre-decided by the spawn-time
636    /// pin walk, making this a no-op there.
637    pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
638        PipeRegistry::ensure_handle(handle, promote)
639    }
640
641    /// Snapshot of one handle for `INSPECT()` diagnostics.
642    pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
643        PipeRegistry::inspect_pipe(handle)
644    }
645
646    /// Non-destructive snapshot of a script handle's buffered bytes for
647    /// pipe-content assertions.
648    ///
649    /// Public so out-of-crate harnesses can assert on script-owned pipes
650    /// after a run completes, via the `PIPE` values in the returned
651    /// bindings. Only meaningful once writers detached (post-run);
652    /// unbound handles and OS pairs bail loudly.
653    pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
654        PipeRegistry::peek_pipe_content(handle)
655    }
656
657    /// Pin a keeper slot on a script backend. `None` for OS-materialized
658    /// and unbound handles. Callers ensure the handle first so OS
659    /// promotion is honored and this never forces a backend into
660    /// existence.
661    pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
662        PipeRegistry::pin_keeper(handle)
663    }
664
665    /// Resolve a stdin binding to a runnable handle plus the script
666    /// backend (for timeout-bounded bridge reads; `None` for OS pairs).
667    pub(super) fn resolve_stdin(
668        &self,
669        idx: usize,
670        handle: &PipeHandle,
671        direct: bool,
672        promote: bool,
673    ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
674        PipeRegistry::resolve_stdin(idx, handle, direct, promote)
675    }
676
677    /// Resolve a stdout binding to a runnable handle plus the script
678    /// backend (for the bridge's socket-EOF force-close).
679    pub(super) fn resolve_stdout(
680        &self,
681        idx: usize,
682        handle: &PipeHandle,
683        direct: bool,
684        promote: bool,
685    ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
686        PipeRegistry::resolve_stdout(idx, handle, direct, promote)
687    }
688
689    /// Resolve a stderr binding to a runnable handle.
690    pub(super) fn resolve_stderr(
691        &self,
692        idx: usize,
693        handle: &PipeHandle,
694        direct: bool,
695        promote: bool,
696    ) -> Result<StreamHandle> {
697        PipeRegistry::resolve_stderr(idx, handle, direct, promote)
698    }
699
700    pub fn stdin(&self) -> Option<SharedInput> {
701        self.stdin.clone()
702    }
703
704    pub fn stdout(&self) -> Option<SharedOutput> {
705        self.stdout.clone()
706    }
707
708    pub fn stderr(&self) -> Option<SharedOutput> {
709        self.stderr.clone().or_else(|| self.stdout.clone())
710    }
711}
712
713pub(super) fn assemble_default_io(
714    stdin: Option<SharedInput>,
715    stdout: Option<SharedOutput>,
716) -> ExecIo {
717    let mut io = ExecIo::new();
718    io.set_stdin(stdin);
719    io.set_stdout(stdout.clone());
720    io.set_stderr(stdout);
721    io
722}