noxid-cli 0.2.1

The Noxid compiler command line: check, build, test, adapt, and the agent surface
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
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
use noxid_ai_eval::AffectedTestSelection;
use noxid_codegen_js::emit_scenario_expression;
use noxid_ir::{
    AgentDefinition, AgentScenarioTurn, ComponentDefinition, EndpointDefinition,
    PropertyDefinition, QueueDefinition, QueueHandler, ScenarioGivenKind, SemanticExpr,
    SemanticExprKind, SemanticId, SemanticTemplatePart, TaskDefinition, TaskHandler,
};
use noxid_property_gen::{GeneratedCase, GeneratedValue, Schema};
use noxid_source::{SourceFile, js_escape, json_escape};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::modules;

/// A scenario runs a compiler-owned task or queue handler outside the server
/// dispatcher, so the handler context is supplied here. Tasks execute under
/// the system principal at runtime (`__NOXID_SYSTEM_PRINCIPAL`) and a queue
/// scenario enqueues without a request, so `System` is the honest principal
/// for both — and the shape is exactly the frozen runtime value ADR 0137
/// rule 5 keeps unchanged.
const SCENARIO_SYSTEM_CONTEXT: &str = "Object.freeze({ principal: Object.freeze({ kind: \"system\", canonical: \"system\", scope: null, agent: null }) })";

static NEXT_SCRATCH_DIRECTORY: AtomicU64 = AtomicU64::new(0);
const SCENARIO_HARNESS_TIMEOUT: Duration = Duration::from_secs(300);
const PROPERTY_NODE_STARTUP_TIMEOUT: Duration = Duration::from_secs(5);
const PROPERTY_VALIDATION_KILL_ALLOWANCE: Duration = Duration::from_secs(1);
const PROPERTY_VALIDATION_MARKER: &str = ".noxid-property-validation-started";
const PROPERTY_OUTCOME_SENTINEL: &str = "__NOXID_PROPERTY_OUTCOME__:";

pub(crate) struct Options {
    pub(crate) gate: bool,
    pub(crate) json_only: bool,
}

pub(crate) struct ScenarioRunReport {
    pub(crate) json: String,
    pub(crate) stderr: String,
    pub(crate) success: bool,
}

pub(crate) fn affected_report_json(
    selection: &AffectedTestSelection,
    execution: &ScenarioRunReport,
) -> String {
    let changed = selection
        .changed
        .iter()
        .map(|id| format!("\"{}\"", json_escape(id.as_str())))
        .collect::<Vec<_>>()
        .join(",");
    let uncovered = selection
        .uncovered_changes
        .iter()
        .map(|id| format!("\"{}\"", json_escape(id.as_str())))
        .collect::<Vec<_>>()
        .join(",");
    format!(
        "{{\"schemaVersion\":1,\"mode\":\"emitted-artifact\",\"ok\":{},\"changed\":[{changed}],\"selectedCount\":{},\"uncoveredChanges\":[{uncovered}],\"execution\":{}}}",
        execution.success,
        selection.scenarios.len(),
        execution.json,
    )
}

#[derive(Clone)]
struct TestComponent {
    definition: ComponentDefinition,
    source: SourceFile,
}

#[derive(Clone)]
struct TestEndpoint {
    definition: EndpointDefinition,
    source: SourceFile,
}

#[derive(Clone)]
struct TestAgent {
    definition: AgentDefinition,
    source: SourceFile,
}

#[derive(Clone)]
struct TestTask {
    definition: TaskDefinition,
    source: SourceFile,
}

#[derive(Clone)]
struct TestQueue {
    definition: QueueDefinition,
    source: SourceFile,
}

#[derive(Clone)]
struct TestProperty {
    definition: PropertyDefinition,
    boundary_kind: &'static str,
    boundary_name: String,
    validator_module: String,
    validators: Vec<(SemanticId, Schema)>,
    timeout: Duration,
}

struct PropertyExecution {
    javascript: String,
}

struct ScratchDirectory(PathBuf);

#[derive(Clone, Copy)]
struct ScenarioCheckpoint<'a> {
    phase: &'static str,
    index: usize,
    target: Option<&'a str>,
}

impl ScenarioCheckpoint<'_> {
    fn as_javascript(self) -> String {
        let target = self
            .target
            .map(|target| format!("\"{}\"", json_escape(target)))
            .unwrap_or_else(|| "null".into());
        format!(
            "{{ phase: \"{}\", index: {}, target: {target} }}",
            self.phase, self.index
        )
    }
}

impl Drop for ScratchDirectory {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

pub(crate) fn run(
    input: &Path,
    options: Options,
    seed: Option<u64>,
    property_selector: Option<&str>,
) -> Result<(), String> {
    let contract_update = options
        .gate
        .then(|| crate::project::prepare_api_contract_gate(input))
        .transpose()?
        .flatten();
    let output = report_from_output(execute_with_selection_and_seed(
        input,
        &options,
        None,
        seed,
        property_selector,
    )?)?;
    println!("{}", output.json);
    // The split is the contract, and `--json` does not change it: stdout is
    // the one report line and everything the run logged — every trace record
    // the emitted server wrote at any `[server] tracing` level, and every
    // refusal it printed — stays NDJSON on stderr. `--json` only suppresses
    // the harness's own human summary line, which it does at the source.
    eprint!("{}", output.stderr);
    if output.success {
        if let Some(update) = contract_update {
            crate::project::apply_api_contract_update(update)?;
        }
        Ok(())
    } else {
        Err("one or more Noxid scenarios failed".into())
    }
}

fn execute(input: &Path, options: &Options) -> Result<Output, String> {
    execute_with_selection_and_seed(input, options, None, None, None)
}

pub(crate) fn execute_report(input: &Path, options: &Options) -> Result<ScenarioRunReport, String> {
    report_from_output(execute(input, options)?)
}

pub(crate) fn execute_selected_report(
    input: &Path,
    options: &Options,
    selected: &BTreeSet<SemanticId>,
) -> Result<ScenarioRunReport, String> {
    report_from_output(execute_with_selection(input, options, Some(selected))?)
}

fn report_from_output(output: Output) -> Result<ScenarioRunReport, String> {
    let json = String::from_utf8(output.stdout)
        .map_err(|error| format!("scenario runner returned non-UTF-8 JSON: {error}"))?;
    let stderr = String::from_utf8(output.stderr)
        .map_err(|error| format!("scenario runner returned non-UTF-8 diagnostics: {error}"))?;
    Ok(ScenarioRunReport {
        json: json.trim().into(),
        stderr,
        success: output.status.success(),
    })
}

fn execute_with_selection(
    input: &Path,
    options: &Options,
    selected: Option<&BTreeSet<SemanticId>>,
) -> Result<Output, String> {
    execute_with_selection_and_seed(input, options, selected, None, None)
}

fn execute_with_selection_and_seed(
    input: &Path,
    options: &Options,
    selected: Option<&BTreeSet<SemanticId>>,
    seed: Option<u64>,
    property_selector: Option<&str>,
) -> Result<Output, String> {
    let root = project_root(input)?;
    let analysis_options = crate::project::project_analysis_options(input);
    let entries = scenario_entries(input, &root)?;
    let scratch = scratch_directory()?;
    let project_components = root.join("src/components");
    let sibling_components = root.join("components");
    let auto_components = if project_components.exists() {
        project_components
    } else {
        sibling_components
    };
    let auto_components = auto_components
        .exists()
        .then_some(auto_components.as_path());
    let mut runtime_imports = BTreeSet::from(["flush".to_string()]);
    let mut components = BTreeMap::<SemanticId, TestComponent>::new();
    let mut component_origins = BTreeMap::<SemanticId, PathBuf>::new();
    let mut endpoint_sources = BTreeMap::<SemanticId, SourceFile>::new();
    let mut endpoint_origins = BTreeMap::<SemanticId, PathBuf>::new();
    let mut endpoint_scenario_ids = BTreeSet::<SemanticId>::new();
    let mut agent_sources = BTreeMap::<SemanticId, SourceFile>::new();
    let mut agent_scenario_ids = BTreeSet::<SemanticId>::new();
    let mut tasks = BTreeMap::<SemanticId, TestTask>::new();
    let mut task_origins = BTreeMap::<SemanticId, PathBuf>::new();
    let mut queues = BTreeMap::<SemanticId, TestQueue>::new();
    let mut queue_origins = BTreeMap::<SemanticId, PathBuf>::new();
    let mut properties = BTreeMap::<SemanticId, TestProperty>::new();
    let mut emitted_modules = BTreeSet::new();

    for entry in entries {
        let graph = modules::compile_module_graph_with_options(
            &entry,
            &root,
            auto_components,
            &BTreeMap::new(),
            &analysis_options,
        )?;
        refuse_transitive_boundaries(&graph, selected)?;
        for (_, module) in graph.modules() {
            for diagnostic in &module.compilation.diagnostics {
                if !options.json_only {
                    eprintln!("{}", diagnostic.render(&module.source));
                }
            }
            if selected.is_none() {
                collect_module_properties(module, &mut properties)?;
            }
            runtime_imports.extend(module.compilation.runtime_imports());
            for component in &module.compilation.program.components {
                let origin = module.source.path().to_path_buf();
                if let Some(existing) = component_origins.get(&component.id) {
                    if existing != &origin {
                        return Err(format!(
                            "DUPLICATE_COMPONENT_ID: `{}` is declared by both {} and {}; project tests require one stable owner per component semantic ID",
                            component.id,
                            existing.display(),
                            origin.display()
                        ));
                    }
                } else {
                    component_origins.insert(component.id.clone(), origin);
                }
            }
            for endpoint in &module.compilation.program.endpoints {
                endpoint_scenario_ids.extend(
                    endpoint
                        .scenarios
                        .iter()
                        .map(|scenario| scenario.id.clone()),
                );
                let origin = module.source.path().to_path_buf();
                if let Some(existing) = endpoint_origins.get(&endpoint.id) {
                    if existing != &origin {
                        return Err(format!(
                            "DUPLICATE_ENDPOINT_ID: `{}` is declared by both {} and {}; project tests require one stable owner per endpoint semantic ID",
                            endpoint.id,
                            existing.display(),
                            origin.display()
                        ));
                    }
                } else {
                    endpoint_origins.insert(endpoint.id.clone(), origin);
                    endpoint_sources.insert(endpoint.id.clone(), module.source.clone());
                }
            }
            for agent in &module.compilation.program.agents {
                agent_scenario_ids
                    .extend(agent.scenarios.iter().map(|scenario| scenario.id.clone()));
                agent_sources
                    .entry(agent.id.clone())
                    .or_insert_with(|| module.source.clone());
            }
            for task in &module.compilation.program.tasks {
                let origin = module.source.path().to_path_buf();
                if let Some(existing) = task_origins.get(&task.id) {
                    if existing != &origin {
                        return Err(format!(
                            "DUPLICATE_TASK_ID: `{}` is declared by both {} and {}; project tests require one stable owner per task semantic ID",
                            task.id,
                            existing.display(),
                            origin.display()
                        ));
                    }
                    continue;
                }
                task_origins.insert(task.id.clone(), origin);
                let mut definition = task.clone();
                if let Some(selected) = selected {
                    definition
                        .scenarios
                        .retain(|scenario| selected.contains(&scenario.id));
                }
                if !definition.scenarios.is_empty() {
                    tasks.insert(
                        definition.id.clone(),
                        TestTask {
                            definition,
                            source: module.source.clone(),
                        },
                    );
                }
            }
            for queue in &module.compilation.program.queues {
                let origin = module.source.path().to_path_buf();
                if let Some(existing) = queue_origins.get(&queue.id) {
                    if existing != &origin {
                        return Err(format!(
                            "DUPLICATE_QUEUE_ID: `{}` is declared by both {} and {}; project tests require one stable owner per queue semantic ID",
                            queue.id,
                            existing.display(),
                            origin.display()
                        ));
                    }
                    continue;
                }
                queue_origins.insert(queue.id.clone(), origin);
                let mut definition = queue.clone();
                if let Some(selected) = selected {
                    definition
                        .scenarios
                        .retain(|scenario| selected.contains(&scenario.id));
                }
                if !definition.scenarios.is_empty() {
                    queues.insert(
                        definition.id.clone(),
                        TestQueue {
                            definition,
                            source: module.source.clone(),
                        },
                    );
                }
            }
            emit_compilation(&scratch.0, module, &mut emitted_modules)?;
            for component in &module.compilation.program.components {
                let mut definition = component.clone();
                if let Some(selected) = selected {
                    definition
                        .scenarios
                        .retain(|scenario| selected.contains(&scenario.id));
                }
                if definition.scenarios.is_empty()
                    && (selected.is_some() || definition.requirements.is_empty())
                {
                    continue;
                }
                components
                    .entry(definition.id.clone())
                    .or_insert_with(|| TestComponent {
                        definition,
                        source: module.source.clone(),
                    });
            }
        }
    }

    let mut endpoints = BTreeMap::<SemanticId, TestEndpoint>::new();
    let mut agents = BTreeMap::<SemanticId, TestAgent>::new();
    let has_selected_endpoint_scenario = endpoint_scenario_ids
        .iter()
        .any(|scenario| selected.is_none_or(|selected| selected.contains(scenario)));
    // An agent scenario drives `POST /_noxid/agents/<Agent>/runs`, which the
    // same emitted server handler serves, so it needs the same artifact an
    // endpoint scenario needs — and it needs the project's derived tool
    // registry, which a single-file compilation of the route that declares the
    // agent cannot see.
    let has_selected_agent_scenario = agent_scenario_ids
        .iter()
        .any(|scenario| selected.is_none_or(|selected| selected.contains(scenario)));
    let endpoint_handler_module = if (!endpoint_sources.is_empty()
        && has_selected_endpoint_scenario)
        || (!agent_sources.is_empty() && has_selected_agent_scenario)
    {
        let (project_input, _) = crate::project::source_import_context(input)?.ok_or_else(|| {
            "error[ENDPOINT_SCENARIO_PROJECT_REQUIRED]: endpoint and agent scenarios execute the shipped file-based Fetch handler and therefore require an enclosing Noxid.toml project; place this endpoint under server/api/ or server/routes/ in a project and run `noxid test <project> --gate`".to_string()
        })?;
        let endpoint_out = scratch.0.join("endpoint-dist");
        let surface =
            crate::project::build_endpoint_scenario_artifact(&project_input, &endpoint_out)?;
        install_endpoint_scenario_boundary_stubs(&endpoint_out)?;
        for mut definition in surface.endpoints {
            let Some(source) = endpoint_sources.get(&definition.id).cloned() else {
                continue;
            };
            if let Some(selected) = selected {
                definition
                    .scenarios
                    .retain(|scenario| selected.contains(&scenario.id));
            }
            if definition.scenarios.is_empty() {
                continue;
            }
            endpoints.insert(definition.id.clone(), TestEndpoint { definition, source });
        }
        for mut definition in surface.agents {
            let Some(source) = agent_sources.get(&definition.id).cloned() else {
                continue;
            };
            if let Some(selected) = selected {
                definition
                    .scenarios
                    .retain(|scenario| selected.contains(&scenario.id));
            }
            if definition.scenarios.is_empty() {
                continue;
            }
            agents.insert(definition.id.clone(), TestAgent { definition, source });
        }
        Some("./endpoint-dist/server/handler.js")
    } else {
        None
    };

    write_file(
        &scratch.0.join("noxid-runtime.js"),
        &noxid_compiler_core::scenario_runtime_javascript_for_imports(&runtime_imports),
    )?;
    write_file(
        &scratch.0.join("package.json"),
        "{\"private\":true,\"type\":\"module\"}\n",
    )?;
    link_project_packages(&root, &scratch.0)?;
    let property_execution = execute_properties(
        &scratch.0,
        input,
        &properties,
        options,
        seed,
        property_selector,
    )?;
    let harness = generate_harness(
        &components,
        &endpoints,
        &agents,
        &tasks,
        &queues,
        endpoint_handler_module,
        &property_execution,
        options,
    )?;
    let harness_path = scratch.0.join("scenarios.mjs");
    write_file(&harness_path, &harness)?;
    run_node_with_timeout(&harness_path, &scratch.0, SCENARIO_HARNESS_TIMEOUT)
}

fn run_node_with_timeout(
    harness_path: &Path,
    current_dir: &Path,
    timeout: Duration,
) -> Result<Output, String> {
    let mut command = Command::new("node");
    command
        .arg(harness_path)
        .current_dir(current_dir)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    configure_node_process_group(&mut command);
    let mut child = command
        .spawn()
        .map_err(|error| format!("cannot execute Node.js scenario harness: {error}"))?;
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| "Node.js scenario harness stdout was not piped".to_string())?;
    let mut stderr = child
        .stderr
        .take()
        .ok_or_else(|| "Node.js scenario harness stderr was not piped".to_string())?;
    let stdout_drain = thread::spawn(move || {
        let mut output = Vec::new();
        stdout.read_to_end(&mut output).map(|_| output)
    });
    let stderr_drain = thread::spawn(move || {
        let mut output = Vec::new();
        stderr.read_to_end(&mut output).map(|_| output)
    });
    let started = Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let stdout = join_scenario_pipe(stdout_drain, "stdout")?;
                let stderr = join_scenario_pipe(stderr_drain, "stderr")?;
                return Ok(Output {
                    status,
                    stdout,
                    stderr,
                });
            }
            Ok(None) if started.elapsed() < timeout => {
                thread::sleep(Duration::from_millis(10));
            }
            Ok(None) => {
                terminate_node_process_group(&mut child);
                let _ = stdout_drain.join();
                let _ = stderr_drain.join();
                return Err(format!(
                    "SCENARIO_TIMEOUT_EXCEEDED: Node.js scenario harness exceeded its {}ms wall-clock budget and was killed; add a finite boundary timeout or remove the non-terminating scenario behavior",
                    timeout.as_millis()
                ));
            }
            Err(error) => {
                terminate_node_process_group(&mut child);
                let _ = stdout_drain.join();
                let _ = stderr_drain.join();
                return Err(format!(
                    "cannot inspect Node.js scenario harness status: {error}"
                ));
            }
        }
    }
}

fn configure_node_process_group(command: &mut Command) {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt as _;
        command.process_group(0);
    }
}

fn terminate_node_process_group(child: &mut Child) {
    #[cfg(unix)]
    {
        let process_group = format!("-{}", child.id());
        let _ = Command::new("kill")
            .args(["-s", "KILL", &process_group])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
    let _ = child.kill();
    let _ = child.wait();
}

fn join_scenario_pipe(
    drain: thread::JoinHandle<std::io::Result<Vec<u8>>>,
    name: &str,
) -> Result<Vec<u8>, String> {
    drain
        .join()
        .map_err(|_| {
            format!("cannot collect Node.js scenario harness {name}: drain thread panicked")
        })?
        .map_err(|error| format!("cannot collect Node.js scenario harness {name}: {error}"))
}

fn run_node_with_validation_timeout(
    harness_path: &Path,
    current_dir: &Path,
    validation_timeout: Duration,
) -> Result<Output, PropertyRunnerError> {
    let marker = current_dir.join(PROPERTY_VALIDATION_MARKER);
    match fs::remove_file(&marker) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(PropertyRunnerError::Other(format!(
                "cannot reset property validation marker {}: {error}",
                marker.display()
            )));
        }
    }
    let mut command = Command::new("node");
    command
        .arg(harness_path)
        .current_dir(current_dir)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    configure_node_process_group(&mut command);
    let mut child = command.spawn().map_err(|error| {
        PropertyRunnerError::Other(format!("cannot execute Node.js property harness: {error}"))
    })?;
    let mut stdout = child.stdout.take().ok_or_else(|| {
        PropertyRunnerError::Other("Node.js property harness stdout was not piped".into())
    })?;
    let mut stderr = child.stderr.take().ok_or_else(|| {
        PropertyRunnerError::Other("Node.js property harness stderr was not piped".into())
    })?;
    let stdout_drain = thread::spawn(move || {
        let mut output = Vec::new();
        stdout.read_to_end(&mut output).map(|_| output)
    });
    let stderr_drain = thread::spawn(move || {
        let mut output = Vec::new();
        stderr.read_to_end(&mut output).map(|_| output)
    });
    let startup_started = Instant::now();
    let mut validation_started = None;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let stdout = join_property_pipe(stdout_drain, "stdout")?;
                let stderr = join_property_pipe(stderr_drain, "stderr")?;
                return Ok(Output {
                    status,
                    stdout,
                    stderr,
                });
            }
            Ok(None) => {
                if validation_started.is_none() && marker.is_file() {
                    validation_started = Some(Instant::now());
                }
                let kill_timeout = validation_timeout + PROPERTY_VALIDATION_KILL_ALLOWANCE;
                if validation_started.is_some_and(|started| started.elapsed() >= kill_timeout) {
                    terminate_node_process_group(&mut child);
                    let _ = stdout_drain.join();
                    let _ = stderr_drain.join();
                    return Err(PropertyRunnerError::ValidationTimeout(format!(
                        "SCENARIO_TIMEOUT_EXCEEDED: boundary validation did not return within its {}ms budget plus the {}ms runner kill allowance and was killed; Node measures finite validator work internally, while this outer allowance preserves killability for a synchronous hang",
                        validation_timeout.as_millis(),
                        PROPERTY_VALIDATION_KILL_ALLOWANCE.as_millis()
                    )));
                }
                if validation_started.is_none()
                    && startup_started.elapsed() >= PROPERTY_NODE_STARTUP_TIMEOUT
                {
                    terminate_node_process_group(&mut child);
                    let _ = stdout_drain.join();
                    let _ = stderr_drain.join();
                    return Err(PropertyRunnerError::Unavailable(format!(
                        "Node.js property harness did not reach validation within its {}ms startup safety budget and was killed; retry when the Node runner is available",
                        PROPERTY_NODE_STARTUP_TIMEOUT.as_millis()
                    )));
                }
                thread::sleep(Duration::from_millis(10));
            }
            Err(error) => {
                terminate_node_process_group(&mut child);
                let _ = stdout_drain.join();
                let _ = stderr_drain.join();
                return Err(PropertyRunnerError::Other(format!(
                    "cannot inspect Node.js property harness status: {error}"
                )));
            }
        }
    }
}

fn join_property_pipe(
    drain: thread::JoinHandle<std::io::Result<Vec<u8>>>,
    name: &str,
) -> Result<Vec<u8>, PropertyRunnerError> {
    drain
        .join()
        .map_err(|_| {
            PropertyRunnerError::Other(format!(
                "cannot collect Node.js property harness {name}: drain thread panicked"
            ))
        })?
        .map_err(|error| {
            PropertyRunnerError::Other(format!(
                "cannot collect Node.js property harness {name}: {error}"
            ))
        })
}

enum PropertyRunnerError {
    Unavailable(String),
    ValidationTimeout(String),
    Other(String),
}

fn collect_module_properties(
    module: &noxid_workspace::CompiledModule,
    properties: &mut BTreeMap<SemanticId, TestProperty>,
) -> Result<(), String> {
    let stem = module
        .source
        .path()
        .file_stem()
        .and_then(|value| value.to_str())
        .ok_or_else(|| format!("{} has no valid file stem", module.source.path().display()))?;
    let validator_module = format!("./{stem}.validators.js");
    let validation = &module.compilation.validation;

    for endpoint in &module.compilation.program.endpoints {
        let validators = validation
            .endpoint_boundaries
            .iter()
            .filter(|boundary| {
                boundary.endpoint == endpoint.id
                    && boundary.section != noxid_validation_ir::EndpointValidationSection::Result
            })
            .filter_map(|boundary| {
                validation
                    .validators
                    .iter()
                    .find(|validator| validator.id == boundary.validator)
                    .map(|validator| {
                        (
                            boundary.validator.clone(),
                            Schema::from_validator(&validator.node, &validation.validators),
                        )
                    })
            })
            .collect::<Vec<_>>();
        for property in &endpoint.properties {
            insert_test_property(
                properties,
                TestProperty {
                    definition: property.clone(),
                    boundary_kind: "endpoint",
                    boundary_name: endpoint.name.clone(),
                    validator_module: validator_module.clone(),
                    validators: validators.clone(),
                    timeout: Duration::from_millis(if endpoint.timeout.defaulted {
                        1_000
                    } else {
                        endpoint.timeout.milliseconds.max(50)
                    }),
                },
            )?;
        }
    }

    for queue in &module.compilation.program.queues {
        let validator_id = SemanticId::queue_validator(&queue.name);
        let validators = validation
            .validators
            .iter()
            .find(|validator| validator.id == validator_id)
            .map(|validator| {
                vec![(
                    validator_id,
                    Schema::from_validator(&validator.node, &validation.validators),
                )]
            })
            .unwrap_or_default();
        for property in &queue.properties {
            insert_test_property(
                properties,
                TestProperty {
                    definition: property.clone(),
                    boundary_kind: "queue",
                    boundary_name: queue.name.clone(),
                    validator_module: validator_module.clone(),
                    validators: validators.clone(),
                    timeout: Duration::from_secs(1),
                },
            )?;
        }
    }
    Ok(())
}

fn insert_test_property(
    properties: &mut BTreeMap<SemanticId, TestProperty>,
    property: TestProperty,
) -> Result<(), String> {
    if let Some(existing) = properties.get(&property.definition.id) {
        if existing.validator_module == property.validator_module {
            return Ok(());
        }
        return Err(format!(
            "DUPLICATE_PROPERTY_ID: `{}` is declared by both {} and {}; property identities require one stable owner",
            property.definition.id, existing.validator_module, property.validator_module
        ));
    }
    properties.insert(property.definition.id.clone(), property);
    Ok(())
}

enum PropertyCaseOutcome {
    Pass,
    Violation(String),
    Timeout(String),
    RunnerUnavailable(String),
}

fn execute_properties(
    scratch: &Path,
    input: &Path,
    properties: &BTreeMap<SemanticId, TestProperty>,
    options: &Options,
    seed: Option<u64>,
    property_selector: Option<&str>,
) -> Result<PropertyExecution, String> {
    let replay_property = replay_property(properties, seed, property_selector)?;
    let include_property_selector = properties.len() > 1;
    let mut javascript = String::new();
    for property in properties.values() {
        if replay_property.is_some_and(|id| id != &property.definition.id) {
            continue;
        }
        if property.validators.is_empty() {
            return Err(format!(
                "PROPERTY_NO_FUZZABLE_BOUNDARY: property `{}` has no generated input validator",
                property.definition.name
            ));
        }
        let declared_runs = if options.gate {
            property.definition.runs.max(100)
        } else {
            property.definition.runs
        };
        let runs = if seed.is_some() { 1 } else { declared_runs };
        let mut failure = None;
        for scheduled_run in 0..runs {
            let run_index = seed.map_or(scheduled_run, |seed| seed as u32);
            let validator_index = run_index as usize % property.validators.len();
            let (validator, schema) = &property.validators[validator_index];
            let case = seed.map_or_else(
                || {
                    noxid_property_gen::generate_case(
                        schema,
                        property.definition.id.as_str(),
                        run_index,
                    )
                },
                |seed| noxid_property_gen::generate_case_from_seed(schema, seed),
            );
            match execute_property_case(scratch, property, validator, &case.value)? {
                PropertyCaseOutcome::Pass => {}
                PropertyCaseOutcome::Timeout(message) => {
                    failure = Some(PropertyFailure::case(
                        run_index,
                        &case,
                        &case.value,
                        "PROPERTY_TIMEOUT_EXCEEDED",
                        &message,
                        input,
                        include_property_selector.then_some(property.definition.id.as_str()),
                    ));
                    break;
                }
                PropertyCaseOutcome::RunnerUnavailable(message) => {
                    failure = Some(PropertyFailure::RunnerUnavailable { message });
                    break;
                }
                PropertyCaseOutcome::Violation(message) => {
                    let mut shrunk = case.value.clone();
                    for candidate in noxid_property_gen::shrink_candidates_bounded(&case.value, 128)
                    {
                        if matches!(
                            execute_property_case(scratch, property, validator, &candidate)?,
                            PropertyCaseOutcome::Violation(_)
                        ) {
                            shrunk = candidate;
                            break;
                        }
                    }
                    failure = Some(PropertyFailure::case(
                        run_index,
                        &case,
                        &shrunk,
                        "PROPERTY_INVARIANT_VIOLATED",
                        &message,
                        input,
                        include_property_selector.then_some(property.definition.id.as_str()),
                    ));
                    break;
                }
            }
        }
        javascript.push_str(&property_result_javascript(
            property,
            runs,
            failure.as_ref(),
        ));
    }
    Ok(PropertyExecution { javascript })
}

fn replay_property<'a>(
    properties: &'a BTreeMap<SemanticId, TestProperty>,
    seed: Option<u64>,
    property_selector: Option<&str>,
) -> Result<Option<&'a SemanticId>, String> {
    if seed.is_none() {
        return property_selector.map_or(Ok(None), |_| {
            Err("PROPERTY_REPLAY_SEED_REQUIRED: --property selects a seeded replay; add --seed <n>, or omit --property to run every declared property".into())
        });
    }
    if let Some(selector) = property_selector {
        let property = properties
            .keys()
            .find(|id| id.as_str() == selector)
            .ok_or_else(|| {
                let available = properties
                    .keys()
                    .map(SemanticId::as_str)
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    "PROPERTY_REPLAY_SELECTOR_UNKNOWN: --property `{selector}` does not name a property in this input; choose one of: {available}"
                )
            })?;
        let seed = seed.expect("seed presence checked above");
        let identity_mask = 0xffff_ffff_0000_0000;
        if seed & identity_mask
            != noxid_property_gen::property_seed(property.as_str(), 0) & identity_mask
        {
            return Err(format!(
                "PROPERTY_REPLAY_SEED_MISMATCH: --seed {seed} does not belong to --property `{selector}`; copy the seed and --property pair from the same failing report, or omit both flags to generate a new run"
            ));
        }
        return Ok(Some(property));
    }
    if properties.len() > 1 {
        let available = properties
            .keys()
            .map(SemanticId::as_str)
            .collect::<Vec<_>>()
            .join(", ");
        return Err(format!(
            "PROPERTY_REPLAY_SELECTOR_REQUIRED: --seed on an input with multiple properties requires --property <semantic-id>; choose one of: {available}"
        ));
    }
    let property = properties.keys().next();
    if let Some(property) = property {
        let seed = seed.expect("seed presence checked above");
        let identity_mask = 0xffff_ffff_0000_0000;
        if seed & identity_mask
            != noxid_property_gen::property_seed(property.as_str(), 0) & identity_mask
        {
            return Err(format!(
                "PROPERTY_REPLAY_SEED_MISMATCH: --seed {seed} does not belong to the only property `{property}` in this input; copy the seed from a failing report for this property, or omit --seed to generate a new run"
            ));
        }
    }
    Ok(property)
}

enum PropertyFailure {
    Case {
        seed: u64,
        run_index: u32,
        code: &'static str,
        message: String,
        counterexample: String,
        repro: String,
    },
    RunnerUnavailable {
        message: String,
    },
}

impl PropertyFailure {
    fn case(
        run_index: u32,
        case: &GeneratedCase,
        shrunk: &GeneratedValue,
        code: &'static str,
        message: &str,
        input: &Path,
        property_selector: Option<&str>,
    ) -> Self {
        let property_argument = property_selector.map_or_else(String::new, |property| {
            format!(" --property {}", shell_quote(property))
        });
        Self::Case {
            seed: case.seed,
            run_index,
            code,
            message: message.to_string(),
            counterexample: shrunk.to_repro_json(),
            repro: format!(
                "noxid test {} --seed {}{}",
                shell_quote(&input.to_string_lossy()),
                case.seed,
                property_argument,
            ),
        }
    }
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

fn property_result_javascript(
    property: &TestProperty,
    runs: u32,
    failure: Option<&PropertyFailure>,
) -> String {
    let identity = format!(
        "id: \"{}\", name: \"{}\", property: true, {}: \"{}\", semanticUnit: \"{}\", runs: {runs}, assertions: [], invariantFailures: [], covers: []",
        json_escape(property.definition.id.as_str()),
        json_escape(&property.definition.name),
        property.boundary_kind,
        json_escape(&property.boundary_name),
        json_escape(property.definition.boundary.as_str()),
    );
    failure.map_or_else(
        || {
            format!(
                "scenarioResults.push({{ {identity}, status: \"pass\", seed: null, counterexample: null, repro: null, failure: null }});\n"
            )
        },
        |failure| match failure {
            PropertyFailure::Case {
                seed,
                run_index,
                code,
                message,
                counterexample,
                repro,
            } => {
                let message = format!(
                    "{code}: property `{}` run {run_index} escaped `{message}`; seed {seed}; shrunk counterexample {counterexample}; repro {repro}",
                    property.definition.name,
                );
                format!(
                    "scenarioResults.push({{ {identity}, status: \"fail\", seed: \"{seed}\", counterexample: \"{}\", repro: \"{}\", failure: \"{}\" }});\n",
                    js_escape(counterexample),
                    js_escape(repro),
                    js_escape(&message),
                )
            }
            PropertyFailure::RunnerUnavailable { message } => {
                let message = format!(
                    "PROPERTY_RUNNER_UNAVAILABLE: property `{}` could not run because `{message}`",
                    property.definition.name,
                );
                format!(
                    "scenarioResults.push({{ {identity}, status: \"fail\", seed: null, counterexample: null, repro: null, failure: \"{}\" }});\n",
                    js_escape(&message),
                )
            }
        },
    )
}

fn execute_property_case(
    scratch: &Path,
    property: &TestProperty,
    validator: &SemanticId,
    value: &GeneratedValue,
) -> Result<PropertyCaseOutcome, String> {
    let script = format!(
        r#"import {{ writeFileSync }} from "node:fs";
import {{ typeValidators, ExternalValidationError }} from "{}";
const validator = typeValidators["{}"];
const value = {};
writeFileSync("{}", "started", {{ encoding: "utf8" }});
const validationStarted = process.cpuUsage();
let result;
let escaped = false;
try {{
  if (typeof validator !== "function") throw new Error("PROPERTY_VALIDATOR_MISSING");
  validator(value, true);
  result = {{ outcome: "accepted" }};
}} catch (error) {{
  const structured = error instanceof ExternalValidationError
    && error.code === "EXTERNAL_VALIDATION_FAILED"
    && Array.isArray(error.path)
    && typeof error.expected === "string"
    && typeof error.actual === "string";
  if (structured) result = {{ outcome: "refused", code: error.code }};
  else {{
    result = {{ outcome: "escaped", code: error?.code ?? null, message: error?.message ?? String(error) }};
    escaped = true;
  }}
}}
const validationUsage = process.cpuUsage(validationStarted);
const validationCpuMs = (validationUsage.user + validationUsage.system) / 1000;
if (validationCpuMs > {}) {{
  result = {{ outcome: "timeout", cpuMs: validationCpuMs }};
  escaped = true;
}}
process.stdout.write("\n{}" + JSON.stringify(result) + "\n");
if (escaped) process.exitCode = 1;
"#,
        json_escape(&property.validator_module),
        json_escape(validator.as_str()),
        value.to_javascript(),
        PROPERTY_VALIDATION_MARKER,
        property.timeout.as_millis(),
        PROPERTY_OUTCOME_SENTINEL,
    );
    let path = scratch.join("property-case.mjs");
    write_file(&path, &script)?;
    match run_node_with_validation_timeout(&path, scratch, property.timeout) {
        Ok(output) => {
            let stdout = String::from_utf8(output.stdout)
                .map_err(|error| format!("property runner returned non-UTF-8 JSON: {error}"))?;
            let Some((outcome, record)) = property_outcome(&stdout) else {
                return Ok(PropertyCaseOutcome::Violation(format!(
                    "PROPERTY_RUNNER_PROTOCOL_INVALID: property runner did not emit its sentinel-prefixed final outcome record; stdout was {}",
                    stdout.trim()
                )));
            };
            match outcome {
                "timeout" => Ok(PropertyCaseOutcome::Timeout(format!(
                    "SCENARIO_TIMEOUT_EXCEEDED: boundary validation consumed more than {}ms of CPU after Node startup and module import; {record}",
                    property.timeout.as_millis(),
                ))),
                "accepted" | "refused" if output.status.success() => Ok(PropertyCaseOutcome::Pass),
                "escaped" => Ok(PropertyCaseOutcome::Violation(record.to_string())),
                other => Ok(PropertyCaseOutcome::Violation(format!(
                    "PROPERTY_RUNNER_PROTOCOL_INVALID: outcome `{other}` disagreed with process status {}; record {record}",
                    output.status
                ))),
            }
        }
        Err(PropertyRunnerError::Unavailable(error)) => {
            Ok(PropertyCaseOutcome::RunnerUnavailable(error))
        }
        Err(PropertyRunnerError::ValidationTimeout(error)) => {
            Ok(PropertyCaseOutcome::Timeout(error))
        }
        Err(PropertyRunnerError::Other(error)) => Err(error),
    }
}

fn property_outcome(stdout: &str) -> Option<(&str, &str)> {
    let record = stdout
        .lines()
        .rev()
        .find_map(|line| line.strip_prefix(PROPERTY_OUTCOME_SENTINEL))?;
    let outcome = record.strip_prefix("{\"outcome\":\"")?;
    let outcome = outcome.split_once('"')?.0;
    Some((outcome, record))
}

fn refuse_transitive_boundaries(
    graph: &noxid_workspace::ModuleGraph,
    selected: Option<&BTreeSet<SemanticId>>,
) -> Result<(), String> {
    let definitions = graph
        .modules()
        .flat_map(|(_, module)| module.compilation.program.components.iter())
        .map(|component| (component.name.as_str(), component))
        .collect::<BTreeMap<_, _>>();

    for component in definitions.values() {
        let executable_scenarios = component.scenarios.iter().filter(|scenario| {
            selected.is_none_or(|selected| selected.contains(&scenario.id))
                && (!scenario.typed_given.is_empty()
                    || !scenario.typed_when.is_empty()
                    || !scenario.typed_expect.is_empty())
        });
        for scenario in executable_scenarios {
            for reachable_name in graph.reachable_components(&component.name) {
                let Some(reachable) = definitions.get(reachable_name.as_str()) else {
                    continue;
                };
                if reachable.id == component.id {
                    continue;
                }
                if let Some(resource) = reachable.resources.first() {
                    return Err(format!(
                        "SCENARIO_RESOURCE_BOUNDARY_UNSTUBBED: scenario `{}` mounts component `{}` with unstubbed resource `{}`; put the scenario beside `{}` and add its lifecycle given there, or remove that child boundary from this deterministic scenario",
                        scenario.name, reachable.name, resource.name, resource.name
                    ));
                }
                if let Some(stream) = reachable.streams.first() {
                    return Err(format!(
                        "SCENARIO_STREAM_BOUNDARY_UNSTUBBED: scenario `{}` mounts component `{}` with unstubbed stream `{}`; put the scenario beside `{}` and add its finite event given there, or remove that child boundary from this deterministic scenario",
                        scenario.name, reachable.name, stream.name, stream.name
                    ));
                }
                if let Some(agent) = reachable.agents.first() {
                    return Err(format!(
                        "SCENARIO_AGENT_BOUNDARY_UNSTUBBED: scenario `{}` mounts component `{}` with unstubbed agent session `{}`; extract plain state/actions into a deterministic component until typed agent-session givens are supported",
                        scenario.name, reachable.name, agent.name
                    ));
                }
            }
        }
    }
    Ok(())
}

fn project_root(input: &Path) -> Result<PathBuf, String> {
    let canonical = fs::canonicalize(input)
        .map_err(|error| format!("cannot resolve {}: {error}", input.display()))?;
    if canonical.is_dir() {
        return Ok(canonical);
    }
    if canonical.file_name().and_then(|value| value.to_str()) == Some("Noxid.toml") {
        return canonical
            .parent()
            .map(Path::to_path_buf)
            .ok_or_else(|| format!("{} has no project directory", canonical.display()));
    }
    canonical
        .parent()
        .map(Path::to_path_buf)
        .ok_or_else(|| format!("{} has no source directory", canonical.display()))
}

fn scenario_entries(input: &Path, root: &Path) -> Result<Vec<PathBuf>, String> {
    let canonical = fs::canonicalize(input)
        .map_err(|error| format!("cannot resolve {}: {error}", input.display()))?;
    if canonical.extension().and_then(|value| value.to_str()) == Some("nox") {
        return Ok(vec![canonical]);
    }
    let mut entries = Vec::new();
    // Scan the project root rather than assuming `src/`: Noxid.toml may point
    // routes and components at custom directories. Generated/dependency
    // directories are pruned by `collect_noxid_files` below.
    collect_noxid_files(root, &mut entries)?;
    entries.sort();
    if entries.is_empty() {
        return Err(format!("{} contains no .nox source files", root.display()));
    }
    Ok(entries)
}

fn collect_noxid_files(directory: &Path, output: &mut Vec<PathBuf>) -> Result<(), String> {
    let mut entries = fs::read_dir(directory)
        .map_err(|error| format!("cannot read {}: {error}", directory.display()))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| format!("cannot read {}: {error}", directory.display()))?;
    entries.sort_by_key(|entry| entry.path());
    for entry in entries {
        let path = entry.path();
        if path.is_dir() {
            if matches!(
                path.file_name().and_then(|value| value.to_str()),
                Some("target" | "dist" | "node_modules" | ".git")
            ) {
                continue;
            }
            collect_noxid_files(&path, output)?;
        } else if path.extension().and_then(|value| value.to_str()) == Some("nox") {
            output.push(path);
        }
    }
    Ok(())
}

fn scratch_directory() -> Result<ScratchDirectory, String> {
    let ordinal = NEXT_SCRATCH_DIRECTORY.fetch_add(1, Ordering::Relaxed);
    let nonce = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|error| format!("system clock cannot create scenario directory: {error}"))?
        .as_nanos();
    let path = std::env::temp_dir().join(format!(
        "noxid-scenarios-{}-{nonce}-{ordinal}",
        std::process::id()
    ));
    fs::create_dir_all(&path)
        .map_err(|error| format!("cannot create {}: {error}", path.display()))?;
    Ok(ScratchDirectory(path))
}

fn emit_compilation(
    directory: &Path,
    module: &noxid_workspace::CompiledModule,
    emitted_modules: &mut BTreeSet<String>,
) -> Result<(), String> {
    let stem = module
        .source
        .path()
        .file_stem()
        .and_then(|value| value.to_str())
        .ok_or_else(|| format!("{} has no valid file stem", module.source.path().display()))?;
    if let Some(generated) = &module.compilation.generated {
        if generated.modules.is_empty() {
            for component in &module.compilation.program.components {
                let name = format!("{}.js", component.name);
                if emitted_modules.insert(name.clone()) {
                    write_file(&directory.join(name), &generated.javascript)?;
                }
            }
        } else {
            for generated_module in &generated.modules {
                let name = format!("{}.js", generated_module.component);
                if emitted_modules.insert(name.clone()) {
                    write_file(&directory.join(name), &generated_module.javascript)?;
                }
            }
        }
    }
    for (suffix, contents) in [
        (
            "validators",
            module.compilation.generated_validators.as_deref(),
        ),
        (
            "resources",
            module.compilation.generated_resources.as_deref(),
        ),
        ("streams", module.compilation.generated_streams.as_deref()),
        ("agents", module.compilation.generated_agents.as_deref()),
    ] {
        if let Some(contents) = contents {
            let name = format!("{stem}.{suffix}.js");
            if emitted_modules.insert(name.clone()) {
                write_file(&directory.join(name), contents)?;
            }
        }
    }
    Ok(())
}

/// The scenario harness runs the shipped server handler out of a scratch
/// directory, so bare package specifiers in emitted server modules (the vetted
/// Drizzle adapter imports `drizzle-orm` and `postgres`) have no resolution
/// root. Point one at the project's installed packages; an absent
/// `node_modules` is not an error here, because a project whose server modules
/// import nothing needs none, and one that does gets Node's own
/// `ERR_MODULE_NOT_FOUND` naming the package to install.
fn link_project_packages(project_root: &Path, scratch: &Path) -> Result<(), String> {
    let packages = project_root.join("node_modules");
    if !packages.is_dir() {
        return Ok(());
    }
    let link = scratch.join("node_modules");
    #[cfg(unix)]
    let linked = std::os::unix::fs::symlink(&packages, &link);
    #[cfg(windows)]
    let linked = std::os::windows::fs::symlink_dir(&packages, &link);
    linked.map_err(|error| {
        format!(
            "cannot link {} into the scenario scratch directory: {error}",
            packages.display()
        )
    })
}

fn install_endpoint_scenario_boundary_stubs(out_dir: &Path) -> Result<(), String> {
    let server_dir = out_dir.join("server");
    // WO-30: a scenario that declares model givens is exercising its host
    // implementation with the model as its only external boundary, so the
    // project's real host is kept beside the stub and reached only for the
    // exact host keys that scenario authorized. Every other boundary stays
    // stubbed and live `fetch` stays banned by the harness.
    let real_host = server_dir.join("host.js");
    let delegate = server_dir.join("host.scenario-real.js");
    let delegation = if real_host.is_file() {
        fs::rename(&real_host, &delegate).map_err(|error| {
            format!("cannot set aside the project host for scenario delegation: {error}")
        })?;
        r#"    const delegated = globalThis.__NOXID_MODEL_SCENARIO__?.hostDelegation;
    if (delegated?.has(String(key))) {
      const host = await import("./host.scenario-real.js");
      const table = host.endpoints ?? host.actions ?? host.default ?? Object.create(null);
      const implementation = table[String(key)];
      if (typeof implementation !== "function") {
        throw new Error(`SCENARIO_MODEL_HOST_MISSING: ${String(key)} declares model givens but the project host implements no ${String(key)}`);
      }
      return implementation(...args);
    }
"#
    } else {
        ""
    };
    write_file(
        &server_dir.join("host.js"),
        &format!(
            r#"const unavailable = (key) => {{
  throw new Error(`SCENARIO_ENDPOINT_BOUNDARY_UNSTUBBED: bodyless endpoint ${{key}} has no exact typed scenario given`);
}};
export const actions = new Proxy(Object.create(null), {{
  has() {{ return true; }},
  getOwnPropertyDescriptor() {{ return {{ configurable: true, enumerable: true }}; }},
  get(_target, key) {{
    return async (...args) => {{
{delegation}      const stubs = globalThis.__NOXID_ENDPOINT_SCENARIO_STUBS__;
      return stubs?.has(String(key)) ? structuredClone(stubs.get(String(key))) : unavailable(String(key));
    }};
  }}
}});
// Deny by default, exactly as before, with two declared exceptions. An agent
// scenario is the first: while one is running, the capabilities it declared
// deferred answer `"defer"` once and every other capability answers `true`,
// which is how `given: authorizer defers <capability>` produces a real
// `PermissionRequired` pause through the ordinary authorizer path.
//
// Otherwise capability authorization is the host's decision, and `authorize`
// is a host export, so it is stubbed with the rest of the host. A scenario
// that declares this endpoint's boundary given has stubbed the whole host, its
// authorizer included, and gets the capabilities the declaration names; so has
// a WO-30 scenario whose model givens delegate this key to the project host. A
// scenario that declares no boundary for the endpoint has no host at all, so
// its authority is undeclared and still fails closed with
// ENDPOINT_CAPABILITY_DENIED.
export async function authorize(request) {{
  const decide = globalThis.__NOXID_MODEL_SCENARIO__?.authorizeAgentCapability;
  // The agent authorizer answers `true` or `"defer"` only while an agent
  // scenario is running; `false` is exactly "no agent scenario is active", so
  // it is the fall-through into the endpoint-scenario stub check rather than a
  // denial. Endpoint scenarios and agent scenarios never both own a run.
  const agentDecision =
    typeof decide === "function" ? decide(request?.capability) : false;
  if (agentDecision === true || agentDecision === "defer") return agentDecision;
  const key = String(request?.semanticId);
  return (
    globalThis.__NOXID_ENDPOINT_SCENARIO_STUBS__?.has(key) === true ||
    globalThis.__NOXID_MODEL_SCENARIO__?.hostDelegation?.has(key) === true
  );
}}
export default actions;
"#
        ),
    )?;
    write_file(
        &server_dir.join("middleware.js"),
        r#"const allow = async () => ({ allow: true });
export const middleware = new Proxy(Object.create(null), { get() { return allow; } });
export const globalMiddlewareHandlers = Object.freeze({});
export const globalMiddleware = Object.freeze([]);
"#,
    )?;
    install_scenario_io_boundary(&server_dir)
}

/// The delegated host runs real project code, so every persistent boundary it
/// could still reach has to be closed here or the scenario's "no I/O"
/// determinism is a claim rather than a fact.
///
/// `storage(...)` keeps working, because a host that cannot store anything is
/// not the host the project ships; it is redirected to an in-memory store
/// created for the scenario run and dropped with the process, so nothing
/// survives to the next scenario or to the developer's disk. Queue enqueue and
/// the database adapter have no such ephemeral equivalent — a fake queue or a
/// fake table would answer questions the real one would answer differently —
/// so they refuse with `MODEL_SCENARIO_IO_FORBIDDEN` naming the call. Live
/// `fetch` stays banned by the harness itself.
fn install_scenario_io_boundary(server_dir: &Path) -> Result<(), String> {
    let bridge = server_dir.join("noxid-server.js");
    if bridge.is_file() {
        let source = fs::read_to_string(&bridge)
            .map_err(|error| format!("cannot read the emitted server bridge: {error}"))?;
        write_file(&bridge, &scenario_server_bridge(&source)?)?;
    }
    // The database adapter is compiler-owned and identified the same way the
    // build identifies it: it is the module that installs the runtime principal
    // authority. Replacing it keeps the real driver out of the process
    // entirely, so a scenario cannot open a connection by accident.
    for module in server_modules_under(server_dir)? {
        let source = fs::read_to_string(&module)
            .map_err(|error| format!("cannot read {}: {error}", module.display()))?;
        if !source.contains("__installNoxidPrincipalAuthority") {
            continue;
        }
        write_file(&module, &scenario_database_refusal(&source))?;
    }
    Ok(())
}

fn server_modules_under(directory: &Path) -> Result<Vec<PathBuf>, String> {
    let mut modules = Vec::new();
    let mut pending = vec![directory.join("modules")];
    while let Some(current) = pending.pop() {
        let Ok(entries) = fs::read_dir(&current) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                pending.push(path);
            } else if path.extension().and_then(|value| value.to_str()) == Some("js") {
                modules.push(path);
            }
        }
    }
    modules.sort();
    Ok(modules)
}

/// Rewrite the emitted `noxid:server` bridge so its storage is ephemeral and
/// its queue enqueue refuses. The two markers are compiler-generated text, so a
/// missing one means the generator changed shape and this transform would
/// silently leave a live boundary open — fail closed instead.
fn scenario_server_bridge(source: &str) -> Result<String, String> {
    const STORAGE: &str = "export function storage(namespace) {";
    const ENQUEUE: &str = "export async function enqueue(queue, payload, options) {";
    let mut rewritten = source.to_string();
    if rewritten.contains(STORAGE) {
        rewritten = rewritten.replace(STORAGE, "function __noxidPersistentStorage(namespace) {");
    } else {
        return Err(
            "error[SCENARIO_IO_BOUNDARY_UNRECOGNIZED]: the emitted `noxid:server` bridge no longer declares `storage`, so scenario runs cannot prove they reach no persistent store".into(),
        );
    }
    if rewritten.contains(ENQUEUE) {
        rewritten = rewritten.replace(
            ENQUEUE,
            "async function __noxidPersistentEnqueue(queue, payload, options) {",
        );
    } else {
        return Err(
            "error[SCENARIO_IO_BOUNDARY_UNRECOGNIZED]: the emitted `noxid:server` bridge no longer declares `enqueue`, so scenario runs cannot prove they reach no durable queue".into(),
        );
    }
    rewritten.push_str(SCENARIO_IO_BRIDGE);
    Ok(rewritten)
}

const SCENARIO_IO_BRIDGE: &str = r#"
// WO-30 scenario I/O boundary. `noxid test` replaces the persistent storage
// and queue surfaces with these, so a delegated host reaches no boundary that
// outlives the run. The persistent implementations above are kept only so the
// emitted module still parses as the compiler wrote it.
void __noxidPersistentStorage;
void __noxidPersistentEnqueue;
// The store is looked up per call, never captured, so the harness can drop it
// between scenarios: one scenario's writes must not be another's fixture, the
// same way a component scenario always remounts.
function __noxidScenarioStore() {
  let store = globalThis.__NOXID_SCENARIO_STORAGE__;
  if (store === undefined || store === null) {
    store = new Map();
    globalThis.__NOXID_SCENARIO_STORAGE__ = store;
  }
  return store;
}
function __noxidScenarioIoForbidden(call, instead) {
  return Object.assign(
    new Error(`MODEL_SCENARIO_IO_FORBIDDEN: a scenario called \`${call}\`, which reaches a boundary that outlives the run; ${instead}`),
    { code: "MODEL_SCENARIO_IO_FORBIDDEN", call },
  );
}
export function storage(namespace) {
  __assertName(namespace, "namespace");
  const bucket = () => {
    const store = __noxidScenarioStore();
    let records = store.get(namespace);
    if (!records) {
      records = new Map();
      store.set(namespace, records);
    }
    return records;
  };
  const read = (records, key) => {
    const record = records.get(key);
    if (!record) return null;
    if (record.expiresAt !== null && record.expiresAt <= Date.now()) {
      records.delete(key);
      return null;
    }
    return __cloneJson(record.value);
  };
  return Object.freeze({
    async get(key) {
      __assertName(key, "key");
      return read(bucket(), key);
    },
    async set(key, value, options) {
      __assertName(key, "key");
      bucket().set(key, { value: __cloneJson(value), expiresAt: __expiresAt(options) });
    },
    async compareAndSet(key, expected, value, options) {
      __assertName(key, "key");
      __assertExpected(expected);
      const copied = __cloneJson(value);
      const expiresAt = __expiresAt(options);
      const records = bucket();
      // No `await` between the read and the write, exactly as the ephemeral
      // driver this stands in for.
      if (!__expectedMatch(read(records, key), expected)) return false;
      records.set(key, { value: copied, expiresAt });
      return true;
    },
    async delete(key) {
      __assertName(key, "key");
      return bucket().delete(key);
    },
    async list(prefix = "") {
      __assertName(prefix, "list prefix", true);
      const records = bucket();
      const keys = [];
      for (const [key, record] of records) {
        if (record.expiresAt !== null && record.expiresAt <= Date.now()) {
          records.delete(key);
        } else if (key.startsWith(prefix)) {
          keys.push(key);
        }
      }
      return Object.freeze(keys.sort());
    },
  });
}
export async function enqueue(queue, payload, options) {
  void payload;
  void options;
  throw __noxidScenarioIoForbidden(
    `enqueue(${typeof queue === "string" ? JSON.stringify(queue) : String(queue)})`,
    "a scenario cannot hand work to a durable queue, because the work would outlive it; assert the handler through that queue's own scenario instead",
  );
}
"#;

/// Replace the compiler-owned database adapter with one that refuses. Every
/// name the real module exports is re-exported as a refusal, so a host that
/// imports the adapter still links and fails with a structured code at the
/// call rather than with a module-resolution error.
fn scenario_database_refusal(source: &str) -> String {
    let mut names = BTreeSet::new();
    for line in source.lines() {
        let rest = match line.trim_start().strip_prefix("export ") {
            Some(rest) => rest,
            None => continue,
        };
        let rest = rest.strip_prefix("async ").unwrap_or(rest);
        let Some(rest) = ["function ", "class ", "const ", "let ", "var "]
            .iter()
            .find_map(|keyword| rest.strip_prefix(keyword))
        else {
            continue;
        };
        let name = rest
            .trim_start()
            .split(|character: char| !character.is_alphanumeric() && character != '_')
            .find(|segment| !segment.is_empty())
            .unwrap_or_default();
        if !name.is_empty() {
            names.insert(name.to_string());
        }
    }
    let mut output = String::from(
        r#"// WO-30 scenario I/O boundary. `noxid test` replaces the compiler-owned
// database adapter with this module, so the real driver is never imported and
// a scenario cannot open a connection. Every export the adapter declares is
// present, and every one of them refuses.
function __noxidScenarioDatabaseRefusal(call) {
  const refuse = (...args) => {
    void args;
    throw Object.assign(
      new Error(`MODEL_SCENARIO_IO_FORBIDDEN: a scenario called \`${call}\` on the database adapter, which reaches a boundary that outlives the run; give the endpoint that owns this data an exact typed scenario given instead`),
      { code: "MODEL_SCENARIO_IO_FORBIDDEN", call },
    );
  };
  return refuse;
}
"#,
    );
    for name in &names {
        // The generated handler installs the principal authority at module
        // load, before any scenario runs, so that one export is a no-op rather
        // than a refusal: refusing it would fail the whole harness at import
        // instead of failing the call that actually reached for data.
        if name == "__installNoxidPrincipalAuthority" {
            output
                .push_str("export function __installNoxidPrincipalAuthority() { return null; }\n");
            continue;
        }
        output.push_str(&format!(
            "export const {name} = __noxidScenarioDatabaseRefusal(\"{name}\");\n"
        ));
    }
    output.push_str("export default __noxidScenarioDatabaseRefusal(\"default\");\n");
    output
}

#[allow(clippy::too_many_arguments)]
fn generate_harness(
    components: &BTreeMap<SemanticId, TestComponent>,
    endpoints: &BTreeMap<SemanticId, TestEndpoint>,
    agents: &BTreeMap<SemanticId, TestAgent>,
    tasks: &BTreeMap<SemanticId, TestTask>,
    queues: &BTreeMap<SemanticId, TestQueue>,
    endpoint_handler_module: Option<&str>,
    property_execution: &PropertyExecution,
    options: &Options,
) -> Result<String, String> {
    let mut javascript = String::new();
    javascript.push_str(noxid_runtime::NODE_TEST_DOM);
    javascript.push_str(
        r#"
const runtime = await import("./noxid-runtime.js");
const registrations = new Map();
globalThis.__NOXID_HMR__ = {
  initialState(_semanticId, initial) { return initial; },
  registerInstance(instance) { registrations.set(instance.component, instance); },
};
// The `noxid test` output contract: stdout carries exactly one line, the JSON
// report. Everything the code under test logs goes to stderr — including every
// trace record the emitted server writes at any `[server] tracing` level, which
// stays NDJSON, one record per line. Without this split a project with
// `tracing = "full"` interleaves trace records with the report and nothing can
// parse stdout as JSON. The report is written through the captured writer so
// the redirect cannot swallow it.
const __noxidWriteReport = (line) => process.stdout.write(line + "\n");
console.log = (...args) => { console.error(...args); };
const scenarioResults = [];
const proseOnlyScenarios = [];
const requirementEntries = [];
globalThis.__NOXID_ENDPOINT_SCENARIO_STUBS__ = new Map();
globalThis.fetch = async () => { throw new Error("SCENARIO_LIVE_IO_FORBIDDEN: endpoint scenarios cannot perform live fetch I/O; add an exact typed given for the boundary"); };
// The WO-30 no-I/O model controller. It is installed for the whole harness,
// not per scenario, so a model call from any scenario is served from a
// declared stub or fails closed with the stubbing syntax — it can never
// reach a provider.
const modelScenarioStubs = new Map();
const modelScenarioDelegation = new Set();
// The compiler-owned semantic id of the declaration whose scenario is running.
// It is what makes a MODEL_STUB_REQUIRED refusal say *which* call had no stub
// left, in the runtime error and in the structured scenario report alike.
let modelScenarioCallSite = "";
const modelScenarioRefusals = [];
// A refusal is a run log, so it is written where the run's logs go: one NDJSON
// record on stderr, beside the emitted server's trace stream. The report says
// *that* a stub was missing; this says which call asked for it, at the moment
// it asked, and it is the only external evidence that a scripted run failed
// closed instead of reaching a provider.
function recordModelStubRefusal(model) {
  modelScenarioRefusals.push({ model, callSite: modelScenarioCallSite });
  console.error(JSON.stringify({
    schema: "noxid.scenario.refusal.v1",
    code: "MODEL_STUB_REQUIRED",
    model,
    callSite: modelScenarioCallSite,
  }));
}
// The WO-31 agent side of the same controller. An agent turn is scripted per
// agent rather than per model because the engine calls the provider itself,
// with the registry's tool schemas attached; one scripted entry is one whole
// provider turn, assembled from a run of `text` entries and at most one
// `tool`/`final` entry — exactly the shape a real turn has.
const agentScenarioState = {
  active: false, agent: "", script: [], cursor: 0, turn: 0,
  deferred: new Set(), deferredSeen: new Set(), toolCalls: [],
};
globalThis.__NOXID_MODEL_SCENARIO__ = {
  hostDelegation: modelScenarioDelegation,
  callSite: modelScenarioCallSite,
  take(model) {
    const queue = modelScenarioStubs.get(model);
    if (queue === undefined || queue.length === 0) {
      recordModelStubRefusal(model);
      return null;
    }
    return queue.shift();
  },
  takeAgentTurn(agent) {
    if (!agentScenarioState.active || agentScenarioState.agent !== agent) {
      recordModelStubRefusal(`agent:${agent}`);
      return null;
    }
    if (agentScenarioState.cursor >= agentScenarioState.script.length) {
      recordModelStubRefusal(`agent:${agent}`);
      return null;
    }
    const text = [];
    let call = null;
    while (agentScenarioState.cursor < agentScenarioState.script.length) {
      const entry = agentScenarioState.script[agentScenarioState.cursor];
      agentScenarioState.cursor += 1;
      if (entry.kind === "text") { text.push(entry.text); continue; }
      call = entry;
      break;
    }
    const index = agentScenarioState.turn;
    agentScenarioState.turn += 1;
    return { index, text, call, inputTokens: 0, outputTokens: 0 };
  },
  // Three-valued, like the host authorizer it stands in for. A capability the
  // scenario declared deferred defers the *first* time the run asks for it and
  // is allowed afterwards, which is the human-in-the-loop shape: the pause
  // asks a person, and the resume re-asks with that person's answer.
  authorizeAgentCapability(capability) {
    if (!agentScenarioState.active) return false;
    if (agentScenarioState.deferred.has(capability) && !agentScenarioState.deferredSeen.has(capability)) {
      agentScenarioState.deferredSeen.add(capability);
      return "defer";
    }
    return true;
  },
  recordAgentToolCall(record) {
    if (agentScenarioState.active) agentScenarioState.toolCalls.push(record);
  },
};
function installAgentScenario(agent, script, deferred) {
  agentScenarioState.active = true;
  agentScenarioState.agent = agent;
  agentScenarioState.script = script;
  agentScenarioState.cursor = 0;
  agentScenarioState.turn = 0;
  agentScenarioState.deferred = new Set(deferred);
  agentScenarioState.deferredSeen = new Set();
  agentScenarioState.toolCalls = [];
}
function clearAgentScenario() { agentScenarioState.active = false; }
function agentScenarioToolCalls() { return agentScenarioState.toolCalls; }
// How many provider turns the run actually consumed from the script.
function agentScenarioTurnCount() { return agentScenarioState.turn; }
// One SSE body, decoded into the `{ tag, value }` events the engine emitted.
// A `noxid-error` frame is the run's terminal refusal.
async function readAgentEvents(response, sink) {
  const text = await response.text();
  for (const frame of text.split("\n\n")) {
    if (frame.trim().length === 0) continue;
    let name = "message";
    const data = [];
    for (const line of frame.split("\n")) {
      if (line.startsWith("event: ")) name = line.slice(7);
      else if (line.startsWith("data: ")) data.push(line.slice(6));
    }
    if (data.length === 0) continue;
    let payload = null;
    try { payload = JSON.parse(data.join("\n")); } catch { continue; }
    if (name === "noxid-error") { sink.refusal = payload?.code ?? payload?.error?.code ?? "STREAM_ERROR"; continue; }
    if (payload === null || typeof payload !== "object" || typeof payload.tag !== "string") continue;
    sink.events.push(payload.tag);
    if (payload.tag === "Completed") sink.output = payload.value ?? null;
    if (payload.tag === "Failed") sink.refusal = payload.value?.code ?? "AGENT_RUN_FAILED";
    if (payload.tag === "Paused") { sink.paused = true; sink.runId = payload.value ?? null; }
  }
}
function agentValuesEqual(left, right) { return endpointValuesEqual(left, right); }
function installModelStubs(stubs, delegated, callSite = "") {
  modelScenarioStubs.clear();
  modelScenarioDelegation.clear();
  modelScenarioRefusals.length = 0;
  // The scenario storage bridge keeps its records here; dropping them is what
  // makes the ephemeral store per-scenario rather than per-process.
  globalThis.__NOXID_SCENARIO_STORAGE__?.clear();
  modelScenarioCallSite = callSite;
  globalThis.__NOXID_MODEL_SCENARIO__.callSite = callSite;
  clearAgentScenario();
  for (const stub of stubs) {
    const queue = modelScenarioStubs.get(stub.model) ?? [];
    queue.push(stub);
    modelScenarioStubs.set(stub.model, queue);
  }
  for (const key of delegated) modelScenarioDelegation.add(key);
}
function modelStubRefusals() {
  return modelScenarioRefusals.map((refusal) => ({ model: refusal.model, callSite: refusal.callSite }));
}
function actualValues(scope, references) {
  const values = {};
  for (const [semanticId, name] of references) {
    try {
      const value = scope[name]?.get?.();
      values[semanticId] = semanticId.startsWith("stream-use:")
        ? value?.map?.(($noxEnvelope) => $noxEnvelope.event)
        : value;
    }
    catch (error) { values[semanticId] = { unreadable: error?.message ?? String(error) }; }
  }
  return values;
}
function failureMessage(error) { return error?.message ?? String(error); }
function endpointQueryValue(value) {
  return typeof value === "object" ? JSON.stringify(value) : String(value);
}
function endpointValuesEqual(left, right) {
  if (Object.is(left, right)) return true;
  if (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => endpointValuesEqual(value, right[index]));
  if (left && right && typeof left === "object" && typeof right === "object") {
    const leftKeys = Object.keys(left).sort();
    const rightKeys = Object.keys(right).sort();
    return leftKeys.length === rightKeys.length && leftKeys.every((key, index) => key === rightKeys[index] && endpointValuesEqual(left[key], right[key]));
  }
  return false;
}
"#,
    );
    javascript.push_str(&property_execution.javascript);

    for (index, test_component) in components.values().enumerate() {
        let component = &test_component.definition;
        let module_var = format!("componentModule{index}");
        javascript.push_str(&format!(
            "const {module_var} = await import(\"./{}.js\");\n",
            json_escape(&component.name)
        ));
        for requirement in &component.requirements {
            javascript.push_str(&format!(
                "requirementEntries.push([\"{}\", \"{}\"]);\n",
                json_escape(&component.name),
                json_escape(requirement.id.as_str())
            ));
        }
        for scenario in &component.scenarios {
            let has_typed_steps = !scenario.typed_given.is_empty()
                || !scenario.typed_when.is_empty()
                || !scenario.typed_expect.is_empty();
            let has_prose = !scenario.given.is_empty()
                || !scenario.when.is_empty()
                || !scenario.expect.is_empty();
            if !has_typed_steps {
                let reason = if has_prose {
                    "prose steps are not executable"
                } else {
                    "scenario has no executable typed steps"
                };
                javascript.push_str(&format!(
                    "proseOnlyScenarios.push(\"{}\");\nscenarioResults.push({{ id: \"{}\", name: \"{}\", component: \"{}\", status: \"unsupported\", assertions: [], failure: \"{reason}\", covers: {} }});\n",
                    json_escape(scenario.id.as_str()),
                    json_escape(scenario.id.as_str()),
                    json_escape(&scenario.name),
                    json_escape(&component.name),
                    ids_as_javascript(&scenario.covers),
                ));
                continue;
            }
            javascript.push_str(&scenario_script(
                &module_var,
                component,
                scenario,
                &test_component.source,
            )?);
        }
    }

    if let Some(endpoint_handler_module) = endpoint_handler_module {
        javascript.push_str(&format!(
            "const endpointModule = await import(\"{}\");\n",
            json_escape(endpoint_handler_module)
        ));
        let mut scenario_ordinal = 1usize;
        for test_endpoint in endpoints.values() {
            let endpoint = &test_endpoint.definition;
            for scenario in &endpoint.scenarios {
                javascript.push_str(&endpoint_scenario_script(
                    endpoint,
                    scenario,
                    &test_endpoint.source,
                    scenario_ordinal,
                )?);
                scenario_ordinal += 1;
            }
        }
        for test_agent in agents.values() {
            let agent = &test_agent.definition;
            for scenario in &agent.scenarios {
                javascript.push_str(&agent_scenario_script(
                    agent,
                    scenario,
                    &test_agent.source,
                    scenario_ordinal,
                )?);
                scenario_ordinal += 1;
            }
        }
    }

    for test_task in tasks.values() {
        for scenario in &test_task.definition.scenarios {
            javascript.push_str(&task_scenario_script(
                &test_task.definition,
                scenario,
                &test_task.source,
            )?);
        }
    }

    for test_queue in queues.values() {
        for scenario in &test_queue.definition.scenarios {
            javascript.push_str(&queue_scenario_script(
                &test_queue.definition,
                scenario,
                &test_queue.source,
            )?);
        }
    }

    javascript.push_str(&format!(
        r#"
const passedCoverage = new Set(scenarioResults.filter((scenario) => scenario.status === "pass").flatMap((scenario) => scenario.covers.map((id) => `${{scenario.component}}\u0000${{id}}`)));
const uncoveredRequirementEntries = {} ? requirementEntries.filter(([component, id]) => !passedCoverage.has(`${{component}}\u0000${{id}}`)) : [];
const uncoveredRequirements = uncoveredRequirementEntries.map(([, id]) => id);
const duplicateRequirementIds = new Set(requirementEntries.filter(([, id], index, entries) => entries.findIndex(([, candidate]) => candidate === id) !== index).map(([, id]) => id));
const uncoveredRequirementDeclarations = uncoveredRequirementEntries.filter(([, id]) => duplicateRequirementIds.has(id)).map(([component, id]) => ({{ component, id }}));
const failed = scenarioResults.filter((scenario) => scenario.status === "fail").length;
const passed = scenarioResults.filter((scenario) => scenario.status === "pass").length;
const unsupported = scenarioResults.filter((scenario) => scenario.status === "unsupported").length;
const gateFailed = {} && (uncoveredRequirements.length > 0 || proseOnlyScenarios.length > 0);
const report = {{
  schemaVersion: 1,
  ok: failed === 0 && !gateFailed,
  summary: {{ total: scenarioResults.length, passed, failed, unsupported }},
  scenarios: scenarioResults,
  gate: {{ enabled: {}, uncoveredRequirements, ...(uncoveredRequirementDeclarations.length > 0 ? {{ uncoveredRequirementDeclarations }} : {{}}), proseOnlyScenarios }},
}};
__noxidWriteReport(JSON.stringify(report));
if (!{}) console.error(`noxid test: ${{passed}} passed, ${{failed}} failed, ${{unsupported}} unsupported${{gateFailed ? ", gate failed" : ""}}`);
if (!report.ok) process.exitCode = 1;
"#,
        options.gate, options.gate, options.gate, options.json_only
    ));
    Ok(javascript)
}

fn queue_scenario_script(
    queue: &QueueDefinition,
    scenario: &noxid_ir::QueueScenario,
    source: &SourceFile,
) -> Result<String, String> {
    let payload = scenario
        .payload
        .iter()
        .map(|argument| {
            Ok((
                argument.name.as_str(),
                emit_scenario_expression(&argument.value)?,
            ))
        })
        .collect::<Result<BTreeMap<_, _>, String>>()?;
    let invocation = match &queue.handler {
        QueueHandler::CompilerOwned { statements, .. } => {
            let arguments = queue
                .payload
                .iter()
                .map(|field| {
                    let value = payload
                        .get(field.name.as_str())
                        .cloned()
                        .unwrap_or_else(|| "null".into());
                    format!("\"{}\": structuredClone({value})", json_escape(&field.name))
                })
                .collect::<Vec<_>>()
                .join(", ");
            let statements =
                noxid_codegen_server_js::compiler_statements_javascript(statements, 4)?;
            format!(
                "await (async () => {{\n    const args = Object.freeze({{ {arguments} }});\n    const context = {SCENARIO_SYSTEM_CONTEXT};\n{statements}\n}})()"
            )
        }
        QueueHandler::Host { key } => match scenario
            .typed_given
            .iter()
            .find(|given| &given.target == key)
        {
            Some(given) => format!(
                "structuredClone({})",
                emit_scenario_expression(&given.value)?
            ),
            None => format!(
                "(() => {{ throw new Error(\"SCENARIO_QUEUE_BOUNDARY_UNSTUBBED: bodyless queue {} has no exact typed scenario given\"); }})()",
                json_escape(key.as_str())
            ),
        },
    };
    let mut script = format!(
        "{{\n{}  const $noxQueueTest = {{ failure: null, assertions: [] }};\n  try {{\n    const $noxQueueValue = {invocation};\n    const value = {{ get() {{ return $noxQueueValue; }} }};\n    const refusal = {{ get() {{ return \"\"; }} }};\n    const attempts = {{ get() {{ return 1; }} }};\n    const runAt = {{ get() {{ return new Date(\"{}\"); }} }};\n    const $noxScope = {{ value, refusal, attempts, runAt }};\n",
        model_stub_script(&scenario.model_stubs, &[], queue.id.as_str())?,
        json_escape(&scenario.clock),
    );
    for expectation in &scenario.expectations {
        let mut references = BTreeSet::new();
        collect_references(expectation, &mut references);
        let reference_pairs = reference_pairs_as_javascript(&references);
        let expression_source = source.slice(expectation.span).trim();
        script.push_str(&format!(
            "    {{ const $noxActual = actualValues($noxScope, [{reference_pairs}]); const $noxPassed = !!({}); $noxQueueTest.assertions.push({{ expression: \"{}\", passed: $noxPassed, actual: $noxActual }}); if (!$noxPassed && $noxQueueTest.failure === null) $noxQueueTest.failure = \"expectation failed: {}\"; }}\n",
            emit_scenario_expression(expectation)?,
            json_escape(expression_source),
            json_escape(expression_source),
        ));
    }
    script.push_str(&format!(
        "  }} catch ($noxError) {{ $noxQueueTest.failure = $noxQueueTest.failure ?? failureMessage($noxError); }}\n  scenarioResults.push({{ id: \"{}\", name: \"{}\", queue: \"{}\", semanticUnit: \"{}\", status: $noxQueueTest.failure === null ? \"pass\" : \"fail\", assertions: $noxQueueTest.assertions, failure: $noxQueueTest.failure, modelStubRefusals: modelStubRefusals(), covers: {} }});\n}}\n",
        json_escape(scenario.id.as_str()),
        json_escape(&scenario.name),
        json_escape(&queue.name),
        json_escape(queue.id.as_str()),
        strings_as_javascript(&scenario.covers),
    ));
    Ok(script)
}

fn task_scenario_script(
    task: &TaskDefinition,
    scenario: &noxid_ir::TaskScenario,
    source: &SourceFile,
) -> Result<String, String> {
    if !scenario.given.is_empty() {
        return Ok(format!(
            "proseOnlyScenarios.push(\"{}\");\nscenarioResults.push({{ id: \"{}\", name: \"{}\", task: \"{}\", semanticUnit: \"{}\", status: \"unsupported\", assertions: [], failure: \"prose task givens are not executable; use an exact typed boundary given\", covers: {} }});\n",
            json_escape(scenario.id.as_str()),
            json_escape(scenario.id.as_str()),
            json_escape(&scenario.name),
            json_escape(&task.name),
            json_escape(task.id.as_str()),
            strings_as_javascript(&scenario.covers),
        ));
    }

    let invocation = match &task.handler {
        TaskHandler::CompilerOwned { statements, .. } => {
            let statements =
                noxid_codegen_server_js::compiler_statements_javascript(statements, 4)?;
            format!(
                "await (async () => {{\n    const context = {SCENARIO_SYSTEM_CONTEXT};\n{statements}\n}})()"
            )
        }
        TaskHandler::Host { key } => {
            let stub = scenario
                .typed_given
                .iter()
                .find(|given| &given.target == key)
                .map(|given| emit_scenario_expression(&given.value))
                .transpose()?;
            stub.map_or_else(
                || {
                    format!(
                        "(() => {{ throw new Error(\"SCENARIO_TASK_BOUNDARY_UNSTUBBED: bodyless task {} has no exact typed scenario given\"); }})()",
                        json_escape(key.as_str())
                    )
                },
                |value| format!("structuredClone({value})"),
            )
        }
    };
    let mut script = format!(
        "{{\n{}  const $noxTaskTest = {{ failure: null, assertions: [] }};\n  try {{\n    const $noxTaskValue = {invocation};\n    const value = {{ get() {{ return $noxTaskValue; }} }};\n    const refusal = {{ get() {{ return \"\"; }} }};\n    const $noxScope = {{ value, refusal }};\n",
        model_stub_script(&scenario.model_stubs, &[], task.id.as_str())?,
    );
    for expectation in &scenario.expectations {
        let mut references = BTreeSet::new();
        collect_references(expectation, &mut references);
        let reference_pairs = reference_pairs_as_javascript(&references);
        let expression_source = source.slice(expectation.span).trim();
        script.push_str(&format!(
            "    {{ const $noxActual = actualValues($noxScope, [{reference_pairs}]); const $noxPassed = !!({}); $noxTaskTest.assertions.push({{ expression: \"{}\", passed: $noxPassed, actual: $noxActual }}); if (!$noxPassed && $noxTaskTest.failure === null) $noxTaskTest.failure = \"expectation failed: {}\"; }}\n",
            emit_scenario_expression(expectation)?,
            json_escape(expression_source),
            json_escape(expression_source),
        ));
    }
    script.push_str(&format!(
        "  }} catch ($noxError) {{ $noxTaskTest.failure = $noxTaskTest.failure ?? failureMessage($noxError); }}\n  scenarioResults.push({{ id: \"{}\", name: \"{}\", task: \"{}\", semanticUnit: \"{}\", status: $noxTaskTest.failure === null ? \"pass\" : \"fail\", assertions: $noxTaskTest.assertions, failure: $noxTaskTest.failure, modelStubRefusals: modelStubRefusals(), covers: {} }});\n}}\n",
        json_escape(scenario.id.as_str()),
        json_escape(&scenario.name),
        json_escape(&task.name),
        json_escape(task.id.as_str()),
        strings_as_javascript(&scenario.covers),
    ));
    Ok(script)
}

#[derive(Clone, Debug)]
struct EndpointFileFixture {
    field: String,
    bytes: Vec<u8>,
    mime: String,
}

fn decode_scenario_file_base64(value: &str, field: &str) -> Result<Vec<u8>, String> {
    if !value.len().is_multiple_of(4) {
        return Err(format!(
            "error[SCENARIO_FILE_FIXTURE_INVALID]: file fixture `{field}` bytes must be canonical padded base64"
        ));
    }
    let decode = |byte: u8| -> Option<u8> {
        match byte {
            b'A'..=b'Z' => Some(byte - b'A'),
            b'a'..=b'z' => Some(byte - b'a' + 26),
            b'0'..=b'9' => Some(byte - b'0' + 52),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    };
    let input = value.as_bytes();
    let mut output = Vec::with_capacity(input.len() / 4 * 3);
    for (index, quartet) in input.chunks_exact(4).enumerate() {
        let last = index + 1 == input.len() / 4;
        let padding = if quartet[2] == b'=' {
            2
        } else if quartet[3] == b'=' {
            1
        } else {
            0
        };
        if (!last && padding != 0)
            || (padding == 2 && quartet[3] != b'=')
            || quartet[0] == b'='
            || quartet[1] == b'='
        {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_INVALID]: file fixture `{field}` bytes must be canonical padded base64"
            ));
        }
        let a = decode(quartet[0]);
        let b = decode(quartet[1]);
        let c = (padding < 2).then(|| decode(quartet[2])).flatten();
        let d = (padding == 0).then(|| decode(quartet[3])).flatten();
        let (Some(a), Some(b)) = (a, b) else {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_INVALID]: file fixture `{field}` bytes must be canonical padded base64"
            ));
        };
        if (padding < 2 && c.is_none()) || (padding == 0 && d.is_none()) {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_INVALID]: file fixture `{field}` bytes must be canonical padded base64"
            ));
        }
        if (padding == 2 && b & 0x0f != 0) || (padding == 1 && c.expect("checked") & 0x03 != 0) {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_INVALID]: file fixture `{field}` bytes must use canonical zero padding bits"
            ));
        }
        output.push((a << 2) | (b >> 4));
        if let Some(c) = c {
            output.push((b << 4) | (c >> 2));
            if let Some(d) = d {
                output.push((c << 6) | d);
            }
        }
    }
    Ok(output)
}

fn scenario_fixture_mime(value: &str) -> bool {
    let Some((kind, subtype)) = value.split_once('/') else {
        return false;
    };
    let token = |part: &str| {
        !part.is_empty()
            && part.len() <= 64
            && part.bytes().all(|byte| {
                byte.is_ascii_alphanumeric()
                    || matches!(
                        byte,
                        b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
                    )
            })
    };
    token(kind) && token(subtype)
}

fn endpoint_file_fixtures(
    endpoint: &EndpointDefinition,
    scenario: &noxid_ir::EndpointScenario,
) -> Result<Option<Vec<EndpointFileFixture>>, String> {
    let mut fixtures = Vec::new();
    for given in &scenario.given {
        let Some(rest) = given.strip_prefix("file ") else {
            return Ok(None);
        };
        let words = rest.split_ascii_whitespace().collect::<Vec<_>>();
        if words.len() != 5 || words[1] != "bytes" || words[3] != "as" {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_INVALID]: endpoint scenario `{}` file givens use `file <body-field> bytes <canonical-base64> as <mime>`",
                scenario.name,
            ));
        }
        let field = words[0];
        let Some(contract) = endpoint
            .body
            .iter()
            .find(|candidate| candidate.name == field)
            .and_then(|candidate| candidate.file.as_ref())
        else {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_UNKNOWN_FIELD]: endpoint scenario `{}` gives file `{field}`, but `{field}` is not a declared File body field",
                scenario.name,
            ));
        };
        if !scenario_fixture_mime(words[4]) {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_INVALID]: endpoint scenario `{}` file `{field}` must declare one syntactically valid MIME type after `as`",
                scenario.name,
            ));
        }
        let bytes = decode_scenario_file_base64(words[2], field)?;
        if bytes.len() as u64 > contract.max_size_bytes.saturating_add(1) {
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_TOO_LARGE]: endpoint scenario `{}` file `{field}` has {} bytes; fixtures may reach the declared {} byte cap plus exactly one refusal byte",
                scenario.name,
                bytes.len(),
                contract.max_size_bytes,
            ));
        }
        fixtures.push(EndpointFileFixture {
            field: field.to_string(),
            bytes,
            mime: words[4].to_string(),
        });
    }

    let upload_fields = endpoint
        .body
        .iter()
        .filter_map(|field| field.file.as_ref().map(|contract| (field, contract)))
        .collect::<Vec<_>>();
    if upload_fields.is_empty() {
        return if fixtures.is_empty() {
            Ok(Some(fixtures))
        } else {
            Err(format!(
                "error[SCENARIO_FILE_FIXTURE_UNKNOWN_FIELD]: endpoint scenario `{}` declares a file fixture for an endpoint with no File body field",
                scenario.name,
            ))
        };
    }
    for (field, contract) in upload_fields {
        let count = fixtures
            .iter()
            .filter(|fixture| fixture.field == field.name)
            .count();
        if count == 0 || (!contract.multiple && count > 1) {
            let rule = if contract.multiple {
                "requires at least one fixture"
            } else {
                "requires exactly one fixture"
            };
            return Err(format!(
                "error[SCENARIO_FILE_FIXTURE_CARDINALITY]: endpoint scenario `{}` {rule} for File body field `{}`; found {count}",
                scenario.name, field.name,
            ));
        }
    }
    Ok(Some(fixtures))
}

fn endpoint_scenario_script(
    endpoint: &EndpointDefinition,
    scenario: &noxid_ir::EndpointScenario,
    source: &SourceFile,
    scenario_ordinal: usize,
) -> Result<String, String> {
    let Some(file_fixtures) = endpoint_file_fixtures(endpoint, scenario)? else {
        return Ok(format!(
            "proseOnlyScenarios.push(\"{}\");\nscenarioResults.push({{ id: \"{}\", name: \"{}\", endpoint: \"{}\", semanticUnit: \"{}\", status: \"unsupported\", assertions: [], failure: \"prose endpoint givens are not executable; use an exact typed boundary given\", covers: {} }});\n",
            json_escape(scenario.id.as_str()),
            json_escape(scenario.id.as_str()),
            json_escape(&scenario.name),
            json_escape(&endpoint.name),
            json_escape(endpoint.id.as_str()),
            strings_as_javascript(&scenario.covers),
        ));
    };

    let route = endpoint
        .route
        .as_ref()
        .expect("scenario project endpoints are route-enriched by the canonical project builder");
    let request_group = |name: &str| -> Result<String, String> {
        match scenario
            .request
            .iter()
            .find(|argument| argument.name == name)
        {
            Some(argument) => emit_endpoint_json_expression(&argument.value),
            None => Ok("{}".into()),
        }
    };
    let params = request_group("params")?;
    let query = request_group("query")?;
    let body = request_group("body")?;
    let delegated = if scenario.model_stubs.is_empty()
        && (file_fixtures.is_empty() || !scenario.typed_given.is_empty())
    {
        Vec::new()
    } else {
        vec![endpoint.id.as_str().to_string()]
    };
    let mut script = format!(
        "{{\n  globalThis.__NOXID_ENDPOINT_SCENARIO_STUBS__.clear();\n{}  const $noxEndpointTest = {{ failure: null, assertions: [] }};\n  try {{\n    const $noxParams = {params};\n    const $noxQuery = {query};\n    const $noxBody = {body};\n    let $noxPath = \"{}\";\n",
        model_stub_script(&scenario.model_stubs, &delegated, endpoint.id.as_str())?,
        json_escape(&route.path),
    );
    for parameter in &route.dynamic_params {
        script.push_str(&format!(
            "    $noxPath = $noxPath.replace(\"[{}]\", encodeURIComponent(String($noxParams[\"{}\"])));\n",
            json_escape(parameter),
            json_escape(parameter),
        ));
    }
    script.push_str("    const $noxUrl = new URL(`http://noxid.test${$noxPath}`);\n");
    for field in &endpoint.query {
        let encoded_value = if endpoint_query_is_array(&field.ty) {
            "JSON.stringify($noxRawValue)"
        } else {
            "endpointQueryValue($noxRawValue)"
        };
        let present = if matches!(&field.ty, noxid_types::Type::Optional(_)) {
            "$noxRawValue !== null"
        } else {
            "true"
        };
        script.push_str(&format!(
            "    {{ const $noxRawValue = $noxQuery[\"{}\"]; if ({present}) $noxUrl.searchParams.append(\"{}\", {encoded_value}); }}\n",
            json_escape(&field.name),
            json_escape(&field.name),
        ));
    }
    for given in &scenario.typed_given {
        script.push_str(&format!(
            "    globalThis.__NOXID_ENDPOINT_SCENARIO_STUBS__.set(\"{}\", {});\n",
            json_escape(given.target.as_str()),
            emit_scenario_expression(&given.value)?,
        ));
    }
    script.push_str("    const $noxHeaders = new Headers();\n");
    if !file_fixtures.is_empty() {
        script.push_str("    const $noxMultipart = new FormData();\n");
        for field in endpoint.body.iter().filter(|field| field.file.is_none()) {
            let encode = match &field.ty {
                noxid_types::Type::String
                | noxid_types::Type::Date
                | noxid_types::Type::Int
                | noxid_types::Type::Number
                | noxid_types::Type::Float
                | noxid_types::Type::Boolean => "String($noxRawValue)",
                noxid_types::Type::Optional(inner)
                    if matches!(
                        inner.as_ref(),
                        noxid_types::Type::String
                            | noxid_types::Type::Date
                            | noxid_types::Type::Int
                            | noxid_types::Type::Number
                            | noxid_types::Type::Float
                            | noxid_types::Type::Boolean
                    ) =>
                {
                    "String($noxRawValue)"
                }
                _ => "JSON.stringify($noxRawValue)",
            };
            script.push_str(&format!(
                "    {{ const $noxRawValue = $noxBody[\"{}\"]; if ($noxRawValue !== null && $noxRawValue !== undefined) $noxMultipart.append(\"{}\", {encode}); }}\n",
                json_escape(&field.name),
                json_escape(&field.name),
            ));
        }
        for fixture in &file_fixtures {
            let bytes = fixture
                .bytes
                .iter()
                .map(u8::to_string)
                .collect::<Vec<_>>()
                .join(",");
            script.push_str(&format!(
                "    $noxMultipart.append(\"{}\", new Blob([Uint8Array.from([{bytes}])], {{ type: \"{}\" }}), \"{}\");\n",
                json_escape(&fixture.field),
                json_escape(&fixture.mime),
                json_escape(&fixture.field),
            ));
        }
    } else if !endpoint.body.is_empty() {
        script.push_str("    $noxHeaders.set(\"content-type\", \"application/json\");\n");
    }
    if endpoint.idempotent {
        script.push_str(&format!(
            "    $noxHeaders.set(\"idempotency-key\", \"{}\");\n",
            json_escape(scenario.id.as_str()),
        ));
    }
    let body_option = if !file_fixtures.is_empty() {
        ", body: $noxMultipart"
    } else if endpoint.body.is_empty() {
        ""
    } else {
        ", body: JSON.stringify($noxBody)"
    };
    script.push_str(&format!(
        "    const $noxRequest = new Request($noxUrl, {{ method: \"{}\", headers: $noxHeaders{body_option} }});\n    const $noxEnvironment = Object.freeze({{ sessionId: \"noxid-scenario:{}\", requestIdentity: Object.freeze({{ ip: \"2001:db8::{scenario_ordinal:x}\" }}) }});\n    const $noxResponse = await endpointModule.fetch($noxRequest, $noxEnvironment, {{ waitUntil() {{}} }});\n    const $noxResponseText = await $noxResponse.text();\n    let $noxPayload = null;\n    try {{ $noxPayload = $noxResponseText === \"\" ? null : JSON.parse($noxResponseText); }} catch {{ $noxPayload = {{ raw: $noxResponseText }}; }}\n    const status = {{ get() {{ return $noxResponse.status; }} }};\n    const value = {{ get() {{ return $noxPayload?.value; }} }};\n    const refusal = {{ get() {{ return $noxPayload?.refusal ?? $noxPayload?.error?.code ?? \"\"; }} }};\n    const $noxScope = {{ status, value, refusal }};\n",
        route.method.as_str().to_ascii_uppercase(),
        json_escape(scenario.id.as_str()),
    ));
    for expectation in &scenario.expectations {
        let mut references = BTreeSet::new();
        collect_references(expectation, &mut references);
        let reference_pairs = reference_pairs_as_javascript(&references);
        let expression_source = source.slice(expectation.span).trim();
        script.push_str(&format!(
            "    {{ const $noxActual = actualValues($noxScope, [{reference_pairs}]); const $noxPassed = !!({}); $noxEndpointTest.assertions.push({{ expression: \"{}\", passed: $noxPassed, actual: $noxActual }}); if (!$noxPassed && $noxEndpointTest.failure === null) $noxEndpointTest.failure = \"expectation failed: {}\"; }}\n",
            emit_endpoint_expectation_expression(expectation)?,
            json_escape(expression_source),
            json_escape(expression_source),
        ));
    }
    script.push_str(&format!(
        "  }} catch ($noxError) {{ $noxEndpointTest.failure = $noxEndpointTest.failure ?? failureMessage($noxError); }}\n  scenarioResults.push({{ id: \"{}\", name: \"{}\", endpoint: \"{}\", semanticUnit: \"{}\", status: $noxEndpointTest.failure === null ? \"pass\" : \"fail\", assertions: $noxEndpointTest.assertions, failure: $noxEndpointTest.failure, modelStubRefusals: modelStubRefusals(), covers: {} }});\n}}\n",
        json_escape(scenario.id.as_str()),
        json_escape(&scenario.name),
        json_escape(&endpoint.name),
        json_escape(endpoint.id.as_str()),
        strings_as_javascript(&scenario.covers),
    ));
    Ok(script)
}

/// One agent scenario, as executable JavaScript.
///
/// The scenario drives the real generated door: `POST
/// /_noxid/agents/<Agent>/runs` with the typed input as its body, then reads
/// the SSE session the run streams. Nothing about the loop is simulated — the
/// only things the scenario replaces are the provider turn (scripted) and the
/// host authorizer's answer for a deferred capability. Every tool call
/// therefore crosses the endpoint's own validator, middleware, limits, and
/// audit, exactly as a production run's would.
fn agent_scenario_script(
    agent: &AgentDefinition,
    scenario: &noxid_ir::AgentScenario,
    source: &SourceFile,
    scenario_ordinal: usize,
) -> Result<String, String> {
    let mut script_entries = Vec::new();
    let mut scripted_tools = Vec::new();
    for turn in &scenario.turns {
        match turn {
            AgentScenarioTurn::Text(text) => script_entries.push(format!(
                "{{ kind: \"text\", text: \"{}\" }}",
                json_escape(text)
            )),
            AgentScenarioTurn::Tool {
                endpoint,
                arguments,
            } => {
                let record = agent_scenario_record(arguments)?;
                scripted_tools.push(format!(
                    "{{ tool: \"{}\", arguments: {record} }}",
                    json_escape(endpoint)
                ));
                script_entries.push(format!(
                    "{{ kind: \"tool\", endpoint: \"{}\", arguments: {record} }}",
                    json_escape(endpoint)
                ));
            }
            AgentScenarioTurn::Final { arguments } => script_entries.push(format!(
                "{{ kind: \"final\", arguments: {} }}",
                agent_scenario_record(arguments)?
            )),
        }
    }
    let input = match &scenario.input {
        Some(value) => emit_endpoint_json_expression(value)?,
        None => "null".into(),
    };
    let deferred = strings_as_javascript(&scenario.deferred);
    let mut script = format!(
        "{{\n  globalThis.__NOXID_ENDPOINT_SCENARIO_STUBS__.clear();\n  installModelStubs([], [], \"{}\");\n  installAgentScenario(\"{}\", [{}], {deferred});\n  const $noxAgentTest = {{ failure: null, assertions: [] }};\n  try {{\n    const $noxSink = {{ events: [], output: null, refusal: \"\", paused: false, resumed: false, runId: null }};\n    const $noxEnvironment = Object.freeze({{ sessionId: \"noxid-scenario:{}\", requestIdentity: Object.freeze({{ ip: \"2001:db8::{scenario_ordinal:x}\" }}) }});\n    const $noxHeaders = new Headers({{ \"content-type\": \"application/json\" }});\n    const $noxStart = new Request(\"http://noxid.test/_noxid/agents/{}/runs\", {{ method: \"POST\", headers: $noxHeaders, body: JSON.stringify({{ input: {input} }}) }});\n    await readAgentEvents(await endpointModule.fetch($noxStart, $noxEnvironment, {{ waitUntil() {{}} }}), $noxSink);\n",
        json_escape(scenario.id.as_str()),
        json_escape(&agent.name),
        script_entries.join(", "),
        json_escape(scenario.id.as_str()),
        json_escape(&agent.name),
    );
    if scenario.resume {
        script.push_str(&format!(
            "    if ($noxSink.paused && typeof $noxSink.runId === \"string\") {{\n      $noxSink.resumed = true;\n      const $noxResume = new Request(`http://noxid.test/_noxid/agents/{}/runs/${{encodeURIComponent($noxSink.runId)}}/resume`, {{ method: \"POST\", headers: new Headers({{ \"content-type\": \"application/json\" }}), body: \"{{}}\" }});\n      await readAgentEvents(await endpointModule.fetch($noxResume, $noxEnvironment, {{ waitUntil() {{}} }}), $noxSink);\n    }}\n",
            json_escape(&agent.name),
        ));
    }
    // Every scripted tool call is checked against what the endpoint actually
    // validated. This is not an expectation the author writes: a scenario that
    // scripts a call the endpoint would have rejected, or that reached the
    // endpoint with different arguments, is a failed scenario by construction.
    script.push_str(&format!(
        "    {{\n      const $noxScripted = [{}];\n      const $noxDispatched = agentScenarioToolCalls();\n      for (let $noxIndex = 0; $noxIndex < $noxDispatched.length; $noxIndex += 1) {{\n        const $noxActualCall = $noxDispatched[$noxIndex];\n        const $noxExpectedCall = $noxScripted[$noxIndex] ?? null;\n        const $noxCallOk = $noxExpectedCall !== null\n          && $noxActualCall.tool === $noxExpectedCall.tool\n          && agentValuesEqual($noxActualCall.arguments, $noxExpectedCall.arguments)\n          && $noxActualCall.status < 400;\n        $noxAgentTest.assertions.push({{ expression: `tool ${{$noxActualCall.tool}} validated the scripted request`, passed: $noxCallOk, actual: {{ tool: $noxActualCall.tool, arguments: $noxActualCall.arguments, status: $noxActualCall.status }} }});\n        if (!$noxCallOk && $noxAgentTest.failure === null) $noxAgentTest.failure = `tool ${{$noxActualCall.tool}} did not validate the scripted request (status ${{$noxActualCall.status}})`;\n      }}\n    }}\n",
        scripted_tools.join(", "),
    ));
    script.push_str("    const emitted = { get() { return $noxSink.events; } };\n    const tools = { get() { return agentScenarioToolCalls().map((call) => call.tool); } };\n    const output = { get() { return $noxSink.output; } };\n    const refusal = { get() { return $noxSink.refusal; } };\n    const paused = { get() { return $noxSink.paused; } };\n    const resumed = { get() { return $noxSink.resumed; } };\n    const turns = { get() { return agentScenarioTurnCount(); } };\n    const $noxScope = { emitted, tools, output, refusal, paused, resumed, turns };\n");
    for expectation in &scenario.expectations {
        let mut references = BTreeSet::new();
        collect_references(expectation, &mut references);
        let reference_pairs = reference_pairs_as_javascript(&references);
        let expression_source = source.slice(expectation.span).trim();
        script.push_str(&format!(
            "    {{ const $noxActual = actualValues($noxScope, [{reference_pairs}]); const $noxPassed = !!({}); $noxAgentTest.assertions.push({{ expression: \"{}\", passed: $noxPassed, actual: $noxActual }}); if (!$noxPassed && $noxAgentTest.failure === null) $noxAgentTest.failure = \"expectation failed: {}\"; }}\n",
            emit_endpoint_expectation_expression(expectation)?,
            json_escape(expression_source),
            json_escape(expression_source),
        ));
    }
    script.push_str(&format!(
        "  }} catch ($noxError) {{ $noxAgentTest.failure = $noxAgentTest.failure ?? failureMessage($noxError); }}\n  clearAgentScenario();\n  scenarioResults.push({{ id: \"{}\", name: \"{}\", agent: \"{}\", semanticUnit: \"{}\", status: $noxAgentTest.failure === null ? \"pass\" : \"fail\", assertions: $noxAgentTest.assertions, failure: $noxAgentTest.failure, modelStubRefusals: modelStubRefusals(), covers: {} }});\n}}\n",
        json_escape(scenario.id.as_str()),
        json_escape(&scenario.name),
        json_escape(&agent.name),
        json_escape(agent.id.as_str()),
        strings_as_javascript(&scenario.covers),
    ));
    Ok(script)
}

/// A scripted turn's `{ field = value }` record, as a JSON object literal.
fn agent_scenario_record(arguments: &[noxid_ir::AgentScenarioArgument]) -> Result<String, String> {
    let fields = arguments
        .iter()
        .map(|argument| {
            Ok(format!(
                "\"{}\": {}",
                json_escape(&argument.name),
                emit_endpoint_json_expression(&argument.value)?
            ))
        })
        .collect::<Result<Vec<_>, String>>()?;
    Ok(format!("{{ {} }}", fields.join(", ")))
}

/// Emit the `installModelStubs(...)` call for one scenario.
///
/// `delegated` names the host keys this scenario's model stubs authorize the
/// boundary host stub to run for real. A scenario that declares model givens
/// is declaring that its host implementation is exercised and that the model
/// is its only external boundary; every other boundary stays stubbed and live
/// `fetch` stays banned.
fn model_stub_script(
    stubs: &[noxid_ir::ScenarioModelStub],
    delegated: &[String],
    call_site: &str,
) -> Result<String, String> {
    let entries = stubs
        .iter()
        .map(|stub| {
            let detail = match &stub.kind {
                noxid_ir::ScenarioModelStubKind::Text(text) => {
                    format!("kind: \"text\", text: \"{}\"", json_escape(text))
                }
                noxid_ir::ScenarioModelStubKind::Object { value, .. } => {
                    format!(
                        "kind: \"object\", value: {}",
                        emit_endpoint_json_expression(value)?
                    )
                }
                noxid_ir::ScenarioModelStubKind::Tokens(tokens) => format!(
                    "kind: \"tokens\", tokens: [{}]",
                    tokens
                        .iter()
                        .map(|token| format!("\"{}\"", json_escape(token)))
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
                noxid_ir::ScenarioModelStubKind::Fails(code) => {
                    format!("kind: \"fails\", code: \"{}\"", json_escape(code))
                }
            };
            Ok(format!(
                "{{ model: \"{}\", {detail}, inputTokens: 0, outputTokens: 0 }}",
                json_escape(&stub.model)
            ))
        })
        .collect::<Result<Vec<_>, String>>()?
        .join(", ");
    let delegated = delegated
        .iter()
        .map(|key| format!("\"{}\"", json_escape(key)))
        .collect::<Vec<_>>()
        .join(", ");
    Ok(format!(
        "  installModelStubs([{entries}], [{delegated}], \"{}\");\n",
        json_escape(call_site),
    ))
}

fn emit_endpoint_json_expression(expression: &SemanticExpr) -> Result<String, String> {
    Ok(match &expression.kind {
        SemanticExprKind::Array(values) => format!(
            "[{}]",
            values
                .iter()
                .map(emit_endpoint_json_expression)
                .collect::<Result<Vec<_>, String>>()?
                .join(", ")
        ),
        SemanticExprKind::Struct { fields, .. } => format!(
            "{{ {} }}",
            fields
                .iter()
                .map(|field| {
                    Ok(format!(
                        "\"{}\": {}",
                        json_escape(&field.name),
                        emit_endpoint_json_expression(&field.value)?
                    ))
                })
                .collect::<Result<Vec<_>, String>>()?
                .join(", ")
        ),
        SemanticExprKind::Variant {
            variant, payload, ..
        } if matches!(&expression.ty, noxid_types::Type::Optional(_)) => {
            if variant.as_str().ends_with(".None") {
                "null".into()
            } else if let Some(payload) = payload {
                emit_endpoint_json_expression(payload)?
            } else {
                "null".into()
            }
        }
        _ if matches!(&expression.ty, noxid_types::Type::Optional(_)) => format!(
            "(($noxOptional) => $noxOptional?.tag === \"None\" ? null : $noxOptional?.tag === \"Some\" ? $noxOptional.value : $noxOptional)({})",
            emit_scenario_expression(expression)?
        ),
        _ => emit_scenario_expression(expression)?,
    })
}

fn emit_endpoint_expectation_expression(expression: &SemanticExpr) -> Result<String, String> {
    Ok(match &expression.kind {
        SemanticExprKind::Binary { left, op, right } => {
            let left = emit_endpoint_expectation_expression(left)?;
            let right = emit_endpoint_expectation_expression(right)?;
            match op {
                noxid_ir::SemanticBinaryOp::Equal => {
                    format!("endpointValuesEqual({left}, {right})")
                }
                noxid_ir::SemanticBinaryOp::NotEqual => {
                    format!("(!endpointValuesEqual({left}, {right}))")
                }
                noxid_ir::SemanticBinaryOp::Coalesce => format!("({left} ?? {right})"),
                other => format!("({left} {} {right})", other.as_str()),
            }
        }
        SemanticExprKind::Unary { op, operand } => format!(
            "({}{})",
            op.as_str(),
            emit_endpoint_expectation_expression(operand)?
        ),
        SemanticExprKind::FieldAccess { base, name, .. } => format!(
            "{}[\"{}\"]",
            emit_endpoint_expectation_expression(base)?,
            json_escape(name)
        ),
        SemanticExprKind::Array(_) | SemanticExprKind::Struct { .. } => {
            emit_endpoint_json_expression(expression)?
        }
        SemanticExprKind::Variant { .. }
            if matches!(&expression.ty, noxid_types::Type::Optional(_)) =>
        {
            emit_endpoint_json_expression(expression)?
        }
        _ => emit_scenario_expression(expression)?,
    })
}

fn scenario_script(
    module_var: &str,
    component: &ComponentDefinition,
    scenario: &noxid_ir::ApplicationScenario,
    source: &SourceFile,
) -> Result<String, String> {
    let mut script = String::new();
    let scope_names = component_scope_names(component).join(", ");
    let factory = format!("__noxidCreate{}Actions", component.name);
    let scenario_stubs = scenario
        .typed_given
        .iter()
        .filter_map(|given| match given.kind {
            ScenarioGivenKind::Resource | ScenarioGivenKind::Stream => {
                Some(Ok(format!("\"{}\"", json_escape(given.target.as_str()))))
            }
            ScenarioGivenKind::RemoteAction => {
                Some(emit_scenario_expression(&given.value).map(|result| {
                    format!(
                        "{{ kind: \"remote-action\", id: \"{}\", result: {result} }}",
                        json_escape(given.target.as_str()),
                    )
                }))
            }
            ScenarioGivenKind::State => None,
        })
        .collect::<Result<BTreeSet<_>, String>>()?
        .into_iter()
        .collect::<Vec<_>>()
        .join(", ");
    let declared_capabilities = component
        .capabilities
        .iter()
        .map(|capability| format!("\"{}\"", json_escape(capability.id.as_str())))
        .collect::<Vec<_>>()
        .join(", ");
    let scenario_props = component
        .props
        .iter()
        .filter(|prop| matches!(prop.ty, noxid_types::Type::Optional(_)))
        .map(|prop| format!("\"{}\": null", json_escape(&prop.name)))
        .collect::<Vec<_>>()
        .join(", ");
    script.push_str(&format!(
        "{{\n  registrations.delete(\"{}\");\n  const $noxTest = {{ mounted: null, scope: null, expressionScope: null, actions: null, failure: null, assertions: [], invariantFailures: [], actualValues, runtime }};\n  try {{\n    const $noxHost = document.createElement(\"main\");\n    const $noxDeclaredCapabilities = new Set([{declared_capabilities}]);\n    const $noxScenarioOptions = runtime.createScenarioHarnessOptions([{scenario_stubs}]);\n    const $noxRuntimeOptions = {{ ...$noxScenarioOptions, authorizeComponent($noxCapability, $noxSubject) {{ return $noxSubject === \"{}\" && $noxDeclaredCapabilities.has($noxCapability); }} }};\n    $noxTest.mounted = {module_var}[\"mount{}\"]($noxHost, {{ {scenario_props} }}, {{}}, null, $noxRuntimeOptions);\n    $noxTest.runtime.flush();\n    const $noxRegistration = registrations.get(\"{}\");\n    if (!$noxRegistration) throw new Error(\"generated mount did not register its semantic state scope\");\n    $noxRegistration.patchActions({{ [\"{factory}\"](scope) {{ $noxTest.scope = scope; $noxTest.actions = {module_var}[\"{factory}\"](scope); return $noxTest.actions; }} }});\n    if (!$noxTest.scope || !$noxTest.actions) throw new Error(\"generated action scope was not captured\");\n    $noxTest.expressionScope = {{ ...$noxTest.scope }};\n{}    {{\n      const {{ {scope_names} }} = $noxTest.expressionScope;\n",
        json_escape(&component.name),
        json_escape(component.id.as_str()),
        json_escape(&component.name),
        json_escape(&component.name),
        "",
    ));
    emit_invariant_checker(&mut script, component, source)?;
    emit_invariant_checkpoint(
        &mut script,
        ScenarioCheckpoint {
            phase: "mount",
            index: 0,
            target: None,
        },
    );
    for (index, given) in scenario.typed_given.iter().enumerate() {
        emit_given_step(&mut script, given)?;
        emit_invariant_checkpoint(
            &mut script,
            ScenarioCheckpoint {
                phase: "given",
                index,
                target: Some(&given.target_name),
            },
        );
    }
    for (index, when) in scenario.typed_when.iter().enumerate() {
        let arguments = when
            .arguments
            .iter()
            .map(emit_scenario_expression)
            .collect::<Result<Vec<_>, String>>()?
            .join(", ");
        script.push_str(&format!(
            "      await $noxTest.actions[\"{}\"]({arguments});\n      $noxTest.runtime.flush();\n",
            json_escape(&when.action_name)
        ));
        emit_invariant_checkpoint(
            &mut script,
            ScenarioCheckpoint {
                phase: "when",
                index,
                target: Some(&when.action_name),
            },
        );
    }
    for expression in &scenario.typed_expect {
        let mut references = BTreeSet::new();
        collect_references(expression, &mut references);
        let reference_pairs = references
            .iter()
            .map(|id| {
                format!(
                    "[\"{}\", \"{}\"]",
                    json_escape(id.as_str()),
                    json_escape(symbol_name(id))
                )
            })
            .collect::<Vec<_>>()
            .join(", ");
        let expression_source = source.slice(expression.span).trim();
        script.push_str(&format!(
            "      {{ const $noxPassed = !!({}); const $noxAssertion = {{ expression: \"{}\", expected: \"Boolean expression evaluates to true\", passed: $noxPassed, actual: $noxTest.actualValues($noxTest.expressionScope, [{reference_pairs}]) }}; $noxTest.assertions.push($noxAssertion); if (!$noxPassed && $noxTest.failure === null) $noxTest.failure = `assertion failed: ${{$noxAssertion.expression}}`; }}\n",
            emit_scenario_expression(expression)?,
            json_escape(expression_source),
        ));
    }
    script.push_str(&format!(
        "    }}\n  }} catch ($noxError) {{ $noxTest.failure = $noxTest.failure ?? failureMessage($noxError); }} finally {{ try {{ $noxTest.mounted?.dispose(); }} catch ($noxError) {{ $noxTest.failure = $noxTest.failure ?? failureMessage($noxError); }} }}\n  scenarioResults.push({{ id: \"{}\", name: \"{}\", component: \"{}\", status: $noxTest.failure === null ? \"pass\" : \"fail\", assertions: $noxTest.assertions, invariantFailures: $noxTest.invariantFailures, failure: $noxTest.failure, covers: {} }});\n}}\n",
        json_escape(scenario.id.as_str()),
        json_escape(&scenario.name),
        json_escape(&component.name),
        ids_as_javascript(&scenario.covers),
    ));
    Ok(script)
}

fn emit_given_step(script: &mut String, given: &noxid_ir::ScenarioGivenStep) -> Result<(), String> {
    let target_name = json_escape(&given.target_name);
    let value = emit_scenario_expression(&given.value)?;
    let statement = match given.kind {
        ScenarioGivenKind::State => format!("$noxTest.scope[\"{target_name}\"].set({value});"),
        ScenarioGivenKind::Resource => {
            let age = given
                .age_milliseconds
                .map(|milliseconds| milliseconds.to_string())
                .unwrap_or_else(|| "null".into());
            format!("$noxTest.mounted.resources[\"{target_name}\"].seedScenario({value}, {age});")
        }
        ScenarioGivenKind::Stream => {
            format!(
                "$noxTest.mounted.streams[\"{target_name}\"].events.set(({value}).map(($noxEvent, $noxIndex) => ({{ sequence: $noxIndex + 1, event: $noxEvent }})));"
            )
        }
        ScenarioGivenKind::RemoteAction => {
            "/* remote-action given installed before mount by the scenario harness */".into()
        }
    };
    script.push_str(&format!(
        "      {statement}\n      $noxTest.runtime.flush();\n"
    ));
    Ok(())
}

fn emit_invariant_checker(
    script: &mut String,
    component: &ComponentDefinition,
    source: &SourceFile,
) -> Result<(), String> {
    script.push_str(
        "      const $noxCheckInvariants = ($noxStep) => {\n        const $noxFailureStart = $noxTest.invariantFailures.length;\n        let $noxCheckpointFailed = false;\n",
    );
    for invariant in &component.invariants {
        let Some(expression) = invariant.typed_assert.as_ref() else {
            continue;
        };
        let mut references = BTreeSet::new();
        collect_references(expression, &mut references);
        let reference_pairs = reference_pairs_as_javascript(&references);
        let expression_source = source.slice(expression.span).trim();
        script.push_str(&format!(
            "        {{ const $noxActual = $noxTest.actualValues($noxTest.expressionScope, [{reference_pairs}]); const $noxPassed = !!({}); if (!$noxPassed) {{ $noxCheckpointFailed = true; $noxTest.invariantFailures.push({{ id: \"{}\", name: \"{}\", expression: \"{}\", step: $noxStep, actual: $noxActual }}); }} }}\n",
            emit_scenario_expression(expression)?,
            json_escape(invariant.id.as_str()),
            json_escape(&invariant.name),
            json_escape(expression_source),
        ));
    }
    script.push_str(
        "        if ($noxCheckpointFailed) { const $noxBreach = $noxTest.invariantFailures[$noxFailureStart]; $noxTest.failure = `invariant failed: ${$noxBreach.name} after ${$noxStep.phase}${$noxStep.target === null ? \"\" : ` ${$noxStep.target}`}`; throw new Error($noxTest.failure); }\n      };\n",
    );
    Ok(())
}

fn emit_invariant_checkpoint(script: &mut String, checkpoint: ScenarioCheckpoint<'_>) {
    script.push_str(&format!(
        "      $noxCheckInvariants({});\n",
        checkpoint.as_javascript()
    ));
}

fn reference_pairs_as_javascript(references: &BTreeSet<SemanticId>) -> String {
    references
        .iter()
        .map(|id| {
            format!(
                "[\"{}\", \"{}\"]",
                json_escape(id.as_str()),
                json_escape(symbol_name(id))
            )
        })
        .collect::<Vec<_>>()
        .join(", ")
}

fn component_scope_names(component: &ComponentDefinition) -> Vec<String> {
    let mut names = BTreeSet::new();
    names.extend(component.props.iter().map(|value| value.name.clone()));
    names.extend(
        component
            .context_uses
            .iter()
            .flat_map(|context| context.fields.iter().map(|field| field.name.clone())),
    );
    names.extend(component.states.iter().map(|value| value.name.clone()));
    names.extend(component.computed.iter().map(|value| value.name.clone()));
    names.extend(component.resources.iter().map(|value| value.name.clone()));
    names.extend(component.streams.iter().map(|value| value.name.clone()));
    names.extend(component.agents.iter().map(|value| value.name.clone()));
    names.into_iter().collect()
}

fn collect_references(expression: &SemanticExpr, references: &mut BTreeSet<SemanticId>) {
    match &expression.kind {
        SemanticExprKind::Int(_)
        | SemanticExprKind::Float(_)
        | SemanticExprKind::String(_)
        | SemanticExprKind::Boolean(_) => {}
        SemanticExprKind::Array(values) => {
            for value in values {
                collect_references(value, references);
            }
        }
        SemanticExprKind::Struct { fields, .. } => {
            for field in fields {
                collect_references(&field.value, references);
            }
        }
        SemanticExprKind::FieldAccess { base, .. }
        | SemanticExprKind::Unary { operand: base, .. } => collect_references(base, references),
        SemanticExprKind::CollectionQuery { base, value, .. } => {
            collect_references(base, references);
            if let Some(value) = value {
                collect_references(value, references);
            }
        }
        SemanticExprKind::Call { arguments, .. }
        | SemanticExprKind::FunctionCall { arguments, .. } => {
            for argument in arguments {
                collect_references(argument, references);
            }
        }
        SemanticExprKind::Reference(id) => {
            references.insert(id.clone());
        }
        SemanticExprKind::Variant { payload, .. } => {
            if let Some(payload) = payload {
                collect_references(payload, references);
            }
        }
        SemanticExprKind::Binary { left, right, .. } => {
            collect_references(left, references);
            collect_references(right, references);
        }
        SemanticExprKind::StringTemplate(parts) => {
            for part in parts {
                if let SemanticTemplatePart::Expression(expression) = part {
                    collect_references(expression, references);
                }
            }
        }
    }
}

fn ids_as_javascript(ids: &[SemanticId]) -> String {
    format!(
        "[{}]",
        ids.iter()
            .map(|id| format!("\"{}\"", json_escape(id.as_str())))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn strings_as_javascript(values: &[String]) -> String {
    format!(
        "[{}]",
        values
            .iter()
            .map(|value| format!("\"{}\"", json_escape(value)))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn endpoint_query_is_array(ty: &noxid_types::Type) -> bool {
    match ty {
        noxid_types::Type::Array(_) => true,
        noxid_types::Type::Optional(inner) => endpoint_query_is_array(inner),
        _ => false,
    }
}

fn symbol_name(id: &SemanticId) -> &str {
    id.as_str().rsplit('.').next().unwrap_or(id.as_str())
}

fn write_file(path: &Path, contents: &str) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
    }
    fs::write(path, contents).map_err(|error| format!("cannot write {}: {error}", path.display()))
}

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

    #[test]
    fn upload_fixture_base64_is_canonical_and_exact() {
        assert_eq!(
            decode_scenario_file_base64("iVBORw0KGgo=", "avatar").unwrap(),
            [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
        );
        for invalid in ["abc", "ab=c", "a===", "AB==", "abc_"] {
            let error = decode_scenario_file_base64(invalid, "avatar").unwrap_err();
            assert!(error.contains("SCENARIO_FILE_FIXTURE_INVALID"), "{error}");
        }
    }

    #[test]
    fn node_harness_timeout_kills_a_hung_process_with_a_stable_code() {
        let scratch = scratch_directory().unwrap();
        let harness = scratch.0.join("hang.mjs");
        write_file(&harness, "while (true) {}\n").unwrap();
        let started = std::time::Instant::now();
        let error =
            run_node_with_timeout(&harness, &scratch.0, std::time::Duration::from_millis(50))
                .unwrap_err();

        assert!(error.contains("SCENARIO_TIMEOUT_EXCEEDED"), "{error}");
        assert!(error.contains("50ms"), "{error}");
        assert!(started.elapsed() < std::time::Duration::from_secs(2));
    }

    #[test]
    fn node_harness_timeout_kills_a_grandchild_holding_stdout() {
        let scratch = scratch_directory().unwrap();
        let harness = scratch.0.join("grandchild.mjs");
        write_file(
            &harness,
            r#"import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
spawn(process.execPath, ["-e", "require('node:fs').writeFileSync('grandchild-started', '1'); setTimeout(() => {}, 10000);"], {
  cwd: process.cwd(),
  stdio: ["ignore", "inherit", "inherit"],
});
while (!existsSync("grandchild-started")) {}
while (true) {}
"#,
        )
        .unwrap();
        let started = std::time::Instant::now();
        let error =
            run_node_with_timeout(&harness, &scratch.0, std::time::Duration::from_millis(500))
                .unwrap_err();

        assert!(scratch.0.join("grandchild-started").is_file());
        assert!(error.contains("SCENARIO_TIMEOUT_EXCEEDED"), "{error}");
        assert!(started.elapsed() < std::time::Duration::from_secs(2));
    }

    #[test]
    fn property_validation_timeout_excludes_node_startup_and_module_import() {
        let scratch = scratch_directory().unwrap();
        write_file(
            &scratch.0.join("package.json"),
            "{\"private\":true,\"type\":\"module\"}\n",
        )
        .unwrap();
        write_file(
            &scratch.0.join("slow-import.validators.js"),
            r#"await new Promise((resolve) => setTimeout(resolve, 150));
export class ExternalValidationError extends Error {}
export const typeValidators = Object.freeze({
  "validator:test": () => true,
});
"#,
        )
        .unwrap();
        let property = TestProperty {
            definition: PropertyDefinition {
                id: SemanticId::endpoint_property("Tight", "Terminates"),
                name: "Terminates".into(),
                runs: 1,
                invariant: noxid_ir::PropertyInvariant::ValidatesOrRefuses,
                boundary: SemanticId::endpoint("Tight"),
                span: noxid_source::Span::new(0, 1),
            },
            boundary_kind: "endpoint",
            boundary_name: "Tight".into(),
            validator_module: "./slow-import.validators.js".into(),
            validators: vec![(SemanticId::parse("validator:test").unwrap(), Schema::String)],
            timeout: Duration::from_millis(50),
        };
        let started = Instant::now();
        let outcome = execute_property_case(
            &scratch.0,
            &property,
            &SemanticId::parse("validator:test").unwrap(),
            &GeneratedValue::String("ready".into()),
        )
        .unwrap();
        assert!(matches!(outcome, PropertyCaseOutcome::Pass));
        assert!(started.elapsed() >= Duration::from_millis(100));
    }

    #[test]
    fn property_failure_and_repro_use_the_shared_javascript_escape() {
        let property = TestProperty {
            definition: PropertyDefinition {
                id: SemanticId::endpoint_property("Escapes", "Reported"),
                name: "Reported".into(),
                runs: 1,
                invariant: noxid_ir::PropertyInvariant::ValidatesOrRefuses,
                boundary: SemanticId::endpoint("Escapes"),
                span: noxid_source::Span::new(0, 1),
            },
            boundary_kind: "endpoint",
            boundary_name: "Escapes".into(),
            validator_module: "./Escapes.validators.js".into(),
            validators: vec![],
            timeout: Duration::from_secs(1),
        };
        let failure = PropertyFailure::Case {
            seed: 1,
            run_index: 0,
            code: "PROPERTY_INVARIANT_VIOLATED",
            message: "failure\u{2028}line".into(),
            counterexample: "counterexample".into(),
            repro: "noxid test 'repro\u{2029}.nox' --seed 1".into(),
        };
        let javascript = property_result_javascript(&property, 1, Some(&failure));

        assert!(
            !javascript.contains('\u{2028}') && !javascript.contains('\u{2029}'),
            "{javascript}"
        );
        assert!(javascript.contains("failure\\u2028line"), "{javascript}");
        assert!(javascript.contains("repro\\u2029.nox"), "{javascript}");
    }

    fn fixture(name: &str, source: &str) -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "noxid-scenario-cli-{name}-{}-{nonce}",
            std::process::id()
        ));
        fs::create_dir_all(&root).unwrap();
        let path = root.join("Counter.nox");
        fs::write(&path, source).unwrap();
        path
    }

    fn endpoint_project_fixture(name: &str) -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "noxid-endpoint-scenario-cli-{name}-{}-{nonce}",
            std::process::id()
        ));
        fs::create_dir_all(root.join("server/api/items")).unwrap();
        fs::create_dir_all(root.join("src/components")).unwrap();
        fs::write(root.join("Noxid.toml"), "[app]\ntitle = \"Scenarios\"\n").unwrap();
        root
    }

    #[test]
    fn emitted_endpoint_property_runs_hostile_cases_and_gate_raises_the_floor() {
        let root = endpoint_project_fixture("property-pass");
        fs::write(
            root.join("server/api/items/validate.post.nox"),
            r#"type Payload { name: String count: Int }
endpoint ValidatePayload {
    body { payload: Payload }
    result: Boolean
    handler { return true }
    property TotalValidation { runs: 1 expect: validates or refuses }
}"#,
        )
        .unwrap();
        let output = execute(
            &root,
            &Options {
                gate: true,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(output.status.success(), "{stdout}");
        assert!(
            stdout.contains("\"id\":\"property:endpoint.ValidatePayload.TotalValidation\""),
            "{stdout}"
        );
        assert!(stdout.contains("\"property\":true"), "{stdout}");
        assert!(stdout.contains("\"runs\":100"), "{stdout}");
        assert!(stdout.contains("\"status\":\"pass\""), "{stdout}");
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn broken_validator_reports_seed_shrunk_counterexample_and_paste_ready_repro() {
        let scratch = scratch_directory().unwrap();
        write_file(
            &scratch.0.join("package.json"),
            "{\"private\":true,\"type\":\"module\"}\n",
        )
        .unwrap();
        write_file(
            &scratch.0.join("broken.validators.js"),
            r#"export class ExternalValidationError extends Error {}
export const typeValidators = Object.freeze({
  "validator:test": (value) => value.name,
});
"#,
        )
        .unwrap();
        let definition = PropertyDefinition {
            id: SemanticId::endpoint_property("Broken", "GetterSafety"),
            name: "GetterSafety".into(),
            runs: 1,
            invariant: noxid_ir::PropertyInvariant::ValidatesOrRefuses,
            boundary: SemanticId::endpoint("Broken"),
            span: noxid_source::Span::new(0, 1),
        };
        let property = TestProperty {
            definition: definition.clone(),
            boundary_kind: "endpoint",
            boundary_name: "Broken".into(),
            validator_module: "./broken.validators.js".into(),
            validators: vec![(
                SemanticId::parse("validator:test").unwrap(),
                Schema::Struct(vec![("name".into(), Schema::String)]),
            )],
            timeout: Duration::from_secs(1),
        };
        let execution = execute_properties(
            &scratch.0,
            Path::new("Broken.nox"),
            &BTreeMap::from([(definition.id.clone(), property)]),
            &Options {
                gate: false,
                json_only: true,
            },
            None,
            None,
        )
        .unwrap();

        assert!(
            execution.javascript.contains("PROPERTY_INVARIANT_VIOLATED"),
            "{}",
            execution.javascript
        );
        assert!(execution.javascript.contains("seed"));
        assert!(execution.javascript.contains("counterexample"));
        assert!(
            execution
                .javascript
                .contains("noxid test 'Broken.nox' --seed")
        );
        assert!(execution.javascript.contains("getterBomb"));
        assert!(execution.javascript.contains("Object.defineProperty"));
    }

    #[test]
    fn explicit_seed_replay_is_refused_after_a_property_rename() {
        let scratch = scratch_directory().unwrap();
        write_file(
            &scratch.0.join("package.json"),
            "{\"private\":true,\"type\":\"module\"}\n",
        )
        .unwrap();
        write_file(
            &scratch.0.join("broken.validators.js"),
            r#"export class ExternalValidationError extends Error {}
export const typeValidators = Object.freeze({
  "validator:test": (value) => value.name,
});
"#,
        )
        .unwrap();
        let test_property = |name: &str| {
            let definition = PropertyDefinition {
                id: SemanticId::endpoint_property("Broken", name),
                name: name.into(),
                runs: 1,
                invariant: noxid_ir::PropertyInvariant::ValidatesOrRefuses,
                boundary: SemanticId::endpoint("Broken"),
                span: noxid_source::Span::new(0, 1),
            };
            TestProperty {
                definition,
                boundary_kind: "endpoint",
                boundary_name: "Broken".into(),
                validator_module: "./broken.validators.js".into(),
                validators: vec![(
                    SemanticId::parse("validator:test").unwrap(),
                    Schema::Struct(vec![("name".into(), Schema::String)]),
                )],
                timeout: Duration::from_secs(1),
            }
        };
        let original = test_property("OriginalName");
        let seed = noxid_property_gen::property_seed(original.definition.id.as_str(), 0);
        let first = execute_properties(
            &scratch.0,
            Path::new("Broken.nox"),
            &BTreeMap::from([(original.definition.id.clone(), original)]),
            &Options {
                gate: false,
                json_only: true,
            },
            None,
            None,
        )
        .unwrap();
        let renamed = test_property("RenamedWithoutChangingTheSeed");
        // A seed carries the identity of the property that produced it. After a
        // rename the property is a different one, so the replay is refused with
        // a teaching message rather than silently re-deriving the case under a
        // name the seed never belonged to (Lane A follow-up sweep, round 1 QA).
        let replay = execute_properties(
            &scratch.0,
            Path::new("Broken.nox"),
            &BTreeMap::from([(renamed.definition.id.clone(), renamed)]),
            &Options {
                gate: false,
                json_only: true,
            },
            Some(seed),
            None,
        );
        let error = match replay {
            Ok(_) => panic!("a renamed property must not accept the old seed"),
            Err(error) => error.to_string(),
        };
        assert!(error.contains("PROPERTY_REPLAY_SEED_MISMATCH"), "{error}");
        assert!(error.contains("RenamedWithoutChangingTheSeed"), "{error}");
        assert!(first.javascript.contains(&format!("seed: \"{seed}\"")));
    }

    #[test]
    fn queue_payload_property_executes_the_emitted_validator() {
        let path = fixture(
            "queue-property",
            r#"type Payload { name: String }
queue ValidatePayload {
    payload { value: Payload }
    retry: 1
    backoff: 1s
    property Structured { runs: 6 expect: refusal is structured }
}"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(output.status.success(), "{stdout}");
        assert!(
            stdout.contains("\"id\":\"property:queue.ValidatePayload.Structured\""),
            "{stdout}"
        );
        assert!(stdout.contains("\"runs\":6"), "{stdout}");
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn property_timeout_reports_the_offending_seed() {
        let scratch = scratch_directory().unwrap();
        write_file(
            &scratch.0.join("package.json"),
            "{\"private\":true,\"type\":\"module\"}\n",
        )
        .unwrap();
        write_file(
            &scratch.0.join("hung.validators.js"),
            r#"export class ExternalValidationError extends Error {}
export const typeValidators = Object.freeze({
  "validator:test": () => { while (true) {} },
});
"#,
        )
        .unwrap();
        let definition = PropertyDefinition {
            id: SemanticId::endpoint_property("Hung", "Terminates"),
            name: "Terminates".into(),
            runs: 1,
            invariant: noxid_ir::PropertyInvariant::ValidatesOrRefuses,
            boundary: SemanticId::endpoint("Hung"),
            span: noxid_source::Span::new(0, 1),
        };
        let property = TestProperty {
            definition: definition.clone(),
            boundary_kind: "endpoint",
            boundary_name: "Hung".into(),
            validator_module: "./hung.validators.js".into(),
            validators: vec![(SemanticId::parse("validator:test").unwrap(), Schema::String)],
            timeout: Duration::from_millis(50),
        };
        let execution = execute_properties(
            &scratch.0,
            Path::new("Hung.nox"),
            &BTreeMap::from([(definition.id.clone(), property)]),
            &Options {
                gate: false,
                json_only: true,
            },
            None,
            None,
        )
        .unwrap();
        assert!(
            execution.javascript.contains("PROPERTY_TIMEOUT_EXCEEDED"),
            "{}",
            execution.javascript
        );
        assert!(execution.javascript.contains("seed"));
    }

    #[test]
    fn resource_given_emission_uses_the_scenario_seed_handshake_with_explicit_age() {
        let span = noxid_source::Span::new(0, 1);
        let resource_given = |age_milliseconds| noxid_ir::ScenarioGivenStep {
            target: SemanticId::resource_acquisition("Catalog", "products"),
            target_name: "products".into(),
            kind: ScenarioGivenKind::Resource,
            value: SemanticExpr {
                kind: SemanticExprKind::Int(7),
                ty: noxid_types::Type::Int,
                span,
            },
            age_milliseconds,
            span,
        };

        let mut aged = String::new();
        emit_given_step(&mut aged, &resource_given(Some(45_000))).expect("given step emits");
        assert!(aged.contains("$noxTest.mounted.resources[\"products\"].seedScenario(7, 45000);"));

        let mut unaged = String::new();
        emit_given_step(&mut unaged, &resource_given(None)).expect("given step emits");
        assert!(unaged.contains("$noxTest.mounted.resources[\"products\"].seedScenario(7, null);"));
        assert!(!aged.contains(".state.set("));
        assert!(!unaged.contains(".state.set("));
    }

    #[test]
    fn executes_generated_action_and_reports_failed_values() {
        let path = fixture(
            "failure",
            r#"component Counter {
                state { count: Int = 0 }
                computed { doubled = count * 2 }
                actions { increment() { count = count + 1 } }
                scenario IncrementOnce {
                    description: "two increments"
                    given: count = 0
                    when: increment(), increment()
                    expect: count == 3, doubled == 4
                }
                view { <p>{count}</p><button +click={increment}>go</button> }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(!output.status.success(), "{stdout}");
        assert!(stdout.contains("\"expression\":\"count == 3\""));
        assert!(stdout.contains("\"state:Counter.count\":2"));
        assert!(stdout.contains("\"computed:Counter.doubled\":4"));
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn executes_typed_invariants_at_mount_and_after_each_scenario_step() {
        let cases = [
            (
                "invariant-mount",
                r#"component Counter {
                    state { count: Int = -1 }
                    invariant NonNegative { assert: count >= 0 }
                    scenario MountBreach {
                        description: "mount is checked"
                        expect: count == -1
                    }
                    view { <p>{count}</p> }
                }"#,
                "\"step\":{\"phase\":\"mount\",\"index\":0,\"target\":null}",
                "\"state:Counter.count\":-1",
            ),
            (
                "invariant-given",
                r#"component Counter {
                    state { count: Int = 0 delta: Int = 0 }
                    invariant NonNegative { assert: count >= 0 && delta >= 0 }
                    scenario GivenBreach {
                        description: "every given is checked"
                        given: count = 1, delta = -1
                        expect: delta == -1
                    }
                    view { <p>{count}</p> }
                }"#,
                "\"step\":{\"phase\":\"given\",\"index\":1,\"target\":\"delta\"}",
                "\"state:Counter.delta\":-1",
            ),
            (
                "invariant-when",
                r#"component Counter {
                    state { count: Int = 0 }
                    computed { doubled = count * 2 }
                    actions { increment() { count = count + 1 } }
                    invariant Bounded { assert: count <= 1 && doubled <= 2 }
                    scenario WhenBreach {
                        description: "every action is checked"
                        when: increment(), increment()
                        expect: count == 2
                    }
                    view { <p>{doubled}</p> }
                }"#,
                "\"step\":{\"phase\":\"when\",\"index\":1,\"target\":\"increment\"}",
                "\"computed:Counter.doubled\":4",
            ),
        ];

        for (name, source, step, actual) in cases {
            let path = fixture(name, source);
            let output = execute(
                &path,
                &Options {
                    gate: false,
                    json_only: true,
                },
            )
            .unwrap();
            let stdout = String::from_utf8(output.stdout).unwrap();
            assert!(
                !output.status.success(),
                "{name} unexpectedly passed: {stdout}"
            );
            assert!(
                stdout.contains("\"invariantFailures\":[{\"id\":\"invariant:Counter."),
                "{name} did not report a structured invariant breach: {stdout}"
            );
            assert!(
                stdout.contains(step),
                "{name} lost its checkpoint: {stdout}"
            );
            assert!(
                stdout.contains("\"expression\":"),
                "{name} lost its invariant expression: {stdout}"
            );
            assert!(
                stdout.contains(actual),
                "{name} lost referenced actual values: {stdout}"
            );
            assert!(
                stdout.contains("\"assertions\":[]"),
                "{name} continued into expects after a breach: {stdout}"
            );
            fs::remove_dir_all(path.parent().unwrap()).unwrap();
        }
    }

    #[test]
    fn executes_resource_and_stream_givens_through_stubbed_runtime_handles() {
        let path = fixture(
            "boundary-givens",
            r#"type Customer { id: Int name: String }
            resource Customers(): Array<Customer> { get { GET "/must-not-fetch" } }
            stream Feed() {
                event Added(Customer)
                event Settled
                buffer 8
                backpressure drop_oldest
            }
            component BoundaryHarness {
                resources { customers = Customers() }
                streams { feed = Feed() }
                invariant ClosedLifecycle {
                    assert: customers == Idle || customers == Loading || customers == Ready([Customer(id = 7, name = "Ada")])
                }
                scenario ReadyAndEvents {
                    description: "ready payload and finite events reach emitted code"
                    given: customers = Ready([Customer(id = 7, name = "Ada")]), feed = [Added(Customer(id = 7, name = "Ada")), Settled]
                    expect: customers == Ready([Customer(id = 7, name = "Ada")])
                }
                scenario LoadingAndEmpty {
                    description: "non-ready lifecycle and empty stream remain deterministic"
                    given: customers = Loading, feed = []
                    expect: customers == Loading
                }
                view {
                    <section>
                        #match customers {
                            Idle { <p>idle</p> }
                            Loading { <p>loading</p> }
                            Ready(rows) { <p>{rows.count()}</p> }
                            Refreshing(rows) { <p>{rows.count()}</p> }
                            Failed(error) { <p>{error.code}</p> }
                        }
                        #stream feed {
                            Added(customer) { <p>{customer.name}</p> }
                            Settled { <p>settled</p> }
                            Completed { <p>completed</p> }
                            Failed(error) { <p>{error.code}</p> }
                        }
                    </section>
                }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(
            output.status.success(),
            "boundary scenarios failed:\nstdout={stdout}\nstderr={}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(stdout.contains("\"total\":2,\"passed\":2,\"failed\":0"));
        assert_eq!(stdout.matches("\"invariantFailures\":[]").count(), 2);
        assert!(stdout.contains("\"expression\":\"customers == Ready"));
        assert!(stdout.contains("\"expression\":\"customers == Loading\""));
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn executes_resource_age_and_successful_mutation_invalidation_scenarios() {
        let path = fixture(
            "resource-cache-algebra",
            r#"type Product { id: Int }
            resource Products(): Array<Product> {
                get { GET "/must-not-fetch" }
                cache 30s
            }
            component CacheScenarios {
                resources { products = Products() }
                actions {
                    server saveProduct(product: Product): Product {}
                    server previewProduct(product: Product): Product invalidates none {}
                    save() {
                        let outcome = await saveProduct(product: Product(id = 2))
                        #match outcome {
                            Ok(saved) {}
                            Err(error) {}
                        }
                    }
                    preview() {
                        let outcome = await previewProduct(product: Product(id = 3))
                        #match outcome {
                            Ok(saved) {}
                            Err(error) {}
                        }
                    }
                }
                scenario StaleSeedRefreshes {
                    description: "a Ready seed older than its TTL refreshes"
                    given: products = Ready([Product(id = 1)]) aged 45s
                    expect: products == Refreshing([Product(id = 1)])
                }
                scenario SuccessfulMutationInvalidates {
                    description: "derived invalidation refreshes cached data"
                    given: products = Ready([Product(id = 1)]), saveProduct = Ok(Product(id = 2))
                    when: save()
                    expect: products == Refreshing([Product(id = 1)])
                }
                scenario ExplicitNonePreservesReady {
                    description: "invalidates none preserves cached data"
                    given: products = Ready([Product(id = 1)]), previewProduct = Ok(Product(id = 3))
                    when: preview()
                    expect: products == Ready([Product(id = 1)])
                }
                view {
                    #match products {
                        Idle { <p>idle</p> }
                        Loading { <p>loading</p> }
                        Ready(rows) { <p>{rows.count()}</p> }
                        Refreshing(rows) { <p>{rows.count()}</p> }
                        Failed(error) { <p>{error.code}</p> }
                    }
                }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(
            output.status.success(),
            "cache scenarios failed:\nstdout={stdout}\nstderr={}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(stdout.contains("\"total\":3,\"passed\":3,\"failed\":0"));
        assert!(stdout.contains("\"name\":\"StaleSeedRefreshes\""));
        assert!(stdout.contains("\"name\":\"SuccessfulMutationInvalidates\""));
        assert!(stdout.contains("\"name\":\"ExplicitNonePreservesReady\""));
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn executes_remote_action_ok_and_err_givens_without_a_host_boundary() {
        let path = fixture(
            "remote-action-givens",
            r#"type Incident { id: Int }
            component RemoteForm {
                state { savedId: Int = 0 message: String = "" }
                actions {
                    server createIncident(request: Int): Incident {}
                    submit() {
                        savedId = -1
                        let outcome = await createIncident(request: 7)
                        #match outcome {
                            Ok(incident) { savedId = incident.id }
                            Err(error) { message = error.message }
                        }
                    }
                }
                scenario RemoteOk {
                    description: "typed success crosses the scenario-only boundary"
                    given: createIncident = Ok(Incident(id = 9))
                    when: submit()
                    expect: savedId == 9, message == ""
                }
                scenario RemoteErr {
                    description: "typed failure is consumed as RemoteError"
                    given: createIncident = Err(RemoteError(code = "CONFLICT", message = "already exists"))
                    when: submit()
                    expect: savedId == -1, message == "already exists"
                }
                view { <p>{savedId}</p> }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        assert!(
            output.status.success(),
            "stdout={}\nstderr={}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(stdout.contains("\"total\":2,\"passed\":2,\"failed\":0"));
        assert!(stdout.contains("\"expression\":\"savedId == 9\""));
        assert!(stdout.contains("\"expression\":\"message == \\\"already exists\\\"\""));
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn generated_harness_names_cannot_capture_component_scope() {
        let path = fixture(
            "hygiene",
            r#"component HarnessHygiene {
                state {
                    actualValues: Int = 0
                    assertions: Int = 0
                    failure: Int = 0
                    host: Int = 0
                    registration: Int = 0
                    runtime: Int = 0
                    scenarioScope: Int = 0
                }
                actions {
                    update() {
                        actualValues = 1
                        assertions = 2
                        failure = 3
                        host = 4
                        registration = 5
                        runtime = 6
                        scenarioScope = 7
                    }
                }
                scenario OrdinaryNames {
                    description: "harness implementation names stay private"
                    when: update()
                    expect: actualValues == 1, assertions == 2, failure == 3, host == 4, registration == 5, runtime == 6, scenarioScope == 7
                }
                view { <p>{actualValues}</p> }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        assert!(
            output.status.success(),
            "stdout={}\nstderr={}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn scenario_mount_grants_only_the_components_declared_capabilities() {
        let path = fixture(
            "declared-capability",
            r#"component AuthorizedCounter {
                requires [ counter.read ]
                state { count: Int = 0 }
                actions { increment() { count = count + 1 } }
                scenario DeclaredAuthority {
                    description: "scenario mounts with compiler-declared authority"
                    when: increment()
                    expect: count == 1
                }
                view { <p>{count}</p> }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap();
        assert!(
            output.status.success(),
            "declared scenario authority was not granted:\nstdout={}\nstderr={}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn gate_requires_passing_requirement_coverage() {
        let path = fixture(
            "gate",
            r#"component Counter {
                state { count: Int = 0 }
                requirement COUNTER_001 {
                    description: "covered by a passing scenario"
                    verify: ["scenario"]
                    depends: [count]
                }
                view { <p>{count}</p> }
            }"#,
        );
        let output = execute(
            &path,
            &Options {
                gate: true,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(!output.status.success(), "{stdout}");
        assert!(stdout.contains("requirement:COUNTER_001"));
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn refuses_unstubbed_boundaries_before_starting_node() {
        let path = fixture(
            "boundary",
            r#"resource Customers(): String { get { GET "/customers" } }
            component Counter {
                resources { customers = Customers() }
                state { count: Int = 0 }
                scenario CannotReachNetwork {
                    description: "network is forbidden in phase one"
                    given: count = 0
                    expect: count == 0
                }
                view { <p>{count}</p> }
            }"#,
        );
        let error = execute(
            &path,
            &Options {
                gate: false,
                json_only: true,
            },
        )
        .unwrap_err();
        assert!(
            error.contains("SCENARIO_RESOURCE_BOUNDARY_UNSTUBBED"),
            "{error}"
        );
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }

    #[test]
    fn executes_endpoint_scenarios_through_the_shipped_fetch_handler() {
        let project = endpoint_project_fixture("fetch-handler");
        fs::write(
            project.join("server/api/items/[id].post.nox"),
            r#"type Tagged { tag: String notes: Optional<Array<String>> }
type Echoed { id: String page: Int tag: String }
endpoint EchoItem {
    params { id: String }
    query { page: Int }
    body { payload: Tagged }
    result: Echoed
    handler { return Echoed(id = id, page = page, tag = payload.tag) }
    scenario RoundTrip {
        description: "path, query, and body cross the emitted Fetch boundary"
        when: request(params: Shape(id = "a/b"), query: Shape(page = 7), body: Shape(payload = Tagged(tag = "None", notes = Some(["</script><script>hostile()</script>"]))))
        expect: status == 200, value == Echoed(id = "a/b", page = 7, tag = "None"), refusal == ""
    }
    scenario NestedOptionalNone {
        description: "nested None crosses as JSON null without mangling an ordinary tag field"
        when: request(params: Shape(id = "none"), query: Shape(page = 8), body: Shape(payload = Tagged(tag = "None", notes = None)))
        expect: status == 200, value == Echoed(id = "none", page = 8, tag = "None")
    }
    scenario NestedOptionalSomeEmpty {
        description: "nested Some empty array stays present as an empty JSON array"
        when: request(params: Shape(id = "empty"), query: Shape(page = 9), body: Shape(payload = Tagged(tag = "Some", notes = Some([]))))
        expect: status == 200, value == Echoed(id = "empty", page = 9, tag = "Some")
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/hosted.get.nox"),
            r#"type HostedValue { message: String }
endpoint Hosted {
    result: HostedValue
    scenario ExactHostStub {
        description: "the exact endpoint semantic key is stubbed"
        given: Hosted = HostedValue(message = "safe")
        when: request()
        expect: status == 200, value == HostedValue(message = "safe"), refusal == ""
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/reject.get.nox"),
            r#"type Accepted { value: Int }
type Refused { reason: String }
endpoint Reject {
    result: Result<Accepted, Refused>
    handler { return Err(Refused(reason = "no")) }
    scenario TypedErr {
        description: "typed Result Err crosses as 422"
        when: request()
        expect: status == 422, refusal == "ENDPOINT_RESULT_ERR"
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/denied.get.nox"),
            r#"endpoint Denied {
    result: Int
    capabilities [secret.read]
    handler { return 1 }
    scenario Refusal {
        description: "undeclared scenario authority fails closed"
        when: request()
        expect: status == 403, refusal == "ENDPOINT_CAPABILITY_DENIED"
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/arrays.get.nox"),
            r#"endpoint Arrays {
    query { tags: Array<String> ranks: Optional<Array<Int>> }
    result: Int
    handler { return tags.count() }
    scenario JsonArray {
        description: "array query values use one JSON-array URL value"
        when: request(query: Shape(tags = ["a&b", "two"], ranks = Some([3, 4])))
        expect: status == 200, value == 2
    }
    scenario EmptyAndAbsent {
        description: "empty arrays and absent optional arrays remain distinct"
        when: request(query: Shape(tags = [], ranks = None))
        expect: status == 200, value == 0
    }
    scenario PresentEmptyOptional {
        description: "Some empty array stays distinct from None on the wire"
        when: request(query: Shape(tags = [""], ranks = Some([])))
        expect: status == 200, value == 1
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/ip-limited.post.nox"),
            r#"endpoint IpLimited {
    body { value: Int }
    result: Int
    limit: 1 per minute per ip
    handler { return value }
    scenario FirstIpIdentity {
        description: "the first scenario receives a trusted deterministic IP identity"
        when: request(body: Shape(value = 11))
        expect: status == 200, value == 11, refusal == ""
    }
    scenario SecondIpIdentity {
        description: "a sibling scenario is isolated under its own deterministic IP identity"
        when: request(body: Shape(value = 12))
        expect: status == 200, value == 12, refusal == ""
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/session-limited.post.nox"),
            r#"endpoint SessionLimited {
    body { value: Int }
    result: Int
    limit: 1 per hour per session
    handler { return value }
    scenario FirstSessionIdentity {
        description: "the first scenario receives a deterministic session identity"
        when: request(body: Shape(value = 21))
        expect: status == 200, value == 21, refusal == ""
    }
    scenario SecondSessionIdentity {
        description: "a sibling scenario is isolated under its own deterministic session identity"
        when: request(body: Shape(value = 22))
        expect: status == 200, value == 22, refusal == ""
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/idempotent.post.nox"),
            r#"endpoint Idempotent {
    body { value: Int }
    result: Int
    idempotent
    handler { return value }
    scenario DeterministicReplayIdentity {
        description: "scenario id supplies both replay key and trusted identity"
        when: request(body: Shape(value = 31))
        expect: status == 200, value == 31, refusal == ""
    }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/host.js"),
            r#"throw new Error("REAL_HOST_EXECUTED");
export const actions = { "endpoint:Hosted@1": async () => fetch("https://must-not-run.invalid") };
"#,
        )
        .unwrap();
        fs::write(
            project.join("src/components/Counter.nox"),
            r#"component Counter {
    state { count: Int = 0 }
    scenario ComponentAlongsideEndpoints {
        description: "component and endpoint IDs share one deterministic report"
        expect: count == 0
    }
    view { <p>{count}</p> }
}"#,
        )
        .unwrap();

        let output = execute(
            &project,
            &Options {
                gate: true,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(
            output.status.success(),
            "endpoint scenarios failed:\nstdout={stdout}\nstderr={}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(stdout.contains("\"total\":15,\"passed\":15,\"failed\":0"));
        assert!(stdout.contains("\"id\":\"scenario:Counter.ComponentAlongsideEndpoints\""));
        assert!(stdout.contains("\"semanticUnit\":\"endpoint:Arrays@1\""));
        assert!(stdout.contains("\"semanticUnit\":\"endpoint:Denied@1\""));
        assert!(stdout.contains("\"semanticUnit\":\"endpoint:EchoItem@1\""));
        assert!(stdout.contains("\"semanticUnit\":\"endpoint:Hosted@1\""));
        assert!(stdout.contains("\"semanticUnit\":\"endpoint:Reject@1\""));
        assert!(!stdout.contains("REAL_HOST_EXECUTED"));
        fs::remove_dir_all(project).unwrap();
    }

    #[test]
    fn endpoint_expectation_failure_fails_the_gate_with_observed_values() {
        let project = endpoint_project_fixture("failed-expectation");
        fs::write(
            project.join("server/api/failure.get.nox"),
            r#"endpoint Failure { result: Int handler { return 7 }
    scenario WrongStatus {
        description: "a false emitted response expectation fails the command"
        when: request()
        expect: status == 201, value == 8
    }
}"#,
        )
        .unwrap();

        let output = execute(
            &project,
            &Options {
                gate: true,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(!output.status.success(), "{stdout}");
        assert!(stdout.contains("\"ok\":false"));
        assert!(stdout.contains("\"endpoint-scenario-value:Failure.WrongStatus.status\":200"));
        assert!(stdout.contains("\"endpoint-scenario-value:Failure.WrongStatus.value\":7"));
        fs::remove_dir_all(project).unwrap();
    }

    #[test]
    fn endpoint_file_input_selects_only_its_scenarios_from_the_project() {
        let project = endpoint_project_fixture("single-file");
        let selected_file = project.join("server/api/selected.get.nox");
        fs::write(
            &selected_file,
            r#"endpoint Selected { result: Int handler { return 1 }
    scenario Only { description: "selected source" when: request() expect: value == 1 }
}"#,
        )
        .unwrap();
        fs::write(
            project.join("server/api/unselected.get.nox"),
            r#"endpoint Unselected { result: Int handler { return 2 }
    scenario Other { description: "other source" when: request() expect: value == 2 }
}"#,
        )
        .unwrap();

        let output = execute(
            &selected_file,
            &Options {
                gate: true,
                json_only: true,
            },
        )
        .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(output.status.success(), "{stdout}");
        assert!(stdout.contains("\"total\":1,\"passed\":1,\"failed\":0"));
        assert!(stdout.contains("scenario:endpoint.Selected.Only"));
        assert!(!stdout.contains("scenario:endpoint.Unselected.Other"));
        fs::remove_dir_all(project).unwrap();
    }

    #[test]
    fn affected_endpoint_selection_executes_only_the_selected_semantic_id() {
        let project = endpoint_project_fixture("affected-selection");
        fs::write(
            project.join("server/api/selected.get.nox"),
            r#"endpoint Selected { result: Int handler { return 1 }
    scenario First { description: "not selected" when: request() expect: value == 1 }
    scenario Second { description: "selected" when: request() expect: value == 1 }
}"#,
        )
        .unwrap();
        let selected = BTreeSet::from([SemanticId::endpoint_scenario("Selected", "Second")]);
        let report = execute_selected_report(
            &project,
            &Options {
                gate: false,
                json_only: true,
            },
            &selected,
        )
        .unwrap();
        assert!(report.success, "{}\n{}", report.json, report.stderr);
        assert!(
            report
                .json
                .contains("\"total\":1,\"passed\":1,\"failed\":0")
        );
        assert!(report.json.contains("scenario:endpoint.Selected.Second"));
        assert!(!report.json.contains("scenario:endpoint.Selected.First"));
        fs::remove_dir_all(project).unwrap();
    }

    #[test]
    fn standalone_endpoint_scenario_refuses_to_invent_file_routing() {
        let path = fixture(
            "endpoint-project-required",
            r#"endpoint Standalone { result: Int handler { return 1 }
    scenario One { description: "requires canonical routing" when: request() expect: value == 1 }
}"#,
        );
        let error = execute(
            &path,
            &Options {
                gate: true,
                json_only: true,
            },
        )
        .unwrap_err();
        assert!(
            error.contains("ENDPOINT_SCENARIO_PROJECT_REQUIRED"),
            "{error}"
        );
        fs::remove_dir_all(path.parent().unwrap()).unwrap();
    }
}