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