oxdock-core 0.17.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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
use std::collections::HashMap;
use std::process::ExitStatus;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

use anyhow::{Result, bail};
use oxdock_fs::GuardedPath;
use oxdock_parser::{Arg, AssertTarget, Step, StepKind, Value, guard_option_allows};
use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};

/// Create an ExitStatus from a raw exit code. Cross-platform.
fn exit_status_from_code(code: i32) -> ExitStatus {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        ExitStatus::from_raw(code << 8)
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::ExitStatusExt;
        ExitStatus::from_raw(code as u32)
    }
}

use super::handlers;
use super::io::{ExactCapture, SlidingWindow, StreamHandle};
use super::state::{ExecState, TaskEntry, TaskPhase};
use oxdock_pipe::PipeInner;

/// A background handle wrapping a `std::thread::JoinHandle` for ASYNC blocks
/// that execute commands in a background thread.
pub(super) struct ThreadJoinHandle {
    join: Option<std::thread::JoinHandle<Result<()>>>,
    cancel_token: Arc<AtomicBool>,
    active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
    /// Identity of the worker thread, published by the child on entry.
    /// Forked worker state shares the parent task registry via `Arc`, so a
    /// parent that errors out can drop its registry reference while the
    /// worker is still alive. The worker then becomes the last registry
    /// owner and would drop (and join) its own handle on thread exit, which
    /// is undefined behavior (`pthread_join` on self). Detect that case and
    /// detach instead of joining.
    worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
    /// Preserved error from the child thread, if any.
    thread_error: Option<anyhow::Error>,
}

impl ThreadJoinHandle {
    pub(super) fn new(
        join: std::thread::JoinHandle<Result<()>>,
        cancel_token: Arc<AtomicBool>,
        active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
        worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
    ) -> Self {
        Self {
            join: Some(join),
            cancel_token,
            active_process,
            worker,
            thread_error: None,
        }
    }

    /// Whether the caller is the worker thread owned by this handle.
    fn is_self(&self) -> bool {
        let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
        guard.is_some_and(|id| id == std::thread::current().id())
    }

    /// Reap the thread if finished, preserving any error.
    fn reap(&mut self) {
        if self.join.is_none() {
            return;
        }
        if self.is_self() {
            // The worker is dropping the last registry reference on its own
            // exit path (parent already tore down or errored out). Detach
            // instead of joining self, which is undefined behavior.
            let _ = self.join.take();
            return;
        }
        let handle = self.join.take().unwrap();
        match handle.join() {
            Ok(Ok(())) => {}
            Ok(Err(e)) => {
                self.thread_error = Some(e);
            }
            Err(panic) => {
                let msg = if let Some(s) = panic.downcast_ref::<&str>() {
                    s.to_string()
                } else if let Some(s) = panic.downcast_ref::<String>() {
                    s.clone()
                } else {
                    "thread panicked".to_string()
                };
                self.thread_error = Some(anyhow::anyhow!("{msg}"));
            }
        }
    }
}

impl BackgroundHandle for ThreadJoinHandle {
    fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
        if let Some(join) = &self.join {
            if join.is_finished() {
                self.reap();
            } else {
                return Ok(None);
            }
        }
        // anyhow::Error is not Clone and this method may run repeatedly,
        // so the preserved error is re-emitted rather than moved. The
        // alternate display (`{err:#}`) flattens the full causal chain
        // into the new message: `{err}` alone would drop every
        // `Caused by` layer at the ASYNC task boundary.
        if let Some(ref err) = self.thread_error {
            Err(anyhow::anyhow!("{err:#}"))
        } else {
            Ok(Some(exit_status_from_code(0)))
        }
    }

    fn kill(&mut self) -> Result<()> {
        // Signal cancellation
        self.cancel_token.store(true, Ordering::SeqCst);
        // Kill any active OS process to interrupt blocking wait
        if let Ok(mut guard) = self.active_process.lock()
            && let Some(ref mut proc) = *guard
        {
            let _ = proc.kill();
        }
        // Join the thread to ensure it completes before returning
        self.reap();
        Ok(())
    }

    fn wait(&mut self) -> Result<ExitStatus> {
        self.reap();
        // Same chain-preserving re-emit as `try_wait` above.
        if let Some(ref err) = self.thread_error {
            Err(anyhow::anyhow!("{err:#}"))
        } else {
            Ok(exit_status_from_code(0))
        }
    }
}

impl Drop for ThreadJoinHandle {
    fn drop(&mut self) {
        let _ = self.kill();
    }
}

/// Monotonically increasing generation counter for assert_windows key scoping.
/// Each execute_steps invocation gets a unique generation, preventing key
/// collisions between nested scopes (for_loop bodies, WithIo blocks).
static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);

/// Intra-thread control-flow signal (`BREAK`/`CONTINUE`/`RETURN`).
/// Produced by steps, consumed by the nearest loop (`Break`/`Continue`) or
/// `call_func` (`Return`). Anything reaching a thread boundary (`ASYNC`
/// spawn, `await` reaping) or the pipeline top becomes a step-numbered
/// error. `idx` is the 0-based index of the originating step in its own
/// body, so boundary errors can name it.
#[derive(Debug)]
pub(super) enum Flow {
    Done,
    Break { idx: usize },
    Continue { idx: usize },
    Return { idx: usize, value: Value },
}

pub(super) fn allocate_assert_generation() -> usize {
    ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
}

/// Which stream a stream-targeted assertion observes.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum AssertStream {
    Stdout,
    Stderr,
}

/// Extract the substring needle from a step asserting over a stream:
/// `ASSERT_CONTAINS stdout|stderr`, handling both top-level and
/// WITH_IO-wrapped variants. Returns the observed stream and the needle.
fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
    let step = match kind {
        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
        other => other,
    };
    match step {
        StepKind::AssertContains { haystack, needle } => match haystack {
            AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
            AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
            _ => None,
        },
        _ => None,
    }
}

/// Whether the step needs the exact-match stdout accumulator:
/// `ASSERT_EQ stdout`, top-level or WITH_IO-wrapped.
fn needs_exact_stdout(kind: &StepKind) -> bool {
    let step = match kind {
        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
        other => other,
    };
    matches!(
        step,
        StepKind::AssertEq {
            actual: AssertTarget::Stdout,
            ..
        }
    )
}

/// An assertion first argument evaluated far enough to check:
/// values stay typed, streams stay references to live buffers.
pub(super) enum ResolvedAssertTarget {
    Value(Value),
    Stdout,
    Stderr,
    Pipe(Vec<u8>),
}

/// Evaluate an assertion target. `Arg::Expr` evaluates typed;
/// strings, templates, and parts render to `String`; stream markers
/// resolve to live buffers (peeked, never consumed). A `$var` holding a
/// `PIPE` likewise peeks its backend bytes: lowering cannot know variable
/// types, so the pipe dispatch lives here where the value exists.
pub(super) fn resolve_assert_target<P: ProcessManager>(
    target: &AssertTarget,
    cx: &mut StepCtx<'_, P>,
) -> Result<ResolvedAssertTarget> {
    match target {
        AssertTarget::Value(arg) => {
            let value = super::args::evaluate_assert_operand(arg, cx)?;
            if let Some(handle) = value.as_pipe_handle() {
                let bytes =
                    cx.state.io.peek_pipe_content(&handle).map_err(|e| {
                        anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
                    })?;
                return Ok(ResolvedAssertTarget::Pipe(bytes));
            }
            Ok(ResolvedAssertTarget::Value(value))
        }
        AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
        AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
    }
}

/// Pre-register stream assertion observers so tees feed them data before
/// the steps execute. Substring needles (`ASSERT_CONTAINS stdout|stderr`)
/// get per-step `SlidingWindow`s; `ASSERT_EQ stdout` allocates the
/// generation's exact accumulator. Uses `args::resolve_arg_state` for
/// actual template expansion. Handles both top-level and WITH_IO-wrapped
/// assertions via `extract_stream_needle` / `needs_exact_stdout`.
pub(super) fn pre_register_assertions<P: ProcessManager>(
    state: &mut ExecState<P>,
    steps: &[Step],
    generation: usize,
) -> Result<()> {
    let mut windows = match state.assert_windows.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("assert_windows poisoned"),
    };
    let mut stderr_windows = match state.assert_windows_stderr.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("assert_windows_stderr poisoned"),
    };
    let mut exact = match state.exact_stdout.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("exact_stdout poisoned"),
    };
    for (idx, step) in steps.iter().enumerate() {
        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
            let resolved = super::args::resolve_arg_state(arg, state)?;
            let map = match stream {
                AssertStream::Stdout => &mut windows,
                AssertStream::Stderr => &mut stderr_windows,
            };
            map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
        }
        if needs_exact_stdout(&step.kind) {
            exact.entry(generation).or_insert_with(ExactCapture::new);
        }
    }
    Ok(())
}

/// After an environment mutation (ENV or INHERIT_ENV), re-expand all
/// substring assertion needles for the current generation to reflect new
/// env values. Preserves ring buffer history via `update_needle`. Handles
/// both top-level and WITH_IO-wrapped assertions. Exact accumulators hold
/// no needle and need no sync.
#[allow(clippy::collapsible_if)]
pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
    state: &ExecState<P>,
    steps: &[Step],
    generation: usize,
) -> Result<()> {
    let mut windows = match state.assert_windows.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("assert_windows poisoned"),
    };
    let mut stderr_windows = match state.assert_windows_stderr.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("assert_windows_stderr poisoned"),
    };
    for (idx, step) in steps.iter().enumerate() {
        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
            let map = match stream {
                AssertStream::Stdout => &mut windows,
                AssertStream::Stderr => &mut stderr_windows,
            };
            if let Some(w) = map.get_mut(&(generation, idx)) {
                let resolved = super::args::resolve_arg_state(arg, state)?;
                w.update_needle(resolved.into_bytes());
            }
        }
    }
    Ok(())
}

/// Per-step execution context handed to every command handler.
///
/// Host-registered functions receive this context: read script state through
/// the public accessors (`get_var`, `get_env`, `cwd`) and return a `Value`.
/// The fields stay crate-private so execution invariants hold for hosts.
///
/// Output contract (load-bearing for `LET`-capture, pipes, and stream assertions):
/// handlers must emit stdout/stderr ONLY through `out`/`err` — via
/// `write_stdout` or `StreamHandle::to_stdout`/`to_stderr` — and never write
/// to host stdout directly. The step runner swaps these handles per context:
/// `LET $x: STRING = <command>` installs a spillable capture sink, `WITH_IO`
/// installs named-pipe endpoints, and the root installs the assertion tee. A handler that bypasses its context handles silently breaks all three.
pub struct StepCtx<'a, P: ProcessManager> {
    pub(super) state: &'a mut ExecState<P>,
    pub(super) process: &'a mut P,
    pub(super) stdin: CommandStdin,
    pub(super) expose_stdin: bool,
    pub(super) out: Option<StreamHandle>,
    pub(super) err: Option<StreamHandle>,
    /// Pipe backend backing `out`, when a `WITH_IO` stdout binding resolved
    /// to a script pipe. Uniform context enrichment (populated for every
    /// command, read only by consumers that need the backend, like the
    /// network bridge). `None` for inherited, captured, and tee outputs,
    /// and for OS pairs (kernel bytes are invisible).
    pub(super) out_pipe: Option<Arc<PipeInner>>,
    /// Pipe backend backing `stdin`, when a `WITH_IO` stdin binding
    /// resolved to a script pipe. Lets bridge workers run timeout-bounded
    /// reads without touching shared pipe semantics (`None` for OS pairs,
    /// which fall back to blocking reads).
    pub(super) stdin_pipe: Option<Arc<PipeInner>>,
}

impl<'a, P: ProcessManager> StepCtx<'a, P> {
    /// Look up a script variable by name (innermost scope first).
    pub fn get_var(&self, key: &str) -> Option<Value> {
        self.state.get_var(key)
    }

    /// Look up an environment variable visible to the script.
    pub fn get_env(&self, key: &str) -> Option<String> {
        self.state.envs.get(key).cloned()
    }

    /// Snapshot of the script-visible environment: `ENV` assignments
    /// layered over inherited entries, as currently scoped. Hosts staging
    /// child processes layer this over the host environment (the same
    /// contract `RUN` honors through `CommandContext`), so block-scoped
    /// `ENV` reaches the child and reverts at scope exit with no extra
    /// machinery.
    pub fn env_snapshot(&self) -> HashMap<String, String> {
        self.state.envs.as_ref().clone()
    }

    /// Current working directory (guarded; stays inside the workspace).
    pub fn cwd(&self) -> &GuardedPath {
        &self.state.cwd
    }

    /// Mint a fresh unbound pipe handle, like bare `LET $p: PIPE`. The
    /// backend materializes lazily on first binding; return it from a
    /// host function to hand the DSL a pipe it can bind. Tagged with the
    /// current task so promotion checks see the declaration origin.
    pub fn new_pipe(&self) -> Value {
        Value::pipe_fresh_in_task(self.state.task_id)
    }

    /// Borrow the read half of a `PIPE` value for byte streaming (see
    /// [`PipeStream`](super::PipeStream)). Unbound handles materialize as script pipes —
    /// hosts cannot spawn `RUN`, so script is the only sensible kind,
    /// and a later `RUN` binding adapts through the shared path. DSL,
    /// bridge, and host bindings on an OS-materialized handle resolve
    /// through the single-take bridge: the first call takes, repeats bail
    /// loudly (same contract as DSL consumers; use script-backed pipes
    /// for repeat or multi access).
    pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
        use oxdock_pipe::{Materialized, materialize};
        let Some(handle) = value.as_pipe_handle() else {
            anyhow::bail!(
                "host pipe_reader needs a PIPE value, got {}",
                value.type_name()
            );
        };
        match materialize(&handle, false)? {
            Materialized::Script(backend) => Ok(backend.reader_handle()),
            #[cfg(not(miri))]
            Materialized::Os(entry) => {
                let owned = entry.reader.take().map_err(|_| {
                    anyhow::anyhow!(
                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
                    )
                })?;
                Ok(Arc::new(Mutex::new(owned)))
            }
        }
    }

    /// Borrow the write half of a `PIPE` value for byte streaming (see
    /// [`PipeStream`](super::PipeStream)). Same materialization and take-once contract as
    /// [`StepCtx::pipe_reader`].
    pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
        use oxdock_pipe::{Materialized, materialize};
        let Some(handle) = value.as_pipe_handle() else {
            anyhow::bail!(
                "host pipe_writer needs a PIPE value, got {}",
                value.type_name()
            );
        };
        match materialize(&handle, false)? {
            Materialized::Script(backend) => Ok(backend.writer_handle()),
            #[cfg(not(miri))]
            Materialized::Os(entry) => {
                let owned = entry.writer.take().map_err(|_| {
                    anyhow::anyhow!(
                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
                    )
                })?;
                Ok(Arc::new(Mutex::new(owned)))
            }
        }
    }

    /// Explicitly close a script pipe: readers drain buffered bytes, then
    /// observe EOF regardless of live writers or keeper pins. Unbound
    /// handles bail (closing a never-bound pipe is a caller bug), and
    /// OS-materialized handles bail (kernel pairs close by dropping their
    /// taken halves — drop the value instead).
    pub fn close_pipe(&self, value: &Value) -> Result<()> {
        let Some(handle) = value.as_pipe_handle() else {
            anyhow::bail!(
                "host close_pipe needs a PIPE value, got {}",
                value.type_name()
            );
        };
        let Some(backend) = oxdock_pipe::script_backend(&handle) else {
            anyhow::bail!(
                "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
            );
        };
        backend.force_close();
        Ok(())
    }

    /// Whether the current task was cancelled (`CANCEL`/`TIMEOUT`). For
    /// external host modules running blocking pumps: poll each tick so
    /// silent-but-open pipes cannot strand the task thread.
    pub fn is_cancelled(&self) -> bool {
        self.state
            .cancel_token
            .load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Whether this step runs on an `ASYNC` task thread. Blocking pumps
    /// must refuse the main sequential flow.
    pub fn is_async_task(&self) -> bool {
        self.state.inside_async
    }

    /// Resolve an explicitly passed `PIPE` value to its script backend for
    /// timeout-bounded reads (`read_into_timeout`). This is value-based on
    /// purpose: the ambient `out_pipe`/`stdin_pipe` fields only populate via
    /// engine-level `WITH_IO` resolution, which never runs for host function
    /// calls. Returns `None` for unbound and OS-materialized handles, which
    /// fall back to blocking reads.
    pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
        let handle = value.as_pipe_handle()?;
        oxdock_pipe::script_backend(&handle)
    }
}

#[allow(clippy::too_many_arguments)]
pub(super) fn execute_steps<P: ProcessManager>(
    state: &mut ExecState<P>,
    process: &mut P,
    steps: &[Step],
    stdin: CommandStdin,
    expose_stdin: bool,
    out: Option<StreamHandle>,
    err: Option<StreamHandle>,
    wait_at_end: bool,
) -> Result<Flow> {
    let generation = allocate_assert_generation();
    let flow = match execute_steps_inner(
        state,
        process,
        generation,
        steps,
        stdin,
        expose_stdin,
        out,
        err,
        wait_at_end,
    ) {
        Ok(flow) => flow,
        Err(e) => {
            // A step failed before end-of-pipeline reaping ran. Join
            // background work now so the parent owns teardown: otherwise the
            // parent drops its task-registry reference while a worker still
            // lives, leaving the worker as the last registry owner to drop
            // (and join) its own handle on thread exit.
            teardown_tasks_on_error(state);
            cleanup_assertion_generation(state, generation)?;
            return Err(e);
        }
    };
    // Cleanup: remove all assertion state for this generation
    cleanup_assertion_generation(state, generation)?;
    Ok(flow)
}

/// Remove per-generation assertion observers. Runs on success and on step
/// failure so a failed pipeline never leaks windows into later runs.
fn cleanup_assertion_generation<P: ProcessManager>(
    state: &mut ExecState<P>,
    generation: usize,
) -> Result<()> {
    let mut windows = match state.assert_windows.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("assert_windows poisoned"),
    };
    windows.retain(|(g, _), _| *g != generation);
    let mut stderr_windows = match state.assert_windows_stderr.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("assert_windows_stderr poisoned"),
    };
    stderr_windows.retain(|(g, _), _| *g != generation);
    let mut exact = match state.exact_stdout.lock() {
        Ok(guard) => guard,
        Err(_) => bail!("exact_stdout poisoned"),
    };
    exact.retain(|g, _| *g != generation);
    Ok(())
}

/// Join background work after a step failure, mirroring the end-of-pipeline
/// fail-fast teardown. Anonymous handles always belong to the current
/// thread. Named entries are root-owned: worker threads must never block on
/// sibling tasks, which may depend on the worker via AWAIT.
fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
    for survivor in state.bg_children.iter_mut() {
        let _ = survivor.kill();
    }
    state.bg_children.clear();
    if state.inside_async {
        return;
    }
    let entries: Vec<Arc<TaskEntry>> = {
        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
        named.values().cloned().collect()
    };
    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
    for entry in &entries {
        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
        match guard.phase {
            TaskPhase::Running | TaskPhase::Awaiting => {
                guard.phase = TaskPhase::Cancelled;
                if let Some(handle) = guard.handle.take() {
                    to_kill.push((Arc::clone(entry), handle));
                }
            }
            TaskPhase::Cancelled | TaskPhase::Completed => {}
        }
    }
    for (entry, mut handle) in to_kill {
        let _ = handle.kill();
        entry.finish_teardown();
    }
}

/// Execute a single step with an explicit generation and index.
/// Used by `with_io` to preserve the parent step's index for assertion window keys.
#[allow(clippy::too_many_arguments)]
pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
    state: &mut ExecState<P>,
    process: &mut P,
    cmd: &StepKind,
    generation: usize,
    idx: usize,
    stdin: CommandStdin,
    expose_stdin: bool,
    out: Option<StreamHandle>,
    err: Option<StreamHandle>,
    out_pipe: Option<Arc<PipeInner>>,
    stdin_pipe: Option<Arc<PipeInner>>,
) -> Result<Flow> {
    let mut cx = StepCtx {
        state,
        process,
        stdin,
        expose_stdin,
        out,
        err,
        out_pipe,
        stdin_pipe,
    };
    // Compound steps (loops, functions, scoped wrappers) participate in
    // Flow and dispatch through the Flow path; every other variant runs
    // the leaf pipeline below and yields Done.
    match cmd {
        StepKind::FuncDef { .. }
        | StepKind::Call { .. }
        | StepKind::Return { .. }
        | StepKind::While { .. }
        | StepKind::Break
        | StepKind::Continue
        | StepKind::For { .. }
        | StepKind::If { .. }
        | StepKind::Timeout { .. }
        | StepKind::WithIo { .. }
        | StepKind::AssignCapture { .. } => {
            return dispatch_flow_step(cmd, &mut cx, generation, idx);
        }
        _ => {}
    }
    match cmd {
        StepKind::Run(arg) => {
            let cmd = super::args::resolve_arg(arg, &mut cx)?;
            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
            handlers::run(&mut cx, idx, &cmd)
        }
        StepKind::RunExec { argv } => {
            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
            handlers::run_argv(&mut cx, idx, &resolved)
        }
        StepKind::Echo(arg) => {
            let msg = super::args::resolve_arg(arg, &mut cx)?;
            handlers::echo(&mut cx, &msg)
        }
        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
        StepKind::Workdir(arg) => {
            let path = super::args::resolve_arg(arg, &mut cx)?;
            handlers::workdir(&mut cx, idx, &path)
        }
        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
        StepKind::Env { key, value } => {
            let resolved = super::args::resolve_arg(value, &mut cx)?;
            handlers::env(&mut cx, key, &resolved)
        }
        StepKind::InheritEnv { keys } => {
            handlers::inherit_env(&mut cx, keys)?;
            sync_iteration_assert_needles(
                cx.state,
                &[Step {
                    guard: None,
                    kind: cmd.clone(),
                    scope_enter: 0,
                    scope_exit: 0,
                }],
                generation,
            )?;
            Ok(())
        }
        StepKind::Copy {
            from_current_workspace,
            from,
            to,
        } => {
            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
            handlers::copy(
                &mut cx,
                idx,
                *from_current_workspace,
                &from_resolved,
                &to_resolved,
            )
        }
        StepKind::CopyGit {
            rev,
            from,
            to,
            include_dirty,
        } => {
            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
            handlers::copy_git(
                &mut cx,
                idx,
                &rev_resolved,
                &from_resolved,
                &to_resolved,
                *include_dirty,
            )
        }
        StepKind::HashSha256 { path } => {
            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
            handlers::hash_sha256(&mut cx, idx, &path_resolved)
        }
        StepKind::Symlink { from, to } => {
            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
            handlers::symlink(&mut cx, idx, &from_resolved, &to_resolved)
        }
        StepKind::Mkdir(arg) => {
            let path = super::args::resolve_arg(arg, &mut cx)?;
            handlers::mkdir(&mut cx, idx, &path)
        }
        StepKind::Ls(arg) => {
            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
            handlers::ls(&mut cx, idx, &resolved)
        }
        StepKind::Cwd => handlers::cwd(&mut cx, idx),
        StepKind::Read(arg) => {
            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
            handlers::read(&mut cx, idx, &resolved)
        }
        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
        StepKind::ListAppend { list, item } => {
            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
            handlers::push_into(&mut cx, idx, list, value)
        }
        StepKind::Write { path, contents } => {
            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
            handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
        }
        StepKind::Append { path, contents } => {
            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
            handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
        }
        StepKind::Expand { path, overrides } => {
            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
        }
        StepKind::AssertEq {
            hash,
            actual,
            expected,
        } => {
            let target = resolve_assert_target(actual, &mut cx)?;
            let expected_resolved = match expected {
                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
                None => None,
            };
            handlers::assert_eq(
                &mut cx,
                idx,
                generation,
                idx,
                hash,
                &target,
                expected_resolved.as_ref(),
            )
        }
        StepKind::AssertContains { haystack, needle } => {
            let target = resolve_assert_target(haystack, &mut cx)?;
            handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
        }
        StepKind::WithIoBlock { .. } => {
            bail!("WITH_IO block should have been expanded during parsing")
        }
        StepKind::Exit(code) => {
            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
            handlers::exit(&mut cx, code)
        }
        StepKind::Assign {
            var,
            decl_type,
            expr,
        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
        StepKind::AssignAsync {
            var,
            decl_type,
            body,
        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
        StepKind::AwaitCapture {
            out_var,
            out_type,
            task_var,
        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
        StepKind::Sleep { duration } => {
            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
            handlers::sleep(&mut cx, idx, &duration)
        }
        StepKind::FuncDef { .. }
        | StepKind::Call { .. }
        | StepKind::Return { .. }
        | StepKind::While { .. }
        | StepKind::Break
        | StepKind::Continue
        | StepKind::For { .. }
        | StepKind::If { .. }
        | StepKind::Timeout { .. }
        | StepKind::WithIo { .. }
        | StepKind::AssignCapture { .. } => {
            unreachable!("compound steps dispatch before this match")
        }
    }?;
    Ok(Flow::Done)
}

#[allow(clippy::too_many_arguments)]
fn execute_steps_inner<P: ProcessManager>(
    state: &mut ExecState<P>,
    process: &mut P,
    generation: usize,
    steps: &[Step],
    stdin: CommandStdin,
    expose_stdin: bool,
    out: Option<StreamHandle>,
    err: Option<StreamHandle>,
    wait_at_end: bool,
) -> Result<Flow> {
    // Pre-register assertion windows for this generation
    pre_register_assertions(state, steps, generation)?;

    for (idx, step) in steps.iter().enumerate() {
        // Check for cancellation before each step
        if state.cancel_token.load(Ordering::SeqCst) {
            bail!("ASYNC task cancelled");
        }
        if step.scope_enter > 0 {
            for _ in 0..step.scope_enter {
                state.push_scope();
            }
        }

        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
        let flow_result: Result<Flow> = if !should_run {
            Ok(Flow::Done)
        } else {
            let mut cx = StepCtx {
                state,
                process,
                stdin: stdin.clone(),
                expose_stdin,
                out: out.clone(),
                err: err.clone(),
                out_pipe: None,
                stdin_pipe: None,
            };
            // Function/loop control steps dispatch through the Flow path;
            // every other variant runs the leaf pipeline and yields Done.
            let flow_result: Result<Flow> = match &step.kind {
                StepKind::FuncDef { .. }
                | StepKind::Call { .. }
                | StepKind::Return { .. }
                | StepKind::While { .. }
                | StepKind::Break
                | StepKind::Continue
                | StepKind::For { .. }
                | StepKind::If { .. }
                | StepKind::Timeout { .. }
                | StepKind::WithIo { .. }
                | StepKind::AssignCapture { .. } => {
                    dispatch_flow_step(&step.kind, &mut cx, generation, idx)
                }
                _ => {
                    match &step.kind {
                        StepKind::InheritEnv { keys } => {
                            handlers::inherit_env(&mut cx, keys)?;
                            sync_iteration_assert_needles(cx.state, steps, generation)?;
                            Ok(())
                        }
                        StepKind::Workdir(arg) => {
                            let path = super::args::resolve_arg(arg, &mut cx)?;
                            handlers::workdir(&mut cx, idx, &path)
                        }
                        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
                        StepKind::Env { key, value } => {
                            let resolved = super::args::resolve_arg(value, &mut cx)?;
                            handlers::env(&mut cx, key, &resolved)?;
                            sync_iteration_assert_needles(cx.state, steps, generation)?;
                            Ok(())
                        }
                        StepKind::Run(arg) => {
                            let cmd = super::args::resolve_arg(arg, &mut cx)?;
                            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
                            handlers::run(&mut cx, idx, &cmd)
                        }
                        StepKind::RunExec { argv } => {
                            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
                            handlers::run_argv(&mut cx, idx, &resolved)
                        }
                        StepKind::Echo(arg) => {
                            let msg = super::args::resolve_arg(arg, &mut cx)?;
                            handlers::echo(&mut cx, &msg)
                        }
                        StepKind::AsyncBlock { .. } => {
                            handlers::dispatch_async_block(&step.kind, &mut cx)
                        }
                        StepKind::Copy {
                            from_current_workspace,
                            from,
                            to,
                        } => {
                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
                            handlers::copy(
                                &mut cx,
                                idx,
                                *from_current_workspace,
                                &from_resolved,
                                &to_resolved,
                            )
                        }
                        StepKind::CopyGit {
                            rev,
                            from,
                            to,
                            include_dirty,
                        } => {
                            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
                            handlers::copy_git(
                                &mut cx,
                                idx,
                                &rev_resolved,
                                &from_resolved,
                                &to_resolved,
                                *include_dirty,
                            )
                        }
                        StepKind::HashSha256 { path } => {
                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
                            handlers::hash_sha256(&mut cx, idx, &path_resolved)
                        }
                        StepKind::Symlink { from, to } => {
                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
                            handlers::symlink(&mut cx, idx, &from_resolved, &to_resolved)
                        }
                        StepKind::Mkdir(arg) => {
                            let path = super::args::resolve_arg(arg, &mut cx)?;
                            handlers::mkdir(&mut cx, idx, &path)
                        }
                        StepKind::Ls(arg) => {
                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
                            handlers::ls(&mut cx, idx, &resolved)
                        }
                        StepKind::Cwd => handlers::cwd(&mut cx, idx),
                        StepKind::Read(arg) => {
                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
                            handlers::read(&mut cx, idx, &resolved)
                        }
                        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
                        StepKind::ListAppend { list, item } => {
                            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
                            handlers::push_into(&mut cx, idx, list, value)
                        }
                        StepKind::Write { path, contents } => {
                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
                            let contents_resolved =
                                super::args::resolve_arg_opt(contents, &mut cx)?;
                            handlers::write(
                                &mut cx,
                                idx,
                                &path_resolved,
                                contents_resolved.as_deref(),
                            )
                        }
                        StepKind::Append { path, contents } => {
                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
                            let contents_resolved =
                                super::args::resolve_arg_opt(contents, &mut cx)?;
                            handlers::append(
                                &mut cx,
                                idx,
                                &path_resolved,
                                contents_resolved.as_deref(),
                            )
                        }
                        StepKind::Expand { path, overrides } => {
                            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
                            let overrides_resolved =
                                super::args::resolve_overrides(overrides, &mut cx)?;
                            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
                        }
                        StepKind::AssertEq {
                            hash,
                            actual,
                            expected,
                        } => {
                            let target = resolve_assert_target(actual, &mut cx)?;
                            let expected_resolved = match expected {
                                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
                                None => None,
                            };
                            handlers::assert_eq(
                                &mut cx,
                                idx,
                                generation,
                                idx,
                                hash,
                                &target,
                                expected_resolved.as_ref(),
                            )
                        }
                        StepKind::AssertContains { haystack, needle } => {
                            let target = resolve_assert_target(haystack, &mut cx)?;
                            handlers::assert_contains(
                                &mut cx, idx, generation, idx, &target, needle,
                            )
                        }
                        StepKind::WithIoBlock { .. } => {
                            bail!("WITH_IO block should have been expanded during parsing")
                        }
                        StepKind::Exit(code) => {
                            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
                            handlers::exit(&mut cx, code)
                        }
                        StepKind::Assign {
                            var,
                            decl_type,
                            expr,
                        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
                        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
                        StepKind::AssignAsync {
                            var,
                            decl_type,
                            body,
                        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
                        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
                        StepKind::AwaitCapture {
                            out_var,
                            out_type,
                            task_var,
                        } => handlers::dispatch_await_capture(
                            out_var,
                            out_type.clone(),
                            task_var,
                            &mut cx,
                        ),
                        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
                        StepKind::Sleep { duration } => {
                            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
                            handlers::sleep(&mut cx, idx, &duration)
                        }
                        StepKind::FuncDef { .. }
                        | StepKind::Call { .. }
                        | StepKind::Return { .. }
                        | StepKind::While { .. }
                        | StepKind::Break
                        | StepKind::Continue
                        | StepKind::For { .. }
                        | StepKind::If { .. }
                        | StepKind::Timeout { .. }
                        | StepKind::WithIo { .. }
                        | StepKind::AssignCapture { .. } => {
                            unreachable!("compound steps dispatch in the outer match")
                        }
                    }?;
                    Ok(Flow::Done)
                }
            };
            flow_result
        };

        let restore_result = restore_scopes(state, step.scope_exit);
        // Keeper expiry: drop spawn-time pins whose final producer step
        // just completed, so later consumer steps in the same task observe
        // EOF. Gated on slice identity, so nested bodies executing through
        // this same loop never discharge the worker's top-level map.
        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
            expiry.expire_step(steps, idx)
        } else {
            false
        };
        if expiry_drained {
            state.keeper_expiry = None;
        }
        let flow = flow_result?;
        restore_result?;
        match flow {
            Flow::Done => {}
            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
                return Ok(flow);
            }
        }
    }

    // Poll anonymous background handles at end-of-pipeline. The shared
    // named_tasks entries are reaped only by the root context: task threads
    // must never block on sibling tasks, which may depend on this thread
    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
    // reaped by the root end-poll, and explicitly awaited tasks join via
    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
    // later AWAIT/CANCEL report precise errors.
    let reap_named = !state.inside_async;
    let has_bg = !state.bg_children.is_empty();
    let named_pending = |state: &ExecState<P>| {
        reap_named
            && state
                .named_tasks
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .values()
                .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
    };
    let has_named = named_pending(state);
    if wait_at_end && (has_bg || has_named) {
        loop {
            let mut failed_status: Option<anyhow::Error> = None;

            // Cancellation (deadline watcher or parent teardown) must break
            // the poll loop: without this, a stuck background handle would
            // hang the reaper forever. Flows into the shared fail-fast
            // teardown below.
            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
            }

            // 1. Poll anonymous background handles
            let mut i = 0;
            while i < state.bg_children.len() {
                match state.bg_children[i].try_wait() {
                    Ok(Some(status)) => {
                        if !status.success() && failed_status.is_none() {
                            failed_status =
                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
                            break;
                        }
                        state.bg_children.swap_remove(i);
                    }
                    Ok(None) => {
                        i += 1;
                    }
                    Err(e) => {
                        if failed_status.is_none() {
                            failed_status = Some(e);
                        }
                        break;
                    }
                }
            }

            // 2. Poll un-awaited named tasks (root context only). Each entry
            // is probed under a short entry lock; terminal entries are
            // retained as tombstones, never removed.
            if failed_status.is_none() && reap_named {
                let entries: Vec<(u64, Arc<TaskEntry>)> = {
                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
                    named
                        .iter()
                        .map(|(id, entry)| (*id, Arc::clone(entry)))
                        .collect()
                };
                for (id, entry) in &entries {
                    enum Poll {
                        Pending,
                        CompletedOk,
                        CompletedErr(anyhow::Error),
                    }
                    let poll = {
                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
                        match guard.phase {
                            TaskPhase::Running | TaskPhase::Awaiting => {
                                match guard.handle.as_mut() {
                                    Some(handle) => match handle.try_wait() {
                                        Ok(Some(status)) => {
                                            let _ = guard.handle.take();
                                            guard.phase = TaskPhase::Completed;
                                            if status.success() {
                                                Poll::CompletedOk
                                            } else {
                                                Poll::CompletedErr(anyhow::anyhow!(
                                                    "named ASYNC task {id} exited with status {status}"
                                                ))
                                            }
                                        }
                                        Ok(None) => Poll::Pending,
                                        Err(e) => {
                                            let _ = guard.handle.take();
                                            guard.phase = TaskPhase::Completed;
                                            Poll::CompletedErr(e)
                                        }
                                    },
                                    // Handle taken by a concurrent CANCEL/AWAIT
                                    // teardown; the barrier below rendezvouses.
                                    None => Poll::Pending,
                                }
                            }
                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
                        }
                    };
                    match poll {
                        Poll::Pending => {}
                        Poll::CompletedOk => {
                            entry.finish_teardown();
                        }
                        Poll::CompletedErr(e) => {
                            entry.finish_teardown();
                            if failed_status.is_none() {
                                failed_status = Some(e);
                            }
                            break;
                        }
                    }
                }
            }

            // 3. Fail-fast teardown (named entries are root-owned; task
            // threads only tear down their own anonymous children).
            // Handles are taken under short locks and killed outside every
            // lock; tombstones are retained.
            if let Some(err) = failed_status {
                for survivor in state.bg_children.iter_mut() {
                    let _ = survivor.kill();
                }
                if reap_named {
                    let entries: Vec<Arc<TaskEntry>> = {
                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
                        named.values().cloned().collect()
                    };
                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
                    for entry in &entries {
                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
                        match guard.phase {
                            TaskPhase::Running | TaskPhase::Awaiting => {
                                guard.phase = TaskPhase::Cancelled;
                                if let Some(handle) = guard.handle.take() {
                                    to_kill.push((Arc::clone(entry), handle));
                                }
                            }
                            TaskPhase::Cancelled | TaskPhase::Completed => {}
                        }
                    }
                    for (entry, mut handle) in to_kill {
                        let _ = handle.kill();
                        entry.finish_teardown();
                    }
                }
                state.bg_children.clear();
                return Err(err);
            }

            let bg_empty = state.bg_children.is_empty();
            if bg_empty && !named_pending(state) {
                return Ok(Flow::Done);
            }
            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
            // own teardown of a Cancelled-but-unreaped entry. Wait for it
            // instead of spinning, so this thread never outruns the join.
            if reap_named {
                let unreaped: Vec<Arc<TaskEntry>> = {
                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
                    named
                        .values()
                        .filter(|entry| {
                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
                        })
                        .cloned()
                        .collect()
                };
                for entry in &unreaped {
                    entry.wait_reaped();
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    Ok(Flow::Done)
}

fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
    for _ in 0..count {
        state.pop_scope()?;
    }
    Ok(())
}

/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
/// filesystem effects cross. Restores even when the body fails. Propagates
/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
#[allow(clippy::too_many_arguments)]
pub(super) fn execute_scoped_steps<P: ProcessManager>(
    state: &mut ExecState<P>,
    process: &mut P,
    steps: &[Step],
    stdin: CommandStdin,
    expose_stdin: bool,
    out: Option<StreamHandle>,
    err: Option<StreamHandle>,
    wait_at_end: bool,
) -> Result<Flow> {
    state.push_scope();
    let res = execute_steps(
        state,
        process,
        steps,
        stdin,
        expose_stdin,
        out,
        err,
        wait_at_end,
    );
    // Restore the scope even when the body failed, but never let an
    // unwinding failure mask the body's own error.
    let pop_res = state.pop_scope();
    match (res, pop_res) {
        (Ok(flow), Ok(())) => Ok(flow),
        (Err(e), _) => Err(e),
        (Ok(_), Err(e)) => Err(e),
    }
}

/// Dispatch one compound step (loops, functions, scoped wrappers) through
/// the Flow path. Called with the caller's generation/idx so assertion
/// windows and error attribution match the leaf pipeline.
fn dispatch_flow_step<P: ProcessManager>(
    cmd: &StepKind,
    cx: &mut StepCtx<'_, P>,
    generation: usize,
    idx: usize,
) -> Result<Flow> {
    match cmd {
        StepKind::FuncDef { name, params, body } => {
            handlers::define_func(cx, name, params, body)?;
            Ok(Flow::Done)
        }
        StepKind::Call { name, args } => {
            let _ = handlers::call_func_value(cx, idx, name, args)?;
            Ok(Flow::Done)
        }
        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
        StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
        StepKind::Break => Ok(Flow::Break { idx }),
        StepKind::Continue => Ok(Flow::Continue { idx }),
        StepKind::For {
            key_var,
            key_type,
            var,
            var_type,
            in_expr,
            body,
        } => handlers::for_loop(
            cx,
            key_var.as_deref(),
            key_type.clone(),
            var,
            var_type.clone(),
            in_expr,
            body,
        ),
        StepKind::If {
            cond,
            then_body,
            else_ifs,
            else_body,
        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
        StepKind::Timeout { duration, body } => {
            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
            handlers::timeout(cx, idx, &duration, body)
        }
        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
        StepKind::AssignCapture {
            var,
            decl_type,
            cmd,
        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
        _ => {
            unreachable!("dispatch_flow_step handles only compound steps")
        }
    }
}