oxdock-core 0.24.4-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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
//! Run-start static type pass for scripts: top-level steps and every
//! script `FUNC` body.
//!
//! Host signatures are enforced at the boundary by macro-generated
//! extractors; this pass is the script-side counterpart. It runs once
//! per run from `finish_run`, before the first step executes, and
//! fails fast on what execution would otherwise discover late:
//! missing returns, disjoint branch types, undeclared variables, and
//! values flowing into typed parameters without a coercion gate.
//!
//! Top-level steps are checked with an empty environment: undeclared
//! variables, bad arities, and mistyped arguments fail at run start
//! whether they sit at the top level or inside a function. A top-level
//! `RETURN` fails here with the same boundary message execution would
//! produce.
//!
//! The rules, in full:
//!
//! - Every terminal `RETURN` path of a `FUNC` body must unify to one
//!   type (`T` + `T` = `T`; anything + `ANY` = `ANY`; disjoint
//!   concrete types fail naming both). `EXIT` ends a path without
//!   contributing a type.
//! - A body with a `RETURN` on some live path but reachable
//!   fallthrough fails with `MissingReturn`. A body with no live
//!   `RETURN` is `VOID`; `VOID` never defaults to `STRING`.
//! - Guards classify statically: absent or `[bool:true]` is
//!   unconditional; `[bool:false]` is statically unreachable and
//!   excluded from classification, unification, completeness, and
//!   checking entirely; every other guard is conditional. Loops never
//!   satisfy completeness (zero-trip); a `RETURN` solely inside a loop
//!   needs an unconditional fallback after it.
//! - Environments are flow-sensitive and sequential: `LET` declares,
//!   `SET` keeps the declared type (runtime coerces), branches fork
//!   and discard (arm declarations are scope-local at runtime, so no
//!   merge is needed — discarding is exact, not conservative).
//! - `ANY` widens unidirectionally only. An `ANY`-typed argument into
//!   a concrete parameter fails naming the `LET $x: T` gate; an
//!   `ANY`-returning call assigned to `LET $x: T` is allowed because
//!   `declare_var` coercion is the gate.
//! - Every statement argument participates: `Arg::Expr` operands and
//!   `{{ }}` fragments inside `Arg::Parts` read through inference,
//!   and task-handle (`AWAIT`, `CANCEL`, `AWAIT`-capture), pipe
//!   (`WITH_IO` bindings), and list (`LIST_APPEND`) names read
//!   through site-aware liveness with their runtime type rules
//!   (`PIPE`/`LIST` exactly). Plain `Arg::String` text stays
//!   unchecked by design: `{{ }}` there expands missing names to
//!   empty at runtime and never errors, so rejecting it would be a
//!   false positive.
//!
//! Performance: single traversal, no fixpoint, no I/O, no registry
//! writes. Branch forks clone a map of live vars; the merge walk
//! would cost O(vars) regardless, so overlays would save nothing
//! measurable. `MAX_STATIC_DEPTH` caps nesting with a static error.

use std::collections::HashMap;

use anyhow::{Result, bail};
use oxdock_parser::{
    CompareOp, Expr, GuardExpr, IoBinding, MathOp, PipeTarget, Step, StepKind, TypeTag, Value,
    render_structural,
};
use oxdock_process::ProcessManager;

use super::{ExecState, FuncMeta, FuncParam, required_arity};

/// Maximum expression nesting and nested-body descent. Parser-bounded
/// scripts never approach it; hand-built ASTs cannot wedge the pass.
/// Exceeding it is a static error, never silent truncation.
pub const MAX_STATIC_DEPTH: usize = 64;

/// Static guard classification. Only unconditional steps terminate
/// paths; only dead steps are skipped.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum GuardClass {
    Unconditional,
    Conditional,
    Dead,
}

/// Inferred static type: a tag, `ANY` (as `TypeTag::Any`), or `VOID`
/// for bodies with no `RETURN`. `VOID` is pass-level only, never a
/// value tag.
#[derive(Clone, Copy, Debug)]
enum StaticTy {
    Ty(TypeTag),
    Void,
}

/// One collected script function: resolved params plus body.
#[derive(Clone)]
struct FuncInfo {
    params: Vec<(String, TypeTag)>,
    body: Vec<Step>,
}

/// Lexical environment: a stack of frames mirroring the runtime
/// `var_scopes`. Frames push on `scope_enter` markers, branch and
/// loop bodies, and function entries; they pop on `scope_exit` or are
/// discarded with a fork. `LET` declares in the top frame only (a
/// duplicate there mirrors the runtime redeclaration error);
/// shadowing an outer frame is legal exactly where the runtime
/// pushes a scope. `SET` and reads walk outward; types never change
/// on mutation (runtime coerces).
/// One live declaration: its tag plus the guard it was declared
/// under. Same-scope duplicates with disjoint guards coexist (only
/// one path ever binds); reads unify across entries since the path
/// is unknowable statically.
#[derive(Clone, Debug)]
struct Binding {
    tag: TypeTag,
    guard: Option<GuardExpr>,
}

#[derive(Clone, Default, Debug)]
struct Env {
    frames: Vec<HashMap<String, Vec<Binding>>>,
}

/// Where a `RETURN`/`BREAK`/`CONTINUE` may legally land, mirroring
/// the runtime boundary errors one for one.
#[derive(Clone, Debug)]
enum RetCtx {
    Top,
    Func(String),
    Block,
    AsyncValue,
    AsyncStmt,
}

/// Walk context: message label, return boundary, loop depth,
/// plus the current step's guard for site-aware reads.
/// `BREAK`/`CONTINUE` are legal only with `loops > 0`; blocks,
/// functions, and tasks reset it (control never crosses those
/// boundaries at runtime).
#[derive(Clone)]
struct Scope<'x> {
    label: &'x str,
    ret: RetCtx,
    loops: usize,
    site: Option<GuardExpr>,
}

/// The pass state: collected functions, host metas, inference
/// memoization, recursion guard, and the linearity counter.
struct Checker<'a, P: ProcessManager> {
    exec: &'a ExecState<P>,
    funcs: HashMap<String, FuncInfo>,
    hosts: HashMap<String, FuncMeta>,
    inferred: HashMap<String, StaticTy>,
    inferring: Vec<String>,
    visits: u64,
}

/// Run the static pass over top-level steps plus every collected
/// script function. Fails before the first step executes.
pub fn validate_script_types<P: ProcessManager>(steps: &[Step], exec: &ExecState<P>) -> Result<()> {
    let mut checker = Checker::new(exec);
    checker.collect(steps)?;
    checker.check_top_level(steps)?;
    for key in checker.func_keys() {
        checker.func_return(&key, 0)?;
    }
    Ok(())
}

/// Same pass returning the visit count, for the linearity test: the
/// count must stay proportional to input size on adversarial input.
/// Test-only: production calls `validate_script_types`.
#[cfg(test)]
pub fn validate_script_types_counted<P: ProcessManager>(
    steps: &[Step],
    exec: &ExecState<P>,
) -> Result<u64> {
    let mut checker = Checker::new(exec);
    checker.collect(steps)?;
    checker.check_top_level(steps)?;
    for key in checker.func_keys() {
        checker.func_return(&key, 0)?;
    }
    Ok(checker.visits)
}

/// Pointer-identity-aware tag equality. `TypeTag` carries no
/// `PartialEq` (descriptors are unsized vtables), and structural
/// comparison would equate distinct registrations; descriptors are
/// `'static` singletons, so pointer equality is the sound rule.
fn tags_equal(left: &TypeTag, right: &TypeTag) -> bool {
    match (left, right) {
        (TypeTag::String, TypeTag::String)
        | (TypeTag::Int, TypeTag::Int)
        | (TypeTag::Float, TypeTag::Float)
        | (TypeTag::Bool, TypeTag::Bool)
        | (TypeTag::List, TypeTag::List)
        | (TypeTag::Map, TypeTag::Map)
        | (TypeTag::Pipe, TypeTag::Pipe)
        | (TypeTag::Handle, TypeTag::Handle)
        | (TypeTag::Duration, TypeTag::Duration)
        | (TypeTag::Path, TypeTag::Path)
        | (TypeTag::Semaphore, TypeTag::Semaphore)
        | (TypeTag::Permit, TypeTag::Permit)
        | (TypeTag::Any, TypeTag::Any) => true,
        (TypeTag::Custom(a), TypeTag::Custom(b)) => std::ptr::eq(*a, *b),
        (TypeTag::ListOf(a), TypeTag::ListOf(b)) => tags_equal(a, b),
        (TypeTag::MapOf(a), TypeTag::MapOf(b)) => tags_equal(a, b),
        (TypeTag::Record(a), TypeTag::Record(b)) => std::ptr::eq(*a, *b),
        _ => false,
    }
}

/// Map-kind tags: bare words, fixed shapes, and value shapes alike.
/// Literals whose every element is maplike join to the unknown map
/// shape instead of collapsing to a bare list.
fn is_maplike(tag: &TypeTag) -> bool {
    matches!(tag, TypeTag::Map | TypeTag::Record(_) | TypeTag::MapOf(_))
}

/// List-kind tags, mirroring [`is_maplike`] for nested lists.
fn is_listlike(tag: &TypeTag) -> bool {
    matches!(tag, TypeTag::List | TypeTag::ListOf(_))
}

/// Unify two terminal types: equal stays, any `ANY` widens to `ANY`
/// (unidirectional — `ANY` never narrows to concrete), disjoint
/// concrete types fail naming both.
fn unify(left: TypeTag, right: TypeTag, ctx: &str) -> Result<TypeTag> {
    if tags_equal(&left, &right) {
        return Ok(left);
    }
    if matches!(left, TypeTag::Any) || matches!(right, TypeTag::Any) {
        return Ok(TypeTag::Any);
    }
    // Same-kind containment: a shaped value IS its bare word, so mixed
    // branches widen to the general tag instead of failing. Narrowing
    // never happens here: unknown shapes never unify INTO fixed ones.
    if matches!(
        (&left, &right),
        (TypeTag::ListOf(_), TypeTag::List) | (TypeTag::List, TypeTag::ListOf(_))
    ) {
        return Ok(TypeTag::List);
    }
    if matches!(
        (&left, &right),
        (TypeTag::Record(_), TypeTag::Map)
            | (TypeTag::Map, TypeTag::Record(_))
            | (TypeTag::Record(_), TypeTag::MapOf(_))
            | (TypeTag::MapOf(_), TypeTag::Record(_))
            | (TypeTag::MapOf(_), TypeTag::Map)
            | (TypeTag::Map, TypeTag::MapOf(_))
    ) {
        return Ok(TypeTag::Map);
    }
    bail!(
        "{ctx}: cannot unify {} and {}",
        render_structural(&left),
        render_structural(&right)
    );
}

fn classify_guard(guard: Option<&GuardExpr>) -> GuardClass {
    match guard {
        None => GuardClass::Unconditional,
        Some(expr) => {
            if !oxdock_parser::guard_satisfiable(expr) {
                // Unsatisfiable (e.g. `[os:macos]` + `[os:windows]` on one
                // step): never executes, excluded everywhere.
                GuardClass::Dead
            } else if oxdock_parser::guard_valid(expr) {
                GuardClass::Unconditional
            } else {
                GuardClass::Conditional
            }
        }
    }
}

/// Strip the `$` sigil the way execution does (`assign`/`set_var_value`
/// trim it before registry calls), so lookups match declarations
/// regardless of spelling.
fn clean_var(name: &str) -> String {
    name.trim_start_matches('$').to_string()
}

/// Display form of a callee name: the runtime boundary messages use
/// the bare name (`INT()`), never the qualified registry key.
fn base_name(name: &str) -> &str {
    name.rsplit("::").next().unwrap_or(name)
}

/// Step prefix, or empty for RPN contexts whose runtime errors carry
/// no step number.
fn loc(at: Option<&str>) -> String {
    at.map(|s| format!("{s}: ")).unwrap_or_default()
}

/// Resolved callee for one call: parameter shapes (absent when the
/// entry declares none), return type, and host closed-set metadata.
struct Callee {
    params: Option<Vec<(String, TypeTag)>>,
    ret: StaticTy,
    host_params: Option<Vec<FuncParam>>,
}

/// Outcome of walking one body: whether fallthrough is reachable,
/// whether a live `RETURN` exists on some path, and the collected
/// terminal types.
struct WalkOut {
    falls_through: bool,
    has_return: bool,
    types: Vec<TypeTag>,
}

impl Env {
    fn one_frame(bindings: Vec<(String, TypeTag)>) -> Self {
        let mut top = HashMap::new();
        for (name, tag) in bindings {
            top.insert(name, vec![Binding { tag, guard: None }]);
        }
        Self { frames: vec![top] }
    }

    /// Fork for a scoped body: clone the stack and push a fresh frame,
    /// mirroring `push_scope`. Discarding the fork is exact — arm and
    /// loop declarations never leak at runtime.
    fn fork(&self) -> Self {
        let mut fork = self.clone();
        fork.frames.push(HashMap::new());
        fork
    }

    /// Read a binding under a read-site guard: first frame outward
    /// holding the name wins (shadowing); only entries overlapping
    /// the site are live on that path, and they unify. No overlap
    /// means the name is never bound where the read executes — the
    /// same undeclared error runtime would produce there.
    fn read_guarded(&self, key: &str, site: Option<&GuardExpr>) -> Result<TypeTag> {
        Ok(self.read_entry_guarded(key, site)?.0)
    }

    /// Same as `read_guarded`, plus the precise liveness guard for
    /// re-seeding (REMOTE headers): the union of surviving entry
    /// guards conjoined with the site. A value crossing scopes is
    /// live exactly where both hold.
    fn read_entry_guarded(
        &self,
        key: &str,
        site: Option<&GuardExpr>,
    ) -> Result<(TypeTag, Option<GuardExpr>)> {
        for frame in self.frames.iter().rev() {
            if let Some(entries) = frame.get(key) {
                let live: Vec<&Binding> = entries
                    .iter()
                    .filter(|entry| oxdock_parser::guards_overlap(entry.guard.as_ref(), site))
                    .collect();
                if live.is_empty() {
                    bail!("undefined variable ${key}");
                }
                // Coverage: an unguarded live entry fires everywhere,
                // otherwise the site must imply the disjunction of
                // live binding guards. That is, site AND NOT(each
                // live guard) must be unsatisfiable — else some
                // reachable path reads unbound.
                let any_bare = live.iter().any(|entry| entry.guard.is_none());
                if !any_bare {
                    let mut atoms: Vec<GuardExpr> = Vec::new();
                    if let Some(site_expr) = site {
                        atoms.push(site_expr.clone());
                    }
                    for entry in &live {
                        if let Some(guard) = entry.guard.as_ref() {
                            atoms.push(GuardExpr::Not(Box::new(guard.clone())));
                        }
                    }
                    if oxdock_parser::guard_satisfiable(&GuardExpr::All(atoms)) {
                        bail!(
                            "variable '${key}' is not guaranteed to be defined on all reachable paths for this step"
                        );
                    }
                }
                let mut unified: Option<TypeTag> = None;
                let mut union: Option<GuardExpr> = None;
                for entry in live {
                    unified = Some(match unified {
                        None => entry.tag,
                        Some(acc) => {
                            unify(acc, entry.tag, &format!("${key} across platform guards"))?
                        }
                    });
                    union = match (union, entry.guard.clone()) {
                        (None, None) => None,
                        (Some(g), None) | (None, Some(g)) => Some(g),
                        (Some(g1), Some(g2)) => Some(GuardExpr::Or(vec![g1, g2])),
                    };
                }
                let guard = match (site.cloned(), union) {
                    (None, union) => union,
                    (Some(site), None) => Some(site),
                    (Some(site), Some(union)) => Some(GuardExpr::All(vec![site, union])),
                };
                return Ok((unified.expect("live never empty"), guard));
            }
        }
        bail!("undefined variable ${key}");
    }

    fn is_declared(&self, key: &str) -> bool {
        self.frames
            .iter()
            .rev()
            .any(|frame| frame.contains_key(key))
    }

    /// Declare in the top frame. A duplicate whose guard overlaps any
    /// live entry mirrors the runtime redeclaration error; a disjoint
    /// one (e.g. `[os:windows]` after `[os:macos]`) shadows across exclusive
    /// paths and is allowed.
    fn declare(
        &mut self,
        key: String,
        tag: TypeTag,
        guard: Option<&GuardExpr>,
        idx: usize,
    ) -> Result<()> {
        if let Some(frame) = self.frames.last()
            && let Some(entries) = frame.get(&key)
        {
            for entry in entries {
                if oxdock_parser::guards_overlap(entry.guard.as_ref(), guard) {
                    bail!(
                        "step {}: redeclaration error: ${key} already declared in this scope; \
                         use ${key} = ... to mutate",
                        idx + 1
                    );
                }
            }
        }
        if let Some(frame) = self.frames.last_mut() {
            frame.entry(key).or_default().push(Binding {
                tag,
                guard: guard.cloned(),
            });
        }
        Ok(())
    }

    fn insert_top(&mut self, key: String, tag: TypeTag, guard: Option<&GuardExpr>) {
        if let Some(frame) = self.frames.last_mut() {
            frame.insert(
                key,
                vec![Binding {
                    tag,
                    guard: guard.cloned(),
                }],
            );
        }
    }
}

impl<'a, P: ProcessManager> Checker<'a, P> {
    fn new(exec: &'a ExecState<P>) -> Self {
        let mut hosts = HashMap::new();
        for meta in exec.functions.all_metas() {
            hosts.insert(meta.name.clone(), meta);
        }
        Self {
            exec,
            funcs: HashMap::new(),
            hosts,
            inferred: HashMap::new(),
            inferring: Vec::new(),
            visits: 0,
        }
    }

    fn func_keys(&self) -> Vec<String> {
        self.funcs.keys().cloned().collect()
    }

    /// Phase A: collect every `FuncDef` in the tree, resolving param
    /// type words now (the same `resolve_tag` execution uses, so an
    /// unknown word fails here with the identical message). Dead
    /// steps are skipped: unregistered code is never checked.
    /// Each function is keyed by bare and `SCRIPT::`-qualified name
    /// so calls resolve regardless of parser qualification.
    fn collect(&mut self, steps: &[Step]) -> Result<()> {
        for step in steps {
            if matches!(classify_guard(step.guard.as_ref()), GuardClass::Dead) {
                continue;
            }
            self.collect_step(step)?;
        }
        Ok(())
    }

    fn collect_step(&mut self, step: &Step) -> Result<()> {
        match &step.kind {
            StepKind::FuncDef { name, params, body } => {
                let mut resolved = Vec::with_capacity(params.len());
                for (pname, ptype) in params {
                    let tag = self
                        .exec
                        .resolve_tag(ptype)
                        .map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
                    resolved.push((clean_var(pname), tag));
                }
                let info = FuncInfo {
                    params: resolved,
                    body: body.clone(),
                };
                self.funcs.insert(name.clone(), info);
                self.funcs.insert(
                    format!("SCRIPT::{name}"),
                    FuncInfo {
                        params: self.funcs[name].params.clone(),
                        body: self.funcs[name].body.clone(),
                    },
                );
                // Nested definitions register if execution reaches
                // them; collect their bodies too.
                let nested = self.funcs[name].body.clone();
                self.collect(&nested)?;
            }
            StepKind::If {
                then_body,
                else_ifs,
                else_body,
                ..
            } => {
                self.collect(then_body)?;
                for (_, arm) in else_ifs {
                    self.collect(arm)?;
                }
                if let Some(arm) = else_body {
                    self.collect(arm)?;
                }
            }
            StepKind::For { body, .. } | StepKind::While { body, .. } => {
                self.collect(body)?;
            }
            StepKind::AsyncBlock { body } => self.collect(body)?,
            _ => {}
        }
        Ok(())
    }

    /// Top-level steps run with an empty environment: undeclared
    /// variables, bad arities, and mistyped arguments fail here, the
    /// same as inside any function.
    fn check_top_level(&mut self, steps: &[Step]) -> Result<()> {
        let mut env = Env::one_frame(Vec::new());
        let scope = Scope {
            label: "top level",
            ret: RetCtx::Top,
            loops: 0,
            site: None,
        };
        let out = self.walk_body(steps, &mut env, &scope, 0)?;
        let _ = out;
        Ok(())
    }

    /// Phase B: inferred return type of one script function,
    /// memoized. Recursive and forward references widen to `ANY`
    /// while inference is in progress.
    fn func_return(&mut self, key: &str, depth: usize) -> Result<StaticTy> {
        if let Some(known) = self.inferred.get(key) {
            return Ok(*known);
        }
        if self.inferring.iter().any(|name| name == key) {
            return Ok(StaticTy::Ty(TypeTag::Any));
        }
        let info = self.funcs.get(key).cloned();
        let Some(info) = info else {
            return Ok(StaticTy::Ty(TypeTag::Any));
        };
        self.inferring.push(key.to_string());
        let result = self.check_function_body(key, &info, depth);
        self.inferring.pop();
        let ty = result?;
        self.inferred.insert(key.to_string(), ty);
        Ok(ty)
    }

    /// Check one function body: terminal unification, MissingReturn,
    /// VOID classification.
    fn check_function_body(
        &mut self,
        key: &str,
        info: &FuncInfo,
        depth: usize,
    ) -> Result<StaticTy> {
        if depth > MAX_STATIC_DEPTH {
            bail!("static analysis depth exceeded in function `{key}`");
        }
        let mut env = Env::one_frame(info.params.clone());
        let scope = Scope {
            label: key,
            ret: RetCtx::Func(key.to_string()),
            loops: 0,
            site: None,
        };
        let out = self.walk_body(&info.body, &mut env, &scope, depth + 1)?;
        if out.has_return && out.falls_through {
            bail!(
                "function `{key}` may fall through with no RETURN on some path; \
                 add an unconditional RETURN or EXIT"
            );
        }
        if !out.has_return {
            return Ok(StaticTy::Void);
        }
        let mut unified: Option<TypeTag> = None;
        for ty in out.types {
            unified = Some(match unified {
                None => ty,
                Some(acc) => unify(acc, ty, &format!("function `{key}`"))?,
            });
        }
        Ok(StaticTy::Ty(unified.expect("has_return implies a type")))
    }

    /// Walk one body sequentially. A conditionally-guarded step keeps
    /// its returns and types but never terminates the walk: the path
    /// passes through it. Branches and loops fork the environment and
    /// discard it (arm and loop declarations are scope-local at
    /// runtime); `SET` cannot change types (runtime coerces), so no
    /// merge is needed — discarding is exact.
    #[allow(clippy::too_many_lines)]
    fn walk_body(
        &mut self,
        steps: &[Step],
        env: &mut Env,
        scope: &Scope,
        depth: usize,
    ) -> Result<WalkOut> {
        if depth > MAX_STATIC_DEPTH {
            bail!("static analysis depth exceeded in `{}`", scope.label);
        }
        let base_frames = env.frames.len();
        let mut out = WalkOut {
            falls_through: true,
            has_return: false,
            types: Vec::new(),
        };
        for (idx, step) in steps.iter().enumerate() {
            self.visits += 1;
            let scoped = Scope {
                label: scope.label,
                ret: scope.ret.clone(),
                loops: scope.loops,
                site: step.guard.clone(),
            };
            let scope = &scoped;
            // Positional scopes mirror execution exactly: pushed
            // before the guard check, restored after the step, even
            // for dead steps (net effect zero there).
            for _ in 0..step.scope_enter {
                env.frames.push(HashMap::new());
            }
            match classify_guard(step.guard.as_ref()) {
                GuardClass::Dead => {}
                GuardClass::Conditional => {
                    let inner = self.walk_step(step, env, scope, idx, depth)?;
                    out.has_return |= inner.has_return;
                    out.types.extend(inner.types);
                }
                GuardClass::Unconditional => {
                    let inner = self.walk_step(step, env, scope, idx, depth)?;
                    out.has_return |= inner.has_return;
                    out.types.extend(inner.types);
                    if !inner.falls_through {
                        out.falls_through = false;
                        return Ok(out);
                    }
                }
            }
            for _ in 0..step.scope_exit {
                if env.frames.len() > base_frames {
                    env.frames.pop();
                }
            }
            // Early terminal returns above skip the pops and discard
            // the env, matching observable runtime behavior (restore
            // then propagate out of the body).
        }
        Ok(out)
    }

    /// Walk a single live step. The returned `falls_through` is
    /// relative to the step alone; the caller applies guard semantics.
    fn walk_step(
        &mut self,
        step: &Step,
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<WalkOut> {
        let live = WalkOut {
            falls_through: true,
            has_return: false,
            types: Vec::new(),
        };
        match &step.kind {
            StepKind::Return { expr } => {
                match &scope.ret {
                    RetCtx::Func(_) | RetCtx::Block | RetCtx::AsyncValue => {}
                    RetCtx::Top => {
                        bail!(
                            "step {}: RETURN outside function, ASYNC task, or LET block",
                            idx + 1
                        );
                    }
                    RetCtx::AsyncStmt => {
                        bail!("step {}: RETURN cannot cross ASYNC boundary", idx + 1);
                    }
                }
                let ty = self.infer_expr(expr, env, scope, idx, depth + 1)?;
                let mut out = live;
                out.has_return = true;
                out.falls_through = false;
                if let StaticTy::Ty(tag) = ty {
                    out.types.push(tag);
                }
                Ok(out)
            }
            StepKind::Break => self.walk_break("BREAK", scope, idx),
            StepKind::Continue => self.walk_break("CONTINUE", scope, idx),
            StepKind::Exit(_) => {
                self.check_step_args(&step.kind, env, scope, idx, depth)?;
                Ok(WalkOut {
                    falls_through: false,
                    has_return: false,
                    types: Vec::new(),
                })
            }
            StepKind::If {
                cond,
                then_body,
                else_ifs,
                else_body,
            } => {
                self.infer_expr(cond, env, scope, idx, depth + 1)?;
                let mut arms_terminal = true;
                let mut out = live;
                let mut arms = vec![then_body];
                for (else_cond, arm) in else_ifs {
                    self.infer_expr(else_cond, env, scope, idx, depth + 1)?;
                    arms.push(arm);
                }
                for arm in arms {
                    let mut fork = env.fork();
                    let arm_out = self.walk_body(arm, &mut fork, scope, depth + 1)?;
                    out.has_return |= arm_out.has_return;
                    out.types.extend(arm_out.types);
                    arms_terminal &= !arm_out.falls_through;
                }
                match else_body {
                    Some(arm) => {
                        let mut fork = env.fork();
                        let arm_out = self.walk_body(arm, &mut fork, scope, depth + 1)?;
                        out.has_return |= arm_out.has_return;
                        out.types.extend(arm_out.types);
                        arms_terminal &= !arm_out.falls_through;
                    }
                    None => arms_terminal = false,
                }
                out.falls_through = !arms_terminal;
                Ok(out)
            }
            StepKind::For {
                key_var,
                key_type,
                var,
                var_type,
                in_expr,
                body,
            } => {
                self.infer_expr(in_expr, env, scope, idx, depth + 1)?;
                let val_tag = self
                    .exec
                    .resolve_tag(var_type)
                    .map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
                let mut fork = env.fork();
                fork.insert_top(clean_var(var), val_tag, step.guard.as_ref());
                if let Some(key) = key_var {
                    let key_tag = match key_type {
                        Some(name) => self
                            .exec
                            .resolve_tag(name)
                            .map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?,
                        None => TypeTag::Int,
                    };
                    fork.insert_top(clean_var(key), key_tag, step.guard.as_ref());
                }
                let mut inner_scope = scope.clone();
                inner_scope.loops += 1;
                let body_out = self.walk_body(body, &mut fork, &inner_scope, depth + 1)?;
                let mut out = live;
                // Loops may trip zero times: fallthrough always
                // survives, but body returns are live paths.
                out.has_return = body_out.has_return;
                out.types = body_out.types;
                Ok(out)
            }
            StepKind::While { cond, body } => {
                self.infer_expr(cond, env, scope, idx, depth + 1)?;
                let mut fork = env.fork();
                let mut inner_scope = scope.clone();
                inner_scope.loops += 1;
                let body_out = self.walk_body(body, &mut fork, &inner_scope, depth + 1)?;
                let mut out = live;
                out.has_return = body_out.has_return;
                out.types = body_out.types;
                Ok(out)
            }
            StepKind::FuncDef { name, params, body } => {
                let mut resolved = Vec::with_capacity(params.len());
                for (pname, ptype) in params {
                    let tag = self
                        .exec
                        .resolve_tag(ptype)
                        .map_err(|err| anyhow::anyhow!("function `{name}`: {err:#}"))?;
                    resolved.push((clean_var(pname), tag));
                }
                let info = FuncInfo {
                    params: resolved,
                    body: body.clone(),
                };
                self.check_function_body(name, &info, depth + 1)?;
                Ok(live)
            }
            StepKind::Call { name, args } => {
                self.check_call(name, args, env, scope, idx, depth + 1)?;
                Ok(live)
            }
            StepKind::Assign {
                var,
                decl_type,
                expr,
            } => {
                let rhs = self.infer_expr(expr, env, scope, idx, depth + 1)?;
                if matches!(rhs, StaticTy::Void) {
                    bail!(
                        "step {}: VOID block has no value to bind to `${var}`",
                        idx + 1
                    );
                }
                let tag = self
                    .exec
                    .resolve_tag(decl_type)
                    .map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
                let key = clean_var(var);
                env.declare(key, tag, step.guard.as_ref(), idx)?;
                Ok(live)
            }
            StepKind::AssignCapture {
                var,
                decl_type,
                cmd,
            } => {
                // The captured command runs first at runtime, so its
                // expressions check before the declaration lands.
                self.walk_wrapped(cmd, env, scope, idx, depth + 1)?;
                let tag = self
                    .exec
                    .resolve_tag(decl_type)
                    .map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
                let key = clean_var(var);
                env.declare(key, tag, step.guard.as_ref(), idx)?;
                Ok(live)
            }
            StepKind::Set { var, expr } => {
                let key = clean_var(var);
                if !env.is_declared(&key) {
                    bail!(
                        "step {}: undeclared variable ${key}: declare it first with LET ${key}: TYPE = ...",
                        idx + 1
                    );
                }
                // Site-aware liveness: the binding must hold on this
                // step's path, not merely somewhere in scope. A bare
                // existence check would accept a mutation on a path
                // where the variable never binds.
                let _ = env.read_guarded(&key, scope.site.as_ref())?;
                self.infer_expr(expr, env, scope, idx, depth + 1)?;
                Ok(live)
            }
            StepKind::AwaitCapture {
                out_var,
                out_type,
                task_var,
            } => {
                // The handle resolves before the output declares.
                Self::check_name_read(env, task_var, scope, idx)?;
                let tag = self
                    .exec
                    .resolve_tag(out_type)
                    .map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
                let key = clean_var(out_var);
                env.declare(key, tag, step.guard.as_ref(), idx)?;
                Ok(live)
            }
            StepKind::AsyncBlock { body } => {
                // Bare tasks never publish a value: control never
                // crosses the thread boundary at runtime.
                let mut fork = env.fork();
                let task = Scope {
                    label: scope.label,
                    ret: RetCtx::AsyncStmt,
                    loops: 0,
                    site: scope.site.clone(),
                };
                self.walk_body(body, &mut fork, &task, depth + 1)?;
                Ok(live)
            }
            StepKind::AssignAsync {
                var,
                decl_type,
                body,
            } => {
                // `LET $o = ASYNC` bodies publish through `AWAIT`;
                // returns belong to the task, never the enclosing
                // function.
                let mut fork = env.fork();
                let task = Scope {
                    label: scope.label,
                    ret: RetCtx::AsyncValue,
                    loops: 0,
                    site: scope.site.clone(),
                };
                self.walk_body(body, &mut fork, &task, depth + 1)?;
                let tag = self
                    .exec
                    .resolve_tag(decl_type)
                    .map_err(|err| anyhow::anyhow!("step {}: {err:#}", idx + 1))?;
                let key = clean_var(var);
                env.insert_top(key, tag, step.guard.as_ref());
                Ok(live)
            }
            StepKind::Timeout { body, .. } => {
                // A dynamic duration evaluates before the body runs.
                self.check_step_args(&step.kind, env, scope, idx, depth)?;
                let inner = self.walk_body(body, env, scope, depth + 1)?;
                let mut out = live;
                // TIMEOUT bounds execution in place: a `RETURN`
                // inside still returns from the enclosing function.
                out.has_return = inner.has_return;
                out.types = inner.types;
                out.falls_through = inner.falls_through;
                if !inner.falls_through {
                    return Ok(out);
                }
                Ok(out)
            }
            StepKind::RemoteBlock {
                target, vars, body, ..
            } => {
                // Sealed scope: the guest starts empty and only
                // header-listed names cross, seeded from the outer
                // environment. A body `LET` over an injected name
                // shadows within the seal, exactly like a braced
                // block. Returns never propagate: the shipped scope
                // runs as ordinary top-level steps.
                let mut sealed = Env::one_frame(Vec::new());
                for name in vars {
                    let key = clean_var(name);
                    let (tag, guard) =
                        env.read_entry_guarded(&key, step.guard.as_ref())
                            .map_err(|_| {
                                anyhow::anyhow!("REMOTE '{target}' uses unknown variable ${key}")
                            })?;
                    sealed.insert_top(key, tag, guard.as_ref());
                }
                // Body declarations shadow injected names: the seal
                // pushes a scope exactly like a braced block.
                sealed.frames.push(HashMap::new());
                let remote = Scope {
                    label: scope.label,
                    ret: RetCtx::Top,
                    loops: 0,
                    site: None,
                };
                self.walk_body(body, &mut sealed, &remote, depth + 1)?;
                Ok(live)
            }
            StepKind::WithIo { bindings, cmd } => {
                // Bindings resolve before the wrapped command runs.
                Self::check_pipe_bindings(env, bindings, scope, idx)?;
                self.walk_wrapped(cmd, env, scope, idx, depth + 1)
            }
            StepKind::ReadLine { var } => {
                // Declares `STRING` when absent, mutates (type kept)
                // when present — mirroring `read_line` exactly.
                let key = clean_var(var);
                if !env.is_declared(&key) {
                    env.insert_top(key, TypeTag::String, step.guard.as_ref());
                }
                Ok(live)
            }
            StepKind::Prompt { var, .. } => {
                // Same declare-or-mutate contract as `read_line`:
                // the answer binds as `STRING`, mutating when present.
                let key = clean_var(var);
                if !env.is_declared(&key) {
                    env.insert_top(key, TypeTag::String, step.guard.as_ref());
                }
                Ok(live)
            }
            _ => {
                // Every remaining variant is a simple command: all its
                // argument expressions (including `{{ }}` template
                // fragments) read through inference, and handle/pipe/list
                // names read through site-aware liveness. Control-flow,
                // declaration, and wrapped forms return through their own
                // arms above, so nothing here double-checks.
                self.check_step_args(&step.kind, env, scope, idx, depth)?;
                match &step.kind {
                    StepKind::Await { var } | StepKind::Cancel { var } => {
                        Self::check_name_read(env, var, scope, idx)?;
                    }
                    StepKind::WithIoBlock { bindings } => {
                        Self::check_pipe_bindings(env, bindings, scope, idx)?;
                    }
                    StepKind::ListAppend { list, item } => {
                        let tag = Self::check_name_read(env, list, scope, idx)?;
                        let element = match tag {
                            TypeTag::List => None,
                            TypeTag::ListOf(element) => Some(*element),
                            _ => bail!(
                                "step {}: LIST_APPEND ${}: variable is {}, not LIST",
                                idx + 1,
                                clean_var(list),
                                render_structural(&tag)
                            ),
                        };
                        // Shaped lists check the item exactly (no coercion
                        // applies on push, so unlike call arguments there
                        // is no gate: unknown items defer to the runtime
                        // walk, which validates every push).
                        if let Some(expected) = element {
                            let actual = match item {
                                oxdock_parser::Arg::Expr(expr) => {
                                    self.infer_expr(expr, env, scope, idx, depth + 1)?
                                }
                                _ => StaticTy::Ty(TypeTag::String),
                            };
                            let StaticTy::Ty(actual) = actual else {
                                bail!(
                                    "step {}: LIST_APPEND ${}: VOID has no value to push",
                                    idx + 1,
                                    clean_var(list)
                                );
                            };
                            Self::check_exact(&expected, &actual, &format!("step {}", idx + 1))?;
                        }
                    }
                    _ => {}
                }
                Ok(live)
            }
        }
    }

    /// Check every argument expression of one simple command through
    /// `infer_expr`: `Arg::Expr` operands and `{{ }}` template
    /// fragments (`Arg::Parts`) read live bindings; plain strings
    /// carry nothing. Built on the exhaustive `walk_exprs` visitor,
    /// so a new expression-carrying variant fails compilation in the
    /// parser instead of slipping past this pass.
    fn check_step_args(
        &mut self,
        kind: &StepKind,
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<()> {
        let mut failed: Option<anyhow::Error> = None;
        kind.walk_exprs(&mut |expr| {
            if failed.is_none()
                && let Err(err) = self.infer_expr(expr, env, scope, idx, depth + 1)
            {
                failed = Some(err);
            }
        });
        if let Some(err) = failed {
            return Err(err);
        }
        Ok(())
    }

    /// Static counterpart of a runtime name lookup (`get_var` and
    /// friends): the binding must be declared and live on this
    /// step's path, mirroring the `undefined variable` failure one
    /// for one.
    fn check_name_read(env: &Env, name: &str, scope: &Scope, idx: usize) -> Result<TypeTag> {
        let key = clean_var(name);
        if !env.is_declared(&key) {
            bail!("step {}: undefined variable ${key}", idx + 1);
        }
        env.read_guarded(&key, scope.site.as_ref())
    }

    /// Static counterpart of `resolve_pipe_handle`: a `$var` pipe
    /// endpoint must be a live `PIPE` binding, mirroring the runtime
    /// `TypeMismatch` one for one.
    fn check_pipe_bindings(
        env: &Env,
        bindings: &[IoBinding],
        scope: &Scope,
        idx: usize,
    ) -> Result<()> {
        for binding in bindings {
            if let Some(PipeTarget::Var(name)) = &binding.pipe {
                let tag = Self::check_name_read(env, name, scope, idx)?;
                if !tags_equal(&tag, &TypeTag::Pipe) {
                    bail!(
                        "step {}: TypeMismatch: expected PIPE, got {}",
                        idx + 1,
                        tag.name()
                    );
                }
            }
        }
        Ok(())
    }

    /// `BREAK`/`CONTINUE`: legal only inside a loop body. Anywhere
    /// else the boundary error mirrors execution one for one.
    fn walk_break(&mut self, word: &str, scope: &Scope, idx: usize) -> Result<WalkOut> {
        if scope.loops > 0 {
            return Ok(WalkOut {
                falls_through: true,
                has_return: false,
                types: Vec::new(),
            });
        }
        match &scope.ret {
            RetCtx::Top => bail!("step {}: {word} outside loop", idx + 1),
            RetCtx::Func(name) => {
                bail!(
                    "step {}: {word} cannot cross function boundary (in {name}())",
                    idx + 1
                );
            }
            RetCtx::Block => {
                bail!("step {}: {word} cannot cross block boundary", idx + 1);
            }
            RetCtx::AsyncValue | RetCtx::AsyncStmt => {
                bail!("step {}: {word} cannot cross ASYNC boundary", idx + 1);
            }
        }
    }

    /// Walk a single boxed `StepKind` (the `WithIo` payload) as if it
    /// were a step: the enclosing guard was already classified by the
    /// caller, so this inherits the live context directly.
    fn walk_wrapped(
        &mut self,
        cmd: &StepKind,
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<WalkOut> {
        let step = Step {
            guard: None,
            kind: cmd.clone(),
            scope_enter: 0,
            scope_exit: 0,
        };
        self.walk_step(&step, env, scope, idx, depth)
    }

    /// Static counterpart of `coerce_value` for argument positions.
    /// `Ok` where runtime coercion provably succeeds or decides by
    /// value; `Err` where it provably fails — plus the `ANY` gate:
    /// an untyped value into a concrete parameter names the
    /// `LET $x: T` binding that would coerce it.
    fn check_arg(&mut self, expected: &TypeTag, actual: StaticTy, ctx: &str) -> Result<()> {
        let StaticTy::Ty(actual) = actual else {
            bail!("{ctx}: VOID has no value to pass");
        };
        if matches!(expected, TypeTag::Any) {
            return Ok(());
        }
        if matches!(actual, TypeTag::Any) {
            bail!(
                "{ctx}: untyped ANY value flows into {} parameter; \
                 bind through LET $x: {} first",
                render_structural(expected),
                render_structural(expected)
            );
        }
        if tags_equal(expected, &actual) {
            return Ok(());
        }
        // Mirror coerce_value/coerce_scalar: allow pairs the runtime
        // decides by value; reject pairs that always bail. Shaped
        // values satisfy bare words (a record IS a map); bare words
        // never satisfy fixed shapes, except the unknown list shape:
        // an empty or heterogeneous literal infers bare `LIST`, which
        // enters `LIST<...>` vacuously (mirroring the bare `MAP`
        // into `MAP<...>` arm). Literals infer their own shapes, so
        // dynamic values still gate through `LET` instead of slipping
        // into shaped positions. Same-constructor shapes compare
        // exactly below; the runtime walk re-validates every element,
        // so a mixed literal still fails loudly at execution.
        let ok = matches!(
            (&actual, expected),
            (TypeTag::String, TypeTag::Int)
                | (TypeTag::String, TypeTag::Float)
                | (TypeTag::String, TypeTag::Bool)
                | (TypeTag::String, TypeTag::Duration)
                | (TypeTag::String, TypeTag::Path)
                | (TypeTag::Int, TypeTag::String)
                | (TypeTag::Int, TypeTag::Float)
                | (TypeTag::Float, TypeTag::String)
                | (TypeTag::Float, TypeTag::Int)
                | (TypeTag::Bool, TypeTag::String)
                | (TypeTag::Duration, TypeTag::String)
                | (TypeTag::Path, TypeTag::String)
                | (TypeTag::ListOf(_), TypeTag::List)
                | (TypeTag::List, TypeTag::ListOf(_))
                | (TypeTag::Record(_), TypeTag::Map)
                | (TypeTag::MapOf(_), TypeTag::Map)
                | (TypeTag::Map, TypeTag::MapOf(_))
        );
        if ok {
            return Ok(());
        }
        if matches!(
            (&actual, expected),
            (TypeTag::ListOf(_), TypeTag::ListOf(_))
                | (TypeTag::MapOf(_), TypeTag::MapOf(_))
                | (TypeTag::Record(_), TypeTag::Record(_))
                | (TypeTag::Record(_), TypeTag::MapOf(_))
        ) {
            return Self::check_exact(expected, &actual, ctx);
        }
        bail!(
            "{ctx}: TypeMismatch: expected {}, got {}",
            render_structural(expected),
            render_structural(&actual)
        );
    }

    /// Exact shape compatibility for same-constructor tags: element by
    /// element, field by field, with `ANY` deferring to the runtime
    /// walk. No scalar coercion applies inside collections (the walk
    /// checks exactly), so mismatches fail here naming the position.
    /// Record comparison is order-free: same names with compatible
    /// types satisfy regardless of declaration order.
    fn check_exact(expected: &TypeTag, actual: &TypeTag, ctx: &str) -> Result<()> {
        if tags_equal(expected, actual) {
            return Ok(());
        }
        if matches!(expected, TypeTag::Any) || matches!(actual, TypeTag::Any) {
            return Ok(());
        }
        match (actual, expected) {
            (TypeTag::ListOf(a), TypeTag::ListOf(e)) | (TypeTag::MapOf(a), TypeTag::MapOf(e)) => {
                Self::check_exact(e, a, ctx)
            }
            (TypeTag::Record(a_fields), TypeTag::Record(e_fields)) => {
                for field in *e_fields {
                    match a_fields.iter().find(|found| found.name == field.name) {
                        Some(found) => Self::check_exact(&field.ty, &found.ty, ctx)?,
                        None if field.optional => {}
                        None => bail!("{ctx}: missing field '{}'", field.name),
                    }
                }
                for field in *a_fields {
                    if !e_fields.iter().any(|known| known.name == field.name) {
                        bail!("{ctx}: unknown field '{}'", field.name);
                    }
                }
                Ok(())
            }
            (TypeTag::Record(a_fields), TypeTag::MapOf(inner)) => {
                for field in *a_fields {
                    Self::check_exact(inner, &field.ty, ctx)?;
                }
                Ok(())
            }
            (TypeTag::ListOf(_), TypeTag::List)
            | (TypeTag::Record(_), TypeTag::Map)
            | (TypeTag::MapOf(_), TypeTag::Map) => Ok(()),
            _ => bail!(
                "{ctx}: TypeMismatch: expected {}, got {}",
                render_structural(expected),
                render_structural(actual)
            ),
        }
    }

    /// Resolve a callee: script functions (bare or `SCRIPT::`-qualified)
    /// win over host metas, matching runtime shadowing. Unknown names
    /// yield `ANY`: the parse-time unknown-function gate owns that
    /// error, not this pass.
    fn resolve_call(&mut self, name: &str, depth: usize) -> Result<Callee> {
        if let Some(info) = self.funcs.get(name) {
            let info = info.clone();
            let ret = self.func_return_owned(&info, name, depth)?;
            let params = info.params;
            return Ok(Callee {
                params: Some(params),
                ret,
                host_params: None,
            });
        }
        if let Some(meta) = self.hosts.get(name) {
            let meta = meta.clone();
            let ret = meta
                .returns
                .map(StaticTy::Ty)
                .unwrap_or(StaticTy::Ty(TypeTag::Any));
            // A missing param list (virtual entries like INSPECT)
            // means no static arity or argument checks: the dedicated
            // AST path owns that call shape.
            let params = meta.params.as_deref().map(|list| {
                list.iter()
                    .map(|param| (param.name.clone(), param.param_type.unwrap_or(TypeTag::Any)))
                    .collect()
            });
            // NOTE: host `allowed` sets are checked from the meta
            // below; the tag triple here carries only shape.
            return Ok(Callee {
                params,
                ret,
                host_params: meta.params.clone(),
            });
        }
        Ok(Callee {
            params: None,
            ret: StaticTy::Ty(TypeTag::Any),
            host_params: None,
        })
    }

    /// Memoized script return with recursion guard, keyed by the
    /// registry key the call resolved through.
    fn func_return_owned(&mut self, info: &FuncInfo, key: &str, depth: usize) -> Result<StaticTy> {
        if let Some(known) = self.inferred.get(key) {
            return Ok(*known);
        }
        if self.inferring.iter().any(|name| name == key) {
            return Ok(StaticTy::Ty(TypeTag::Any));
        }
        self.inferring.push(key.to_string());
        let result = self.check_function_body(key, info, depth);
        self.inferring.pop();
        let ty = result?;
        self.inferred.insert(key.to_string(), ty);
        Ok(ty)
    }

    /// Check one call: arity, then each argument against its parameter
    /// (host `allowed` sets enforced on string literals from the same
    /// tokens that render the signature). Returns the callee return
    /// type with `VOID` mapped to `STRING`, mirroring
    /// `Flow::Done => Ok("")`.
    fn check_call(
        &mut self,
        name: &str,
        args: &[Expr],
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<StaticTy> {
        // Order mirrors execution: the arity gate fires before any
        // argument evaluates, so undeclared names in extra arguments
        // never surface. (`native_arity_failure_...` pins this.)
        let callee = self.resolve_call(name, depth)?;
        // Arity range comes from the full host metadata (which carries
        // the optional flags); script FUNCs and bare shape lists are
        // always exact. Missing lists (INSPECT-like) skip the check:
        // the dedicated AST path owns that call shape.
        let (required, total) = match callee.host_params.as_deref() {
            Some(host) => (required_arity(host), host.len()),
            None => match callee.params.as_deref() {
                Some(shape) => (shape.len(), shape.len()),
                None => (0, usize::MAX),
            },
        };
        if args.len() < required || args.len() > total {
            if required == total {
                bail!(
                    "step {}: {}() expects {} argument(s), got {}",
                    idx + 1,
                    base_name(name),
                    total,
                    args.len()
                );
            }
            bail!(
                "step {}: {}() expects {} to {} argument(s), got {}",
                idx + 1,
                base_name(name),
                required,
                total,
                args.len()
            );
        }
        let mut tys = Vec::with_capacity(args.len());
        let mut literals: Vec<Option<&str>> = Vec::with_capacity(args.len());
        for arg in args.iter() {
            let actual = self.infer_expr(arg, env, scope, idx, depth + 1)?;
            let literal = match arg {
                Expr::Literal(value) => value.as_str(),
                _ => None,
            };
            tys.push(actual);
            literals.push(literal);
        }
        self.apply_checked(
            name,
            &callee,
            &tys,
            &literals,
            Some(&format!("step {}", idx + 1)),
        )
    }

    /// Apply already-inferred argument types to a resolved callee:
    /// per-parameter shape plus closed-set membership for string
    /// literals. Shared by AST calls (literals available) and RPN
    /// calls (shapes only).
    fn apply_checked(
        &mut self,
        name: &str,
        callee: &Callee,
        arg_tys: &[StaticTy],
        literals: &[Option<&str>],
        at: Option<&str>,
    ) -> Result<StaticTy> {
        let display = base_name(name);
        let Callee {
            params,
            ret,
            host_params,
        } = callee;
        let (required, total) = match host_params.as_deref() {
            Some(host) => (required_arity(host), host.len()),
            None => match params.as_deref() {
                Some(shape) => (shape.len(), shape.len()),
                // INSPECT-like entries skip arity: the dedicated AST
                // path owns that call shape.
                None => (0, usize::MAX),
            },
        };
        if arg_tys.len() < required || arg_tys.len() > total {
            if required == total {
                bail!(
                    "{}{display}() expects {} argument(s), got {}",
                    loc(at),
                    total,
                    arg_tys.len()
                );
            }
            bail!(
                "{}{display}() expects {} to {} argument(s), got {}",
                loc(at),
                required,
                total,
                arg_tys.len()
            );
        }
        for (position, actual) in arg_tys.iter().enumerate() {
            let Some(expected) = params.as_deref().and_then(|list| list.get(position)) else {
                continue;
            };
            let (pname, ptype) = expected;
            let pat = format!("{}{display}() argument `${pname}`", loc(at));
            self.check_arg(ptype, *actual, &pat)?;
            if let Some(host_list) = host_params.as_deref()
                && let Some(param) = host_list.get(position)
                && let Some(allowed) = param.allowed
                && let Some(Some(text)) = literals.get(position)
                && !allowed.contains(text)
            {
                bail!("{pat} must be one of: {}, got {text:?}", allowed.join(", "));
            }
        }
        match *ret {
            StaticTy::Void => Ok(StaticTy::Ty(TypeTag::String)),
            other => Ok(other),
        }
    }
}

/// Map a literal word to its tag via the script vocabulary; custom
/// words (opaque handles) widen to `ANY`.
fn literal_tag(value: &Value) -> TypeTag {
    TypeTag::builtin(value.type_name()).unwrap_or(TypeTag::Any)
}

/// Binary arithmetic rule, mirroring `apply_arith`: `INT op INT` is
/// `INT`, any `FLOAT` among numerics promotes, `ANY` defers, and
/// concrete non-numerics are a static Type Error (the evaluator
/// bails identically).
fn numeric_pair(left: StaticTy, right: StaticTy, at: Option<&str>) -> Result<StaticTy> {
    let (StaticTy::Ty(left), StaticTy::Ty(right)) = (left, right) else {
        bail!("{}VOID has no value in arithmetic", loc(at));
    };
    if matches!(left, TypeTag::Any) || matches!(right, TypeTag::Any) {
        return Ok(StaticTy::Ty(TypeTag::Any));
    }
    if matches!(
        (&left, &right),
        (TypeTag::Int, TypeTag::Int)
            | (TypeTag::Int, TypeTag::Float)
            | (TypeTag::Float, TypeTag::Int)
            | (TypeTag::Float, TypeTag::Float)
    ) {
        return Ok(StaticTy::Ty(
            if matches!(left, TypeTag::Int) && matches!(right, TypeTag::Int) {
                TypeTag::Int
            } else {
                TypeTag::Float
            },
        ));
    }
    bail!("{}Type Error: arithmetic requires Int or Float", loc(at));
}

/// Unary negation rule, mirroring `apply_neg`.
fn neg_rule(top: StaticTy, at: Option<&str>) -> Result<StaticTy> {
    match top {
        StaticTy::Ty(TypeTag::Int) => Ok(StaticTy::Ty(TypeTag::Int)),
        StaticTy::Ty(TypeTag::Float) => Ok(StaticTy::Ty(TypeTag::Float)),
        StaticTy::Ty(TypeTag::Any) => Ok(StaticTy::Ty(TypeTag::Any)),
        StaticTy::Void => bail!("{}VOID has no value to negate", loc(at)),
        StaticTy::Ty(other) => {
            bail!(
                "{}Type Error: unary '-' requires Int or Float, got {}",
                loc(at),
                other.name()
            )
        }
    }
}

/// Ordering comparison rule, mirroring `apply_compare`.
fn ordering_pair(left: StaticTy, right: StaticTy, at: Option<&str>) -> Result<()> {
    let (StaticTy::Ty(left), StaticTy::Ty(right)) = (left, right) else {
        bail!("{}VOID has no value to compare", loc(at));
    };
    if matches!(left, TypeTag::Any) || matches!(right, TypeTag::Any) {
        return Ok(());
    }
    let numeric = |tag: &TypeTag| matches!(tag, TypeTag::Int | TypeTag::Float);
    if numeric(&left) && numeric(&right) {
        return Ok(());
    }
    bail!(
        "{}Type Error: ordering comparison requires Int or Float",
        loc(at)
    );
}

impl<'a, P: ProcessManager> Checker<'a, P> {
    /// Infer a list literal's shape: homogeneous non-empty lists lock
    /// their element tag through the interned spelling (shared with
    /// declarations, so identical shapes unify). Uniformly maplike or
    /// listlike elements join to the unknown shape (`LIST<MAP<ANY>>`,
    /// `LIST<LIST<ANY>>`); anything else stays bare `LIST` for the
    /// runtime walk to decide. Never fails: shapes that cannot be
    /// spelled fall back instead of erroring.
    fn infer_list_literal(
        &mut self,
        items: &[Expr],
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<StaticTy> {
        let mut tags = Vec::with_capacity(items.len());
        for item in items {
            match self.infer_expr(item, env, scope, idx, depth + 1)? {
                StaticTy::Ty(tag) => tags.push(tag),
                StaticTy::Void => return Ok(StaticTy::Ty(TypeTag::List)),
            }
        }
        let Some(first) = tags.first() else {
            return Ok(StaticTy::Ty(TypeTag::List));
        };
        if matches!(first, TypeTag::Any) || !tags.iter().all(|tag| tags_equal(first, tag)) {
            let join = if tags.iter().all(is_maplike) {
                Some("LIST<MAP<ANY>>")
            } else if tags.iter().all(is_listlike) {
                Some("LIST<LIST<ANY>>")
            } else {
                None
            };
            let Some(spelling) = join else {
                return Ok(StaticTy::Ty(TypeTag::List));
            };
            return Ok(self
                .exec
                .resolve_tag(spelling)
                .map(StaticTy::Ty)
                .unwrap_or(StaticTy::Ty(TypeTag::List)));
        }
        let spelling = format!("LIST<{}>", render_structural(first));
        Ok(self
            .exec
            .resolve_tag(&spelling)
            .map(StaticTy::Ty)
            .unwrap_or(StaticTy::Ty(TypeTag::List)))
    }

    /// Infer a map literal's shape through its canonical spelling, so
    /// conforming literals share the interned entry that declarations
    /// resolve to. Source order is significant (spellings canonicalize
    /// without reordering): matching declaration order unifies, anything
    /// else falls back to bare shape handling downstream. Never fails.
    fn infer_map_literal(
        &mut self,
        entries: &[(String, Expr)],
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<StaticTy> {
        let mut parts = Vec::with_capacity(entries.len());
        for (key, value) in entries {
            match self.infer_expr(value, env, scope, idx, depth + 1)? {
                StaticTy::Ty(tag) => parts.push(format!("{key}: {}", render_structural(&tag))),
                StaticTy::Void => return Ok(StaticTy::Ty(TypeTag::Map)),
            }
        }
        if parts.is_empty() {
            return Ok(StaticTy::Ty(TypeTag::Map));
        }
        let spelling = format!("MAP<{}>", parts.join(", "));
        Ok(self
            .exec
            .resolve_tag(&spelling)
            .map(StaticTy::Ty)
            .unwrap_or(StaticTy::Ty(TypeTag::Map)))
    }

    /// Infer an expression's static type, running nested checks
    /// (undeclared variables, nested calls) along the way.
    fn infer_expr(
        &mut self,
        expr: &Expr,
        env: &mut Env,
        scope: &Scope,
        idx: usize,
        depth: usize,
    ) -> Result<StaticTy> {
        if depth > MAX_STATIC_DEPTH {
            bail!("static analysis depth exceeded in `{}`", scope.label);
        }
        self.visits += 1;
        let at = || format!("step {}", idx + 1);
        match expr {
            Expr::Literal(value) => Ok(StaticTy::Ty(literal_tag(value))),
            Expr::Var(name) => {
                let key = clean_var(name);
                if !env.is_declared(&key) {
                    bail!("{}undefined variable ${key}", loc(Some(&at())));
                }
                Ok(StaticTy::Ty(env.read_guarded(&key, scope.site.as_ref())?))
            }
            Expr::Env(_) => Ok(StaticTy::Ty(TypeTag::String)),
            Expr::KeyPath { base, keys } => {
                let key = clean_var(base);
                if !env.is_declared(&key) {
                    bail!("{}undefined variable ${key}", loc(Some(&at())));
                }
                let mut current = env.read_guarded(&key, scope.site.as_ref())?;
                for part in keys {
                    match current {
                        TypeTag::Record(fields) => {
                            let Some(field) = fields.iter().find(|field| field.name == part) else {
                                bail!(
                                    "{}: unknown field '{part}'; expected fields: {}",
                                    at(),
                                    fields
                                        .iter()
                                        .map(|field| field.name)
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                );
                            };
                            current = field.ty;
                        }
                        TypeTag::ListOf(element) => {
                            // Shaped lists step into the element type on
                            // numeric segments (bounds stay runtime);
                            // anything else mirrors the evaluator's
                            // invalid-index failure statically.
                            if part.parse::<usize>().is_err() {
                                bail!("{}: Invalid array index '{part}'", at());
                            }
                            current = *element;
                        }
                        TypeTag::MapOf(values) => {
                            // Unknown maps step into their value shape;
                            // keys resolve by value at runtime.
                            current = *values;
                        }
                        // MAP keys and LIST indices resolve by value at
                        // runtime (missing keys, bounds); the shape
                        // stays unknown here.
                        TypeTag::Map | TypeTag::List | TypeTag::Any => {
                            return Ok(StaticTy::Ty(TypeTag::Any));
                        }
                        _ => {
                            bail!(
                                "{}: Cannot traverse into scalar value at key '{part}'",
                                at()
                            );
                        }
                    }
                }
                Ok(StaticTy::Ty(current))
            }
            Expr::List(items) => self.infer_list_literal(items, env, scope, idx, depth),
            Expr::Map(entries) => self.infer_map_literal(entries, env, scope, idx, depth),
            Expr::Block(steps) => {
                // Blocks run in a fresh scope but read enclosing
                // bindings: fork, check, discard. Same terminal rules
                // as function bodies, with block-worded errors.
                let mut fork = env.fork();
                let out = self.walk_body(
                    steps,
                    &mut fork,
                    &Scope {
                        label: scope.label,
                        ret: RetCtx::Block,
                        loops: 0,
                        site: scope.site.clone(),
                    },
                    depth + 1,
                )?;
                if out.has_return && out.falls_through {
                    bail!(
                        "{}: block may fall through with no RETURN on some path",
                        at()
                    );
                }
                if !out.has_return {
                    return Ok(StaticTy::Void);
                }
                let mut unified: Option<TypeTag> = None;
                for ty in out.types {
                    unified = Some(match unified {
                        None => ty,
                        Some(acc) => unify(acc, ty, &at())?,
                    });
                }
                Ok(StaticTy::Ty(unified.expect("has_return implies a type")))
            }
            Expr::Call { name, args } => self.check_call(name, args, env, scope, idx, depth),
            Expr::Inspect(name) => {
                let key = clean_var(name);
                if !env.is_declared(&key) {
                    bail!("{}undefined variable ${key}", loc(Some(&at())));
                }
                env.read_guarded(&key, scope.site.as_ref())?;
                Ok(StaticTy::Ty(TypeTag::Any))
            }
            Expr::Compare { op, left, right } => {
                let left_ty = self.infer_expr(left, env, scope, idx, depth + 1)?;
                let right_ty = self.infer_expr(right, env, scope, idx, depth + 1)?;
                match op {
                    // Equality stringifies anything: always BOOL.
                    CompareOp::Eq | CompareOp::Ne => {}
                    // Ordering needs numerics (mirror apply_compare).
                    CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
                        ordering_pair(left_ty, right_ty, Some(&at()))?;
                    }
                }
                Ok(StaticTy::Ty(TypeTag::Bool))
            }
            Expr::Arithmetic { left, right, .. } => {
                let left_ty = self.infer_expr(left, env, scope, idx, depth + 1)?;
                let right_ty = self.infer_expr(right, env, scope, idx, depth + 1)?;
                // All four operators share one typing rule in
                // `apply_arith`; only operand shapes matter.
                numeric_pair(left_ty, right_ty, Some(&at()))
            }
            Expr::CompiledMath(ops) => self.infer_rpn(ops, env, scope, depth),
            Expr::FreshPipe => Ok(StaticTy::Ty(TypeTag::Pipe)),
            Expr::UnsignedIntBoundary(_) => Ok(StaticTy::Ty(TypeTag::Int)),
            Expr::Not(inner) => {
                self.infer_expr(inner, env, scope, idx, depth + 1)?;
                Ok(StaticTy::Ty(TypeTag::Bool))
            }
            Expr::Logical { left, .. } => {
                // Short-circuit: the right side may never execute at
                // runtime, so it is never checked here. Whatever runs
                // is still gated at execution.
                self.infer_expr(left, env, scope, idx, depth + 1)?;
                Ok(StaticTy::Ty(TypeTag::Bool))
            }
        }
    }

    /// Ordering (`<`, `<=`, `>`, `>=`) operand rule: numerics pass,
    /// `ANY` defers to runtime, concrete non-numerics are a static
    /// Type Error mirroring `apply_compare`.
    /// RPN stack simulation over inferred operand tags. Operators
    /// apply the same rules as their AST twins; stack underflow or a
    /// trailing stack depth other than one is an internal error (the
    /// lowering never emits those shapes).
    fn infer_rpn(
        &mut self,
        ops: &[MathOp],
        env: &mut Env,
        scope: &Scope,
        depth: usize,
    ) -> Result<StaticTy> {
        if depth > MAX_STATIC_DEPTH {
            bail!("static analysis depth exceeded in `{}`", scope.label);
        }
        let mut stack: Vec<StaticTy> = Vec::new();
        for op in ops {
            match op {
                MathOp::PushConst(value) => stack.push(StaticTy::Ty(literal_tag(value))),
                MathOp::LoadVar(name) => {
                    let key = clean_var(name);
                    if !env.is_declared(&key) {
                        bail!("undefined variable ${key}");
                    }
                    stack.push(StaticTy::Ty(env.read_guarded(&key, scope.site.as_ref())?));
                }
                MathOp::LoadEnv(_) => stack.push(StaticTy::Ty(TypeTag::String)),
                MathOp::LoadKeyPath { base, keys } => {
                    let key = clean_var(base);
                    if !env.is_declared(&key) {
                        bail!("undefined variable ${key}");
                    }
                    let mut current = env.read_guarded(&key, scope.site.as_ref())?;
                    for part in keys {
                        match current {
                            TypeTag::Record(fields) => {
                                let Some(field) = fields.iter().find(|field| field.name == *part)
                                else {
                                    bail!(
                                        "unknown field '{part}'; expected fields: {}",
                                        fields
                                            .iter()
                                            .map(|field| field.name)
                                            .collect::<Vec<_>>()
                                            .join(", ")
                                    );
                                };
                                current = field.ty;
                            }
                            TypeTag::ListOf(element) => {
                                if part.parse::<usize>().is_err() {
                                    bail!("Invalid array index '{part}'");
                                }
                                current = *element;
                            }
                            TypeTag::MapOf(values) => {
                                current = *values;
                            }
                            TypeTag::Map | TypeTag::List | TypeTag::Any => {
                                current = TypeTag::Any;
                                break;
                            }
                            _ => {
                                bail!("Cannot traverse into scalar value at key '{part}'");
                            }
                        }
                    }
                    stack.push(StaticTy::Ty(current));
                }
                MathOp::Call { name, arity } => {
                    let before = stack.len();
                    if before < *arity {
                        bail!("internal error: RPN stack underflow");
                    }
                    let mut taken: Vec<StaticTy> = stack.split_off(before - arity);
                    taken.reverse();
                    // RPN operands carry no literal forms, so closed
                    // `#[values]` sets cannot be checked here; shape and
                    // arity still are. (Math-position calls are
                    // numeric builtins in practice.)
                    let blanks = vec![None; taken.len()];
                    let callee = self.resolve_call(name, depth)?;
                    let ret = self.apply_checked(name, &callee, &taken, &blanks, None)?;
                    stack.push(ret);
                }
                MathOp::Inspect(name) => {
                    let key = clean_var(name);
                    if !env.is_declared(&key) {
                        bail!("undefined variable ${key}");
                    }
                    env.read_guarded(&key, scope.site.as_ref())?;
                    stack.push(StaticTy::Ty(TypeTag::Any));
                }
                MathOp::Neg => {
                    let Some(top) = stack.pop() else {
                        bail!("internal error: RPN stack underflow");
                    };
                    stack.push(neg_rule(top, None)?);
                }
                MathOp::Add | MathOp::Sub | MathOp::Mul | MathOp::Div => {
                    let (Some(right), Some(left)) = (stack.pop(), stack.pop()) else {
                        bail!("internal error: RPN stack underflow");
                    };
                    stack.push(numeric_pair(left, right, None)?);
                }
                MathOp::Lt | MathOp::Le | MathOp::Gt | MathOp::Ge => {
                    let (Some(right), Some(left)) = (stack.pop(), stack.pop()) else {
                        bail!("internal error: RPN stack underflow");
                    };
                    ordering_pair(left, right, None)?;
                    stack.push(StaticTy::Ty(TypeTag::Bool));
                }
                MathOp::Eq | MathOp::Ne => {
                    if stack.pop().is_none() || stack.pop().is_none() {
                        bail!("internal error: RPN stack underflow");
                    }
                    stack.push(StaticTy::Ty(TypeTag::Bool));
                }
            }
        }
        if stack.len() != 1 {
            bail!("internal error: RPN stack left {} values", stack.len());
        }
        Ok(stack.pop().expect("length checked"))
    }
}

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

    fn static_bool(value: &str) -> GuardExpr {
        GuardExpr::Predicate(Guard::Attr {
            ns: oxdock_parser::Ns::Bool,
            key: None,
            val: Some(value.to_string()),
        })
    }

    #[test]
    fn guard_trichotomy_classifies_statically() {
        assert_eq!(classify_guard(None), GuardClass::Unconditional);
        assert_eq!(
            classify_guard(Some(&static_bool("true"))),
            GuardClass::Unconditional
        );
        assert_eq!(
            classify_guard(Some(&static_bool("false"))),
            GuardClass::Dead
        );
        assert_eq!(
            classify_guard(Some(&GuardExpr::All(vec![static_bool("true")]))),
            GuardClass::Unconditional
        );
        assert_eq!(
            classify_guard(Some(&GuardExpr::All(vec![static_bool("false")]))),
            GuardClass::Dead
        );
        assert_eq!(
            classify_guard(Some(&GuardExpr::Not(Box::new(static_bool("false"))))),
            GuardClass::Unconditional
        );
    }

    #[test]
    fn unify_widens_any_unidirectionally() {
        assert!(tags_equal(
            &unify(TypeTag::Int, TypeTag::Int, "t").expect("same"),
            &TypeTag::Int
        ));
        assert!(tags_equal(
            &unify(TypeTag::Int, TypeTag::Any, "t").expect("widen"),
            &TypeTag::Any
        ));
        assert!(tags_equal(
            &unify(TypeTag::Any, TypeTag::Map, "t").expect("widen"),
            &TypeTag::Any
        ));
        assert!(unify(TypeTag::Int, TypeTag::String, "t").is_err());
    }
}