oxdock-core 0.40.0-alpha

Core engine for OxDock's Dockerfile-inspired compile-time DSL, orchestrating workspace snapshots and asset embedding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::{self, Write};
use std::sync::{Arc, Mutex, atomic::AtomicU64};

use anyhow::Result;
#[cfg(not(miri))]
use anyhow::bail;
#[cfg(not(miri))]
use oxdock_pipe::OsPipeWriter;
use oxdock_pipe::{
    KeeperGuard, Materialized, PipeHandle, PipeInfo, PipeInner, SharedInput, SharedOutput,
    inspect as inspect_handle, materialize, peek as peek_handle, script_backend,
};
use oxdock_process::{CommandStderr, CommandStdin, CommandStdout};

/// Fan-out writer for background tasks: every default-routed byte goes
/// to the parent handle exactly as an unwrapped write would, and a copy
/// lands in the task's tail ring for `TASK_POLL`. Parent semantics are
/// preserved verbatim (Stream sink, inherited host stdio, OS-pipe bail),
/// so the only observable difference is the retained copy.
pub(super) struct TaskTee {
    parent: Option<StreamHandle>,
    tails: Arc<Mutex<super::state::TaskTails>>,
    stream: TeeStream,
}

impl TaskTee {
    /// Wrap a worker handle: `None` parent inherits host stdio, matching
    /// `write_stdout`/`write_stderr` behavior for the unwrapped case.
    pub(super) fn wrap(
        parent: Option<StreamHandle>,
        tails: &Arc<Mutex<super::state::TaskTails>>,
        stream: TeeStream,
    ) -> Option<StreamHandle> {
        Some(StreamHandle::Stream(Arc::new(Mutex::new(Self {
            parent,
            tails: Arc::clone(tails),
            stream,
        }))))
    }
}

impl Write for TaskTee {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match &self.parent {
            Some(StreamHandle::Stream(writer)) => {
                if let Ok(mut guard) = writer.lock() {
                    guard.write_all(buf)?;
                }
            }
            #[cfg(not(miri))]
            Some(StreamHandle::Os(_)) => {
                return Err(io::Error::other(
                    "cannot write DSL output to a live OS pipe",
                ));
            }
            None => match self.stream {
                TeeStream::Stdout => io::stdout().write_all(buf)?,
                TeeStream::Stderr => io::stderr().write_all(buf)?,
            },
        }
        if let Ok(mut tails) = self.tails.lock() {
            tails.push(self.stream, buf);
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Handle-scoped pipe resolution. No central index exists: every method
/// below takes the `PIPE` value's backend cell, materializing it on first
/// binding (first-binding-wins under the cell lock) and adapting later
/// bindings through the existing machinery. The `ExecIo` receiver carries
/// no pipe state; methods live here (rather than as free functions) so
/// call sites keep their `cx.state.io.*` shape.
#[derive(Clone, Default)]
pub(super) struct PipeRegistry;

/// Loud take-twice error for OS handles: a second consumer or producer on
/// one end can never steal the descriptor, and (unlike the old recycling
/// behavior) never silently receives a fresh pair either : the remedy is a
/// fresh declaration. No rebind rule exists by design: no rule can tell
/// sequential loop reuse apart from concurrent fan-in sharing.
#[cfg(not(miri))]
fn spent_handle() -> anyhow::Error {
    anyhow::anyhow!(
        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session",
    )
}

impl PipeRegistry {
    /// First-binding-wins materialization for one binding site: an unbound
    /// handle decides its kind from `promote` (the caller supplies full
    /// usage context); a decided handle is returned unchanged. Callers
    /// adapt mismatches through resolution below, never here.
    pub(super) fn ensure_handle(handle: &PipeHandle, promote: bool) -> Result<()> {
        materialize(handle, promote)?;
        Ok(())
    }

    /// Non-destructive snapshot of a script handle's buffered bytes for
    /// pipe-content assertions. Delegates to the backend without creating:
    /// unbound handles and OS pairs bail loudly instead of yielding empty
    /// content.
    ///
    /// Public so out-of-crate harnesses can assert on script-owned pipes
    /// after a run completes, via the `PIPE` values in the returned
    /// bindings. Only meaningful once writers detached (post-run).
    pub fn peek_pipe_content(handle: &PipeHandle) -> Result<Vec<u8>> {
        peek_handle(handle)
    }

    /// Snapshot one handle for `INSPECT()` diagnostics.
    pub(super) fn inspect_pipe(handle: &PipeHandle) -> PipeInfo {
        inspect_handle(handle)
    }

    /// Pin a keeper slot on a script backend so transient writer churn can
    /// never observe zero writers. Returns `None` for OS-materialized and
    /// unbound handles, which need no pin. Callers ensure the handle
    /// first so OS promotion is honored and this never forces a script
    /// backend into existence.
    pub(super) fn pin_keeper(handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
        Ok(script_backend(handle).map(KeeperGuard::new))
    }

    /// Resolve a stdin binding against a decided handle. Script backends
    /// hand out a shared reader (plus the backend for timeout-bounded
    /// bridge reads); OS pairs hand the take-once reader to `RUN` directly
    /// and bridge it to a shared handle for DSL commands. A second take
    /// on one end bails loudly with the fresh-declaration remedy instead
    /// of stealing the descriptor.
    pub(super) fn resolve_stdin(
        handle: &PipeHandle,
        direct: bool,
        promote: bool,
    ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
        // `direct` serves only the OS-pipe arms below, which are
        // compiled out under Miri.
        let _ = direct;
        match materialize(handle, promote)? {
            Materialized::Script(backend) => {
                Ok((CommandStdin::Stream(backend.reader_handle()), Some(backend)))
            }
            #[cfg(not(miri))]
            Materialized::Os(entry) => {
                if direct {
                    return Ok((CommandStdin::OsPipe(entry.reader.clone()), None));
                }
                let owned = entry.reader.take().map_err(|_| spent_handle())?;
                Ok((
                    CommandStdin::Stream(Arc::new(std::sync::Mutex::new(owned))),
                    None,
                ))
            }
        }
    }

    /// Resolve a stdout binding. Mirrors
    /// [`PipeRegistry::resolve_stdin`] with `StreamHandle` outputs so
    /// `RUN` keeps zero copy `Stdio` handoff, plus the script backend for
    /// the bridge's socket-EOF force-close.
    pub(super) fn resolve_stdout(
        handle: &PipeHandle,
        direct: bool,
        promote: bool,
    ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
        // `direct` serves only the OS-pipe arms below, which are
        // compiled out under Miri.
        let _ = direct;
        match materialize(handle, promote)? {
            Materialized::Script(backend) => {
                Ok((StreamHandle::Stream(backend.writer_handle()), Some(backend)))
            }
            #[cfg(not(miri))]
            Materialized::Os(entry) => {
                if direct {
                    return Ok((StreamHandle::Os(entry.writer.clone()), None));
                }
                let owned = entry.writer.take().map_err(|_| spent_handle())?;
                Ok((
                    StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))),
                    None,
                ))
            }
        }
    }

    /// Resolve a stderr binding. Mirrors
    /// [`PipeRegistry::resolve_stdout`]: `RUN` keeps zero copy handoff,
    /// DSL commands get a bridged shared handle. Binding `stdout` and
    /// `stderr` to one live OS handle takes the same slot twice, so the
    /// second take bails deterministically; merge in shell via `2>&1`
    /// instead.
    pub(super) fn resolve_stderr(
        handle: &PipeHandle,
        direct: bool,
        promote: bool,
    ) -> Result<StreamHandle> {
        // `direct` serves only the OS-pipe arms below, which are
        // compiled out under Miri.
        let _ = direct;
        match materialize(handle, promote)? {
            Materialized::Script(backend) => Ok(StreamHandle::Stream(backend.writer_handle())),
            #[cfg(not(miri))]
            Materialized::Os(entry) => {
                if direct {
                    return Ok(StreamHandle::Os(entry.writer.clone()));
                }
                let owned = entry.writer.take().map_err(|_| spent_handle())?;
                Ok(StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))))
            }
        }
    }
}

#[derive(Clone, Default)]
pub struct ExecIo {
    stdin: Option<SharedInput>,
    stdout: Option<SharedOutput>,
    stderr: Option<SharedOutput>,
    inherit_env_overrides: HashMap<String, String>,
    inherit_env_removed: HashSet<String>,
    remote_runners: HashMap<String, RemoteRunnerArc>,
    remote_guest: bool,
    /// Shared sink for the guest execution manifest: when staged, executed
    /// flagged `COPY` steps append their evaluated pairs here as well as
    /// to state, so a serve loop holding only `ExecIo` can pack exactly
    /// what ran. `None` on hosts (nothing records).
    push_manifest_sink: Option<PushManifestSink>,
    /// Shared pump-worker count for this run. The root hub adopts it
    /// and forks inherit it, so one run's workers attribute to exactly
    /// one counter even as tasks fan out.
    worker_counter: Arc<AtomicU64>,
    /// Host override for `INTERPRETER()`: the path returned instead of
    /// the current executable. Staged by embedding hosts (and doc
    /// conformance) whose in-process binary is not a CLI; `None` keeps
    /// the `current_exe` default.
    interpreter_override: Option<String>,
}

/// Shared append-only manifest of executed `--to-host` declarations.
pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;

/// Shared handle to the transport behind `REMOTE` blocks. Staged here (not
/// threaded through every `run_steps_*` signature) so existing callers keep
/// compiling: `None` means remote execution is unavailable and every
/// `REMOTE` step bails naming the NET plugin.
pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;

/// Standard chunk size for all I/O handlers.
pub const CHUNK_SIZE: usize = 8192;

/// Minimum ring buffer capacity. Actual capacity scales with needle length.
const MIN_RING_CAPACITY: usize = 1024;

/// Sliding window for streaming pattern matching in stream assertions.
/// Maintains a ring buffer and detects matches inline as chunks pass through.
pub(crate) struct SlidingWindow {
    pub(crate) needle: Vec<u8>,
    ring: VecDeque<u8>,
    pub matched: bool,
}

impl SlidingWindow {
    pub fn new(needle: Vec<u8>) -> Self {
        Self {
            ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
            needle,
            matched: false,
        }
    }

    pub fn push_chunk(&mut self, chunk: &[u8]) {
        if self.matched {
            return;
        }
        // Eviction limit scales with needle length, never below MIN_RING_CAPACITY
        let limit = self.needle.len().max(MIN_RING_CAPACITY);
        for &byte in chunk {
            self.ring.push_back(byte);
            if self.ring.len() > limit {
                self.ring.pop_front();
            }
            self.check_match();
        }
    }

    /// Replace needle without discarding ring history.
    /// Re-evaluates current ring against updated needle.
    pub fn update_needle(&mut self, new_needle: Vec<u8>) {
        if self.matched {
            return;
        }
        self.needle = new_needle;
        self.check_match();
    }

    fn check_match(&mut self) {
        if self.matched || self.ring.len() < self.needle.len() {
            return;
        }
        let start = self.ring.len() - self.needle.len();
        if self
            .ring
            .iter()
            .skip(start)
            .zip(self.needle.iter())
            .all(|(a, b)| a == b)
        {
            self.matched = true;
        }
    }

    /// Return the ring buffer contents for debugging.
    pub fn ring_buffer(&self) -> Vec<u8> {
        self.ring.iter().copied().collect()
    }
}

#[derive(Clone)]
pub(super) enum StreamHandle {
    Stream(SharedOutput),
    /// Live OS kernel pipe writer handed to one concurrent producer.
    /// Only `RUN` consumes this directly; DSL commands never observe it
    /// because `with_io` bridges OS entries to shared handles for them.
    #[cfg(not(miri))]
    Os(OsPipeWriter),
}

impl StreamHandle {
    pub(super) fn to_stdout(&self) -> CommandStdout {
        match self {
            StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
            #[cfg(not(miri))]
            StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
        }
    }

    pub(super) fn to_stderr(&self) -> CommandStderr {
        match self {
            StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
            #[cfg(not(miri))]
            StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
        }
    }
}

pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
where
    F: FnOnce(&mut dyn Write) -> Result<()>,
{
    match handle {
        Some(StreamHandle::Stream(writer)) => {
            if let Ok(mut guard) = writer.lock() {
                op(&mut *guard)?;
            }
            Ok(())
        }
        // DSL commands never observe a live OS handle: `with_io` bridges
        // OS entries to shared handles for them, and promotion only fires
        // for single RUN bodies. This arm is defensive only.
        #[cfg(not(miri))]
        Some(StreamHandle::Os(_)) => {
            bail!("cannot write DSL output to a live OS pipe")
        }
        // `None` inherits host stdout: only explicit `Stream` bindings
        // reroute DSL output.
        None => {
            let mut stdout = io::stdout();
            op(&mut stdout)
        }
    }
}

/// Slice-based byte adapter over pipe halves for host (`#[oxdock_func]`)
///
/// stateful functions. All byte movement goes through the standard traits
/// on caller-owned buffers : `Read::read(&mut [u8])` and
/// `Write::write(&[u8])` : so hosts can hand pipes directly to `serde_json`,
/// `flate2`, `tar`, and friends with a single reused stack buffer and zero
/// per-chunk allocation. `0` read means EOF exactly like `std::io`; never
/// slurp a stream into one `Vec` (unbounded memory growth : stream it).
/// `flush()` delegates to backend flush semantics, which for script pipes
/// is a no-op that loses nothing: every `write()` wakes readers itself.
///
/// A host read blocks the calling task thread exactly like a DSL reader;
/// EOF and half-close map identically to DSL consumers. Take-once applies
/// like everywhere else: bridging an OS backend takes once, repeats bail.
pub struct PipeStream {
    reader: Option<SharedInput>,
    writer: Option<SharedOutput>,
}

impl PipeStream {
    /// Read-half adapter (e.g. over [`StepCtx::pipe_reader`](super::steps::StepCtx::pipe_reader)).
    pub fn reader(reader: SharedInput) -> Self {
        Self {
            reader: Some(reader),
            writer: None,
        }
    }

    /// Write-half adapter (e.g. over [`StepCtx::pipe_writer`](super::steps::StepCtx::pipe_writer)).
    pub fn writer(writer: SharedOutput) -> Self {
        Self {
            reader: None,
            writer: Some(writer),
        }
    }

    /// Both halves (e.g. a filter with separate in/out pipes).
    pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
        Self {
            reader: Some(reader),
            writer: Some(writer),
        }
    }
}

impl std::io::Read for PipeStream {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let Some(reader) = &self.reader else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "pipe stream has no reader half",
            ));
        };
        let mut guard = reader
            .lock()
            .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
        guard.read(buf)
    }
}

impl std::io::Write for PipeStream {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let Some(writer) = &self.writer else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "pipe stream has no writer half",
            ));
        };
        let mut guard = writer
            .lock()
            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
        guard.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        let Some(writer) = &self.writer else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "pipe stream has no writer half",
            ));
        };
        let mut guard = writer
            .lock()
            .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
        guard.flush()
    }
}

/// Hard cap for `ASSERT_EQ`/`ASSERT_NE stdout` exact accumulators, mirroring the
/// `SpillBuffer` spill threshold: exact stream matching is a test-time
/// opt-in, and unbounded trials must use pipe targets or harness captures.
pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;

/// Cumulative stdout record for one execution generation backing
/// `ASSERT_EQ`/`ASSERT_NE stdout`. Unlike `SlidingWindow` nothing is ever evicted;
/// once the cap is exceeded the entry latches `overflowed` and stops
/// growing, and the asserting step reports it with remediation guidance.
pub(crate) struct ExactCapture {
    pub(crate) bytes: Vec<u8>,
    pub(crate) overflowed: bool,
}

impl ExactCapture {
    pub fn new() -> Self {
        Self {
            bytes: Vec::new(),
            overflowed: false,
        }
    }

    pub fn push_chunk(&mut self, chunk: &[u8]) {
        if self.overflowed {
            return;
        }
        if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
            self.overflowed = true;
            return;
        }
        self.bytes.extend_from_slice(chunk);
    }
}

/// Which host stream a tee forwards to when no capture sink is configured.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TeeStream {
    Stdout,
    Stderr,
}

/// One live output fragment: the bytes from a single tee write plus
/// which host stream they belong to. Carried from the synchronous
/// execution threads to the MCP forwarder over a bounded channel.
#[derive(Clone, Debug)]
pub struct StreamChunk {
    /// Which host stream produced these bytes.
    pub kind: TeeStream,
    /// Raw bytes as written. Decoded lossily at the forward edge.
    pub bytes: Vec<u8>,
}

/// Live-stream tap for a tool call. Cloned into every per-call tee:
/// each default-routed write `try_send`s one chunk. Bounded channel,
/// so a chatty tool cannot grow the queue without bound; overflow
/// chunks are dropped and counted. Explicit `WITH_IO` redirections
/// bypass the tee entirely, so redirected bytes never stream.
#[derive(Clone, Debug)]
pub struct StreamHook {
    /// Bounded egress. `try_send` only: never blocks script execution.
    pub tx: std::sync::mpsc::SyncSender<StreamChunk>,
    /// Chunks dropped on a full channel. Read after the call for the
    /// transit note; lossy transit never affects the tail buffers.
    pub dropped: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}

/// Wraps the configured stdout sink so every byte written to it is also
/// pushed to all registered SlidingWindow observers for stream assertions.
/// When no sink is configured (`inner` is `None`) bytes are forwarded to
/// real stdout so interactive CLI output still reaches the terminal.
struct TeeWriter {
    inner: Option<SharedOutput>,
    stream: TeeStream,
    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
    hook: Option<StreamHook>,
}

impl Write for TeeWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        // Forward to downstream (streaming)
        match &self.inner {
            Some(inner) => {
                let mut guard = inner
                    .lock()
                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
                guard.write_all(buf)?;
            }
            None => match self.stream {
                TeeStream::Stdout => io::stdout().write_all(buf)?,
                TeeStream::Stderr => io::stderr().write_all(buf)?,
            },
        }
        // Push to ALL registered assertion windows (O(1) per byte per window)
        if let Ok(mut windows) = self.windows.lock() {
            for window in windows.values_mut() {
                window.push_chunk(buf);
            }
        }
        if let Ok(mut exact) = self.exact.lock() {
            for capture in exact.values_mut() {
                capture.push_chunk(buf);
            }
        }
        // Live tap: default-routed bytes stream to the MCP forwarder.
        // `try_send` only, so a slow client never blocks execution;
        // overflow drops and counts. Redirected bytes never reach this
        // tee, so explicit `WITH_IO` stays silent by construction.
        if let Some(hook) = &self.hook {
            let chunk = StreamChunk {
                kind: self.stream,
                bytes: buf.to_vec(),
            };
            if hook.tx.try_send(chunk).is_err() {
                hook.dropped
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        match &self.inner {
            Some(inner) => {
                let mut guard = inner
                    .lock()
                    .map_err(|_| io::Error::other("stdout sink poisoned"))?;
                guard.flush()?;
            }
            None => match self.stream {
                TeeStream::Stdout => io::stdout().flush()?,
                TeeStream::Stderr => io::stderr().flush()?,
            },
        }
        Ok(())
    }
}

/// Installs the tee around `sink` (or real stdout when absent).
pub(crate) fn teed_stdout(
    sink: Option<SharedOutput>,
    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
    exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
    hook: Option<StreamHook>,
) -> SharedOutput {
    Arc::new(Mutex::new(TeeWriter {
        inner: sink,
        stream: TeeStream::Stdout,
        windows,
        exact,
        hook,
    }))
}

/// Installs the tee around `sink` (or real stderr when absent) for
/// `ASSERT_CONTAINS stderr` substring observers. Exact matching is not
/// offered over stderr; use pipe targets or harness captures instead.
pub(crate) fn teed_stderr(
    sink: Option<SharedOutput>,
    windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
    hook: Option<StreamHook>,
) -> SharedOutput {
    Arc::new(Mutex::new(TeeWriter {
        inner: sink,
        stream: TeeStream::Stderr,
        windows,
        exact: Arc::new(Mutex::new(HashMap::new())),
        hook,
    }))
}

impl ExecIo {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
        self.stdin = stdin;
    }

    pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
        self.stdout = stdout.clone();
        if self.stderr.is_none() {
            self.stderr = stdout;
        }
    }

    pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
        self.stderr = stderr;
    }

    /// Stage this run's pump-worker count. Chainable.
    pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
        self.worker_counter = counter;
        self
    }

    /// This run's shared pump-worker count.
    pub fn worker_counter(&self) -> Arc<AtomicU64> {
        Arc::clone(&self.worker_counter)
    }

    /// Stage the `INTERPRETER()` path for this run. Chainable. Embedding
    /// hosts whose engine runs in-process (no CLI binary as the current
    /// executable) point this at their CLI so child reinvocation leaves
    /// the process boundary intact.
    pub fn set_interpreter<S: Into<String>>(&mut self, path: S) -> &mut Self {
        self.interpreter_override = Some(path.into());
        self
    }

    /// The staged interpreter path, if any. `None` selects the
    /// `current_exe` default.
    pub fn interpreter_override(&self) -> Option<String> {
        self.interpreter_override.clone()
    }

    /// Stage the transport behind one `REMOTE` target. Chainable; the NET
    /// plugin registers one session per inventory target at CLI startup
    /// and tests stage mocks. Registration is inert (no process spawns
    /// until a block entry runs).
    pub fn set_remote_runner_for_target(
        &mut self,
        target: String,
        runner: RemoteRunnerArc,
    ) -> &mut Self {
        self.remote_runners.insert(target, runner);
        self
    }

    /// The staged remote transport for `target`, if any. `REMOTE`
    /// interception bails when the target has no runner.
    pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
        self.remote_runners.get(target).cloned()
    }

    /// Legacy single-runner staging: registers under the empty target.
    /// Prefer [`set_remote_runner_for_target`](Self::set_remote_runner_for_target).
    pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
        self.set_remote_runner_for_target(String::new(), runner)
    }

    /// Mark this run as executing inside a remote guest serve loop. In
    /// guest mode, flagged `COPY --from-host` / `--to-host` steps are
    /// transfer declarations already fulfilled by the session, so they
    /// acknowledge as no-ops instead of re-copying. Never set on hosts:
    /// the parser rejects flagged copies outside `REMOTE` bodies, and
    /// hosts never execute `REMOTE` bodies.
    pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
        self.remote_guest = guest;
        self
    }

    /// Whether flagged `COPY` transfer declarations acknowledge as no-ops.
    pub fn is_remote_guest(&self) -> bool {
        self.remote_guest
    }

    /// Stage the shared push-manifest sink for a guest serve loop.
    /// Chainable. Executed flagged `COPY` steps append here; the serve
    /// loop packs exactly these entries after the engine joins.
    pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
        self.push_manifest_sink = Some(sink);
        self
    }

    /// The staged push-manifest sink, if any.
    pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
        self.push_manifest_sink.clone()
    }

    pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
        let key = key.into();
        self.inherit_env_removed.remove(&key);
        self.inherit_env_overrides.insert(key, value.into());
    }

    pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
        let key = key.into();
        self.inherit_env_overrides.remove(&key);
        self.inherit_env_removed.insert(key);
    }

    pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
        self.inherit_env_overrides.get(key)
    }

    pub fn inherit_env_is_removed(&self, key: &str) -> bool {
        self.inherit_env_removed.contains(key)
    }

    pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
        &self.inherit_env_overrides
    }

    /// Ensure a handle is materialized for one binding site (see
    /// [`PipeRegistry::ensure_handle`]). Main-flow bindings call this with
    /// the per-step trigger; task bodies are pre-decided by the spawn-time
    /// pin walk, making this a no-op there.
    pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
        PipeRegistry::ensure_handle(handle, promote)
    }

    /// Snapshot of one handle for `INSPECT()` diagnostics.
    pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
        PipeRegistry::inspect_pipe(handle)
    }

    /// Non-destructive snapshot of a script handle's buffered bytes for
    /// pipe-content assertions.
    ///
    /// Public so out-of-crate harnesses can assert on script-owned pipes
    /// after a run completes, via the `PIPE` values in the returned
    /// bindings. Only meaningful once writers detached (post-run);
    /// unbound handles and OS pairs bail loudly.
    pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
        PipeRegistry::peek_pipe_content(handle)
    }

    /// Pin a keeper slot on a script backend. `None` for OS-materialized
    /// and unbound handles. Callers ensure the handle first so OS
    /// promotion is honored and this never forces a backend into
    /// existence.
    pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
        PipeRegistry::pin_keeper(handle)
    }

    /// Resolve a stdin binding to a runnable handle plus the script
    /// backend (for timeout-bounded bridge reads; `None` for OS pairs).
    pub(super) fn resolve_stdin(
        &self,
        handle: &PipeHandle,
        direct: bool,
        promote: bool,
    ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
        PipeRegistry::resolve_stdin(handle, direct, promote)
    }

    /// Resolve a stdout binding to a runnable handle plus the script
    /// backend (for the bridge's socket-EOF force-close).
    pub(super) fn resolve_stdout(
        &self,
        handle: &PipeHandle,
        direct: bool,
        promote: bool,
    ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
        PipeRegistry::resolve_stdout(handle, direct, promote)
    }

    /// Resolve a stderr binding to a runnable handle.
    pub(super) fn resolve_stderr(
        &self,
        handle: &PipeHandle,
        direct: bool,
        promote: bool,
    ) -> Result<StreamHandle> {
        PipeRegistry::resolve_stderr(handle, direct, promote)
    }

    pub fn stdin(&self) -> Option<SharedInput> {
        self.stdin.clone()
    }

    pub fn stdout(&self) -> Option<SharedOutput> {
        self.stdout.clone()
    }

    pub fn stderr(&self) -> Option<SharedOutput> {
        self.stderr.clone().or_else(|| self.stdout.clone())
    }
}

pub(super) fn assemble_default_io(
    stdin: Option<SharedInput>,
    stdout: Option<SharedOutput>,
) -> ExecIo {
    let mut io = ExecIo::new();
    io.set_stdin(stdin);
    io.set_stdout(stdout.clone());
    io.set_stderr(stdout);
    io
}

#[cfg(test)]
mod tests {
    use super::*;

    /// One tee plus its hook channel, drop counter, and backing sink.
    type TestTee = (
        TeeWriter,
        std::sync::mpsc::Receiver<StreamChunk>,
        Arc<std::sync::atomic::AtomicUsize>,
        Arc<Mutex<Vec<u8>>>,
    );

    fn tee_with_hook(stream: TeeStream, bound: usize) -> TestTee {
        let vec: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::<u8>::new()));
        let sink: SharedOutput = vec.clone();
        let (tx, rx) = std::sync::mpsc::sync_channel(bound);
        let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let tee = TeeWriter {
            inner: Some(sink),
            stream,
            windows: Arc::new(Mutex::new(HashMap::new())),
            exact: Arc::new(Mutex::new(HashMap::new())),
            hook: Some(StreamHook {
                tx,
                dropped: dropped.clone(),
            }),
        };
        (tee, rx, dropped, vec)
    }

    #[test]
    fn hook_receives_stderr_kind_and_sink_still_gets_bytes() {
        let (mut tee, rx, dropped, sink) = tee_with_hook(TeeStream::Stderr, 8);
        tee.write_all(b"oops\n").expect("write");
        tee.flush().expect("flush");
        let chunk = rx.try_recv().expect("one chunk streamed");
        assert_eq!(chunk.kind, TeeStream::Stderr);
        assert_eq!(chunk.bytes, b"oops\n");
        assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 0);
        let guard = sink.lock().expect("sink lock");
        assert_eq!(guard.as_slice(), b"oops\n");
    }

    #[test]
    fn full_channel_drops_and_counts_without_blocking() {
        let (mut tee, rx, dropped, _sink) = tee_with_hook(TeeStream::Stdout, 1);
        tee.write_all(b"first\n").expect("write");
        tee.write_all(b"second\n")
            .expect("write must not block on full");
        assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 1);
        let kept = rx.try_recv().expect("first chunk kept");
        assert_eq!(kept.bytes, b"first\n");
    }
}