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/// 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    /// Shared pump-worker count for this run. The root hub adopts it
185    /// and forks inherit it, so one run's workers attribute to exactly
186    /// one counter even as tasks fan out.
187    worker_counter: Arc<AtomicU64>,
188}
189
190/// Shared append-only manifest of executed `--to-host` declarations.
191pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
192
193/// Shared handle to the transport behind `REMOTE` blocks. Staged here (not
194/// threaded through every `run_steps_*` signature) so existing callers keep
195/// compiling: `None` means remote execution is unavailable and every
196/// `REMOTE` step bails naming the NET plugin.
197pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
198
199/// Standard chunk size for all I/O handlers.
200pub const CHUNK_SIZE: usize = 8192;
201
202/// Minimum ring buffer capacity. Actual capacity scales with needle length.
203const MIN_RING_CAPACITY: usize = 1024;
204
205/// Sliding window for streaming pattern matching in stream assertions.
206/// Maintains a ring buffer and detects matches inline as chunks pass through.
207pub(crate) struct SlidingWindow {
208    pub(crate) needle: Vec<u8>,
209    ring: VecDeque<u8>,
210    pub matched: bool,
211}
212
213impl SlidingWindow {
214    pub fn new(needle: Vec<u8>) -> Self {
215        Self {
216            ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
217            needle,
218            matched: false,
219        }
220    }
221
222    pub fn push_chunk(&mut self, chunk: &[u8]) {
223        if self.matched {
224            return;
225        }
226        // Eviction limit scales with needle length, never below MIN_RING_CAPACITY
227        let limit = self.needle.len().max(MIN_RING_CAPACITY);
228        for &byte in chunk {
229            self.ring.push_back(byte);
230            if self.ring.len() > limit {
231                self.ring.pop_front();
232            }
233            self.check_match();
234        }
235    }
236
237    /// Replace needle without discarding ring history.
238    /// Re-evaluates current ring against updated needle.
239    pub fn update_needle(&mut self, new_needle: Vec<u8>) {
240        if self.matched {
241            return;
242        }
243        self.needle = new_needle;
244        self.check_match();
245    }
246
247    fn check_match(&mut self) {
248        if self.matched || self.ring.len() < self.needle.len() {
249            return;
250        }
251        let start = self.ring.len() - self.needle.len();
252        if self
253            .ring
254            .iter()
255            .skip(start)
256            .zip(self.needle.iter())
257            .all(|(a, b)| a == b)
258        {
259            self.matched = true;
260        }
261    }
262
263    /// Return the ring buffer contents for debugging.
264    pub fn ring_buffer(&self) -> Vec<u8> {
265        self.ring.iter().copied().collect()
266    }
267}
268
269#[derive(Clone)]
270pub(super) enum StreamHandle {
271    Stream(SharedOutput),
272    /// Live OS kernel pipe writer handed to one concurrent producer.
273    /// Only `RUN` consumes this directly; DSL commands never observe it
274    /// because `with_io` bridges OS entries to shared handles for them.
275    #[cfg(not(miri))]
276    Os(OsPipeWriter),
277}
278
279impl StreamHandle {
280    pub(super) fn to_stdout(&self) -> CommandStdout {
281        match self {
282            StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
283            #[cfg(not(miri))]
284            StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
285        }
286    }
287
288    pub(super) fn to_stderr(&self) -> CommandStderr {
289        match self {
290            StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
291            #[cfg(not(miri))]
292            StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
293        }
294    }
295}
296
297pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
298where
299    F: FnOnce(&mut dyn Write) -> Result<()>,
300{
301    match handle {
302        Some(StreamHandle::Stream(writer)) => {
303            if let Ok(mut guard) = writer.lock() {
304                op(&mut *guard)?;
305            }
306            Ok(())
307        }
308        // DSL commands never observe a live OS handle: `with_io` bridges
309        // OS entries to shared handles for them, and promotion only fires
310        // for single RUN bodies. This arm is defensive only.
311        #[cfg(not(miri))]
312        Some(StreamHandle::Os(_)) => {
313            bail!("cannot write DSL output to a live OS pipe")
314        }
315        // `None` inherits host stdout: only explicit `Stream` bindings
316        // reroute DSL output.
317        None => {
318            let mut stdout = io::stdout();
319            op(&mut stdout)
320        }
321    }
322}
323
324/// Slice-based byte adapter over pipe halves for host (`#[oxdock_func]`)
325///
326/// stateful functions. All byte movement goes through the standard traits
327/// on caller-owned buffers : `Read::read(&mut [u8])` and
328/// `Write::write(&[u8])` : so hosts can hand pipes directly to `serde_json`,
329/// `flate2`, `tar`, and friends with a single reused stack buffer and zero
330/// per-chunk allocation. `0` read means EOF exactly like `std::io`; never
331/// slurp a stream into one `Vec` (unbounded memory growth : stream it).
332/// `flush()` delegates to backend flush semantics, which for script pipes
333/// is a no-op that loses nothing: every `write()` wakes readers itself.
334///
335/// A host read blocks the calling task thread exactly like a DSL reader;
336/// EOF and half-close map identically to DSL consumers. Take-once applies
337/// like everywhere else: bridging an OS backend takes once, repeats bail.
338pub struct PipeStream {
339    reader: Option<SharedInput>,
340    writer: Option<SharedOutput>,
341}
342
343impl PipeStream {
344    /// Read-half adapter (e.g. over [`StepCtx::pipe_reader`](super::steps::StepCtx::pipe_reader)).
345    pub fn reader(reader: SharedInput) -> Self {
346        Self {
347            reader: Some(reader),
348            writer: None,
349        }
350    }
351
352    /// Write-half adapter (e.g. over [`StepCtx::pipe_writer`](super::steps::StepCtx::pipe_writer)).
353    pub fn writer(writer: SharedOutput) -> Self {
354        Self {
355            reader: None,
356            writer: Some(writer),
357        }
358    }
359
360    /// Both halves (e.g. a filter with separate in/out pipes).
361    pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
362        Self {
363            reader: Some(reader),
364            writer: Some(writer),
365        }
366    }
367}
368
369impl std::io::Read for PipeStream {
370    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
371        let Some(reader) = &self.reader else {
372            return Err(std::io::Error::new(
373                std::io::ErrorKind::NotConnected,
374                "pipe stream has no reader half",
375            ));
376        };
377        let mut guard = reader
378            .lock()
379            .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
380        guard.read(buf)
381    }
382}
383
384impl std::io::Write for PipeStream {
385    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
386        let Some(writer) = &self.writer else {
387            return Err(std::io::Error::new(
388                std::io::ErrorKind::NotConnected,
389                "pipe stream has no writer half",
390            ));
391        };
392        let mut guard = writer
393            .lock()
394            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
395        guard.write(buf)
396    }
397
398    fn flush(&mut self) -> std::io::Result<()> {
399        let Some(writer) = &self.writer else {
400            return Err(std::io::Error::new(
401                std::io::ErrorKind::NotConnected,
402                "pipe stream has no writer half",
403            ));
404        };
405        let mut guard = writer
406            .lock()
407            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
408        guard.flush()
409    }
410}
411
412/// Hard cap for `ASSERT_EQ stdout` exact accumulators, mirroring the
413/// `SpillBuffer` spill threshold: exact stream matching is a test-time
414/// opt-in, and unbounded trials must use pipe targets or harness captures.
415pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
416
417/// Cumulative stdout record for one execution generation backing
418/// `ASSERT_EQ stdout`. Unlike `SlidingWindow` nothing is ever evicted;
419/// once the cap is exceeded the entry latches `overflowed` and stops
420/// growing, and the asserting step reports it with remediation guidance.
421pub(crate) struct ExactCapture {
422    pub(crate) bytes: Vec<u8>,
423    pub(crate) overflowed: bool,
424}
425
426impl ExactCapture {
427    pub fn new() -> Self {
428        Self {
429            bytes: Vec::new(),
430            overflowed: false,
431        }
432    }
433
434    pub fn push_chunk(&mut self, chunk: &[u8]) {
435        if self.overflowed {
436            return;
437        }
438        if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
439            self.overflowed = true;
440            return;
441        }
442        self.bytes.extend_from_slice(chunk);
443    }
444}
445
446/// Which host stream a tee forwards to when no capture sink is configured.
447#[derive(Clone, Copy)]
448enum TeeStream {
449    Stdout,
450    Stderr,
451}
452
453/// Wraps the configured stdout sink so every byte written to it is also
454/// pushed to all registered SlidingWindow observers for stream assertions.
455/// When no sink is configured (`inner` is `None`) bytes are forwarded to
456/// real stdout so interactive CLI output still reaches the terminal.
457struct TeeWriter {
458    inner: Option<SharedOutput>,
459    stream: TeeStream,
460    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
461    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
462}
463
464impl Write for TeeWriter {
465    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
466        // Forward to downstream (streaming)
467        match &self.inner {
468            Some(inner) => {
469                let mut guard = inner
470                    .lock()
471                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
472                guard.write_all(buf)?;
473            }
474            None => match self.stream {
475                TeeStream::Stdout => io::stdout().write_all(buf)?,
476                TeeStream::Stderr => io::stderr().write_all(buf)?,
477            },
478        }
479        // Push to ALL registered assertion windows (O(1) per byte per window)
480        if let Ok(mut windows) = self.windows.lock() {
481            for window in windows.values_mut() {
482                window.push_chunk(buf);
483            }
484        }
485        if let Ok(mut exact) = self.exact.lock() {
486            for capture in exact.values_mut() {
487                capture.push_chunk(buf);
488            }
489        }
490        Ok(buf.len())
491    }
492
493    fn flush(&mut self) -> io::Result<()> {
494        match &self.inner {
495            Some(inner) => {
496                let mut guard = inner
497                    .lock()
498                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
499                guard.flush()?;
500            }
501            None => match self.stream {
502                TeeStream::Stdout => io::stdout().flush()?,
503                TeeStream::Stderr => io::stderr().flush()?,
504            },
505        }
506        Ok(())
507    }
508}
509
510/// Installs the tee around `sink` (or real stdout when absent).
511pub(crate) fn teed_stdout(
512    sink: Option<SharedOutput>,
513    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
514    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
515) -> SharedOutput {
516    Arc::new(Mutex::new(TeeWriter {
517        inner: sink,
518        stream: TeeStream::Stdout,
519        windows,
520        exact,
521    }))
522}
523
524/// Installs the tee around `sink` (or real stderr when absent) for
525/// `ASSERT_CONTAINS stderr` substring observers. Exact matching is not
526/// offered over stderr; use pipe targets or harness captures for that.
527pub(crate) fn teed_stderr(
528    sink: Option<SharedOutput>,
529    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
530) -> SharedOutput {
531    Arc::new(Mutex::new(TeeWriter {
532        inner: sink,
533        stream: TeeStream::Stderr,
534        windows,
535        exact: Arc::new(Mutex::new(HashMap::new())),
536    }))
537}
538
539impl ExecIo {
540    pub fn new() -> Self {
541        Self::default()
542    }
543
544    pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
545        self.stdin = stdin;
546    }
547
548    pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
549        self.stdout = stdout.clone();
550        if self.stderr.is_none() {
551            self.stderr = stdout;
552        }
553    }
554
555    pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
556        self.stderr = stderr;
557    }
558
559    /// Stage this run's pump-worker count. Chainable.
560    pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
561        self.worker_counter = counter;
562        self
563    }
564
565    /// This run's shared pump-worker count.
566    pub fn worker_counter(&self) -> Arc<AtomicU64> {
567        Arc::clone(&self.worker_counter)
568    }
569
570    /// Stage the transport behind one `REMOTE` target. Chainable; the NET
571    /// plugin registers one session per inventory target at CLI startup
572    /// and tests stage mocks. Registration is inert (no process spawns
573    /// until a block entry runs).
574    pub fn set_remote_runner_for_target(
575        &mut self,
576        target: String,
577        runner: RemoteRunnerArc,
578    ) -> &mut Self {
579        self.remote_runners.insert(target, runner);
580        self
581    }
582
583    /// The staged remote transport for `target`, if any. `REMOTE`
584    /// interception bails when the target has no runner.
585    pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
586        self.remote_runners.get(target).cloned()
587    }
588
589    /// Legacy single-runner staging: registers under the empty target.
590    /// Prefer [`set_remote_runner_for_target`](Self::set_remote_runner_for_target).
591    pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
592        self.set_remote_runner_for_target(String::new(), runner)
593    }
594
595    /// Mark this run as executing inside a remote guest serve loop. In
596    /// guest mode, flagged `COPY --from-host` / `--to-host` steps are
597    /// transfer declarations already fulfilled by the session, so they
598    /// acknowledge as no-ops instead of re-copying. Never set on hosts:
599    /// the parser rejects flagged copies outside `REMOTE` bodies, and
600    /// hosts never execute `REMOTE` bodies.
601    pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
602        self.remote_guest = guest;
603        self
604    }
605
606    /// Whether flagged `COPY` transfer declarations acknowledge as no-ops.
607    pub fn is_remote_guest(&self) -> bool {
608        self.remote_guest
609    }
610
611    /// Stage the shared push-manifest sink for a guest serve loop.
612    /// Chainable. Executed flagged `COPY` steps append here; the serve
613    /// loop packs exactly these entries after the engine joins.
614    pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
615        self.push_manifest_sink = Some(sink);
616        self
617    }
618
619    /// The staged push-manifest sink, if any.
620    pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
621        self.push_manifest_sink.clone()
622    }
623
624    pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
625        let key = key.into();
626        self.inherit_env_removed.remove(&key);
627        self.inherit_env_overrides.insert(key, value.into());
628    }
629
630    pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
631        let key = key.into();
632        self.inherit_env_overrides.remove(&key);
633        self.inherit_env_removed.insert(key);
634    }
635
636    pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
637        self.inherit_env_overrides.get(key)
638    }
639
640    pub fn inherit_env_is_removed(&self, key: &str) -> bool {
641        self.inherit_env_removed.contains(key)
642    }
643
644    pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
645        &self.inherit_env_overrides
646    }
647
648    /// Ensure a handle is materialized for one binding site (see
649    /// [`PipeRegistry::ensure_handle`]). Main-flow bindings call this with
650    /// the per-step trigger; task bodies are pre-decided by the spawn-time
651    /// pin walk, making this a no-op there.
652    pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
653        PipeRegistry::ensure_handle(handle, promote)
654    }
655
656    /// Snapshot of one handle for `INSPECT()` diagnostics.
657    pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
658        PipeRegistry::inspect_pipe(handle)
659    }
660
661    /// Non-destructive snapshot of a script handle's buffered bytes for
662    /// pipe-content assertions.
663    ///
664    /// Public so out-of-crate harnesses can assert on script-owned pipes
665    /// after a run completes, via the `PIPE` values in the returned
666    /// bindings. Only meaningful once writers detached (post-run);
667    /// unbound handles and OS pairs bail loudly.
668    pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
669        PipeRegistry::peek_pipe_content(handle)
670    }
671
672    /// Pin a keeper slot on a script backend. `None` for OS-materialized
673    /// and unbound handles. Callers ensure the handle first so OS
674    /// promotion is honored and this never forces a backend into
675    /// existence.
676    pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
677        PipeRegistry::pin_keeper(handle)
678    }
679
680    /// Resolve a stdin binding to a runnable handle plus the script
681    /// backend (for timeout-bounded bridge reads; `None` for OS pairs).
682    pub(super) fn resolve_stdin(
683        &self,
684        idx: usize,
685        handle: &PipeHandle,
686        direct: bool,
687        promote: bool,
688    ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
689        PipeRegistry::resolve_stdin(idx, handle, direct, promote)
690    }
691
692    /// Resolve a stdout binding to a runnable handle plus the script
693    /// backend (for the bridge's socket-EOF force-close).
694    pub(super) fn resolve_stdout(
695        &self,
696        idx: usize,
697        handle: &PipeHandle,
698        direct: bool,
699        promote: bool,
700    ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
701        PipeRegistry::resolve_stdout(idx, handle, direct, promote)
702    }
703
704    /// Resolve a stderr binding to a runnable handle.
705    pub(super) fn resolve_stderr(
706        &self,
707        idx: usize,
708        handle: &PipeHandle,
709        direct: bool,
710        promote: bool,
711    ) -> Result<StreamHandle> {
712        PipeRegistry::resolve_stderr(idx, handle, direct, promote)
713    }
714
715    pub fn stdin(&self) -> Option<SharedInput> {
716        self.stdin.clone()
717    }
718
719    pub fn stdout(&self) -> Option<SharedOutput> {
720        self.stdout.clone()
721    }
722
723    pub fn stderr(&self) -> Option<SharedOutput> {
724        self.stderr.clone().or_else(|| self.stdout.clone())
725    }
726}
727
728pub(super) fn assemble_default_io(
729    stdin: Option<SharedInput>,
730    stdout: Option<SharedOutput>,
731) -> ExecIo {
732    let mut io = ExecIo::new();
733    io.set_stdin(stdin);
734    io.set_stdout(stdout.clone());
735    io.set_stderr(stdout);
736    io
737}