Skip to main content

oxdock_core/exec/
io.rs

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