nova-cli 0.3.0

The Nova programming language: compiler, formatter, language server, package manager and documentation generator
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
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
//! End-to-end `nova run` tests — the Phase 1 gate criteria
//! (00-MASTER-SPEC.md §3, Phase 1).

use assert_cmd::Command;
use std::path::PathBuf;

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(|p| p.parent())
        .expect("crates/nova-cli has a repo root two levels up")
        .to_path_buf()
}

fn nova() -> Command {
    Command::cargo_bin("nova").expect("nova binary builds")
}

#[test]
fn gate_1_hello_world_runs() {
    nova()
        .arg("run")
        .arg(repo_root().join("examples/01-hello-world/src/main.nova"))
        .assert()
        .success()
        .stdout("Hello, World!\n");
}

#[test]
fn gate_2_fibonacci_runs() {
    nova()
        .arg("run")
        .arg(repo_root().join("examples/02-fibonacci/src/main.nova"))
        .assert()
        .success()
        .stdout("fib(10) = 55\n");
}

/// `60-EXAMPLES.md` §2's gate, as written: `nova run -- 20` in the example's
/// own directory prints `fib(20) = 6765`.
#[test]
fn gate_2_fibonacci_reads_its_argument() {
    nova()
        .current_dir(repo_root().join("examples/02-fibonacci"))
        .arg("run")
        .arg("--")
        .arg("20")
        .assert()
        .success()
        .stdout("fib(20) = 6765\n");
}

#[test]
fn gate_3_match_on_enum_runs() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/match_enum.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/match_enum.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn gate_4_generic_functions_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/generics.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/generics.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn records_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/records.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/records.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn field_assign_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/field_assign.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/field_assign.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn field_assign_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/field_assign.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/field_assign.nova", "field_assign");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

#[test]
fn for_loops_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/for_loops.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/for_loops.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn arrays_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/arrays.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/arrays.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn array_out_of_bounds_aborts() {
    let dir = std::env::temp_dir().join("nova-oob");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("oob.nova");
    std::fs::write(
        &file,
        "fn main() { let a = [1, 2, 3]\n println(\"${a[5]}\") }",
    )
    .expect("write");
    let exe = dir.join(format!("oob{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let out = Command::new(&exe).assert().failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert!(stderr.contains("out of bounds"), "stderr: {stderr}");
}

#[test]
fn array_repeat_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/array_repeat.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/array_repeat.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn array_repeat_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/array_repeat.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/array_repeat.nova", "array_repeat");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// A negative repeat length is guarded, not clamped: `[x; -1]` aborts at the
/// allocation with a message naming the problem, rather than silently yielding
/// an empty array whose first index then fails somewhere that looks fine.
/// Mirrors `array_out_of_bounds_aborts`, the same abort-on-bad-input policy.
#[test]
fn repeat_array_negative_length_aborts() {
    let dir = std::env::temp_dir().join("nova-neg-len");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("neg_len.nova");
    std::fs::write(
        &file,
        "fn main() { let n = 0 - 1\n let a = [7; n]\n println(\"${a.len()}\") }",
    )
    .expect("write");
    let exe = dir.join(format!("neg_len{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let out = Command::new(&exe).assert().failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert!(
        stderr.contains("array length must not be negative"),
        "stderr: {stderr}"
    );
}

/// An *overlong* repeat length is guarded too — and unlike the negative case
/// this one was memory-unsafe, not merely confusing. Both backends compute the
/// allocation size as `8 * len + 8` with wrapping arithmetic, so at
/// `len = 2^60` the size wraps to `i64::MIN + 8`, `gc::alloc`'s `size.max(8)`
/// clamps it to an **8-byte** block, the huge length is written into that
/// block's header, and the fill loop (deliberately unchecked) then writes far
/// past the end. This program used to exit 139 (SIGSEGV) with no output.
///
/// `[init; n]` is the only way to allocate a runtime-length array, so `n` is by
/// design a computed value and this is reachable from ordinary code.
#[test]
fn repeat_array_overlong_length_aborts_instead_of_segfaulting() {
    let dir = std::env::temp_dir().join("nova-huge-len");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("huge_len.nova");
    // `1 << 60`, written as a shift so no literal-overflow question arises.
    std::fs::write(
        &file,
        "fn main() { let n = 1 << 60\n let a = [7; n]\n println(\"${a.len()}\") }",
    )
    .expect("write");
    let exe = dir.join(format!("huge_len{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let out = Command::new(&exe).assert().failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert!(
        stderr.contains("array length is too large"),
        "stderr: {stderr}"
    );
    // The JIT path shares the lowering, but assert it too: a segfault there
    // would take the compiler process down rather than a child.
    let assert = nova().arg("run").arg(&file).assert().failure();
    let jit_stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        jit_stderr.contains("array length is too large"),
        "stderr: {jit_stderr}"
    );
}

/// The very top of the *legal* length range is a clean Nova abort, not a Rust
/// one. `MAX_ARRAY_LEN` is the largest length whose `8 * len + 8` size still fits
/// in an `i64`, so the lowering's guards both pass — but at `ALIGN = 16` that
/// size rounds up 8 bytes past `isize::MAX`, so `Layout::from_size_align` cannot
/// describe it. That used to reach an `expect` in `gc::alloc` and end the
/// process with "thread caused non-unwinding panic" plus a Rust backtrace.
///
/// The check happens before any allocation is attempted, so this test costs
/// nothing in memory. `gc::alloc` is shared by every allocation site in the
/// language, so this covers records, strings, closures and collection growth
/// too — arrays are just the one path that can name such a size in one line.
#[test]
fn undescribable_allocation_size_aborts_cleanly() {
    let dir = std::env::temp_dir().join("nova-max-len");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("max_len.nova");
    // `(1 << 60) - 2` is exactly `MAX_ARRAY_LEN`, written as a shift so no
    // literal-overflow question arises.
    std::fs::write(
        &file,
        "fn main() { let n = (1 << 60) - 2\n let a = [7; n]\n println(\"${a.len()}\") }",
    )
    .expect("write");
    let exe = dir.join(format!("max_len{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let out = Command::new(&exe).assert().failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: allocation of 9223372036854775800 bytes exceeds the maximum object size of 9223372036854775792 bytes"),
        "stderr: {stderr}"
    );
    // The point of the fix: a Nova diagnostic instead of a Rust panic. Also
    // distinct from the genuine out-of-memory wording ("memory allocation of N
    // bytes failed"), which a merely-too-big length still produces.
    assert!(
        !stderr.contains("panicked at") && !stderr.contains("non-unwinding"),
        "expected no Rust panic, stderr: {stderr}"
    );
    // The JIT shares `gc::alloc`, but assert it too: the abort happens inside
    // the compiler process there.
    let assert = nova().arg("run").arg(&file).assert().failure();
    let jit_stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        jit_stderr.contains("exceeds the maximum object size"),
        "stderr: {jit_stderr}"
    );
    assert!(
        !jit_stderr.contains("panicked at"),
        "expected no Rust panic, stderr: {jit_stderr}"
    );
}

#[test]
fn constants_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/constants.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/constants.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn break_continue_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/break_continue.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/break_continue.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn closures_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/closures.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/closures.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn closures_build_standalone() {
    let out = build_and_run("tests/runtime/closures.nova", "closures");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/closures.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn generic_impls_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/generic_impls.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/generic_impls.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn generic_impls_build_standalone() {
    let out = build_and_run("tests/runtime/generic_impls.nova", "generic_impls");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/generic_impls.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn method_generics_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/method_generics.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/method_generics.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn method_generics_build_standalone() {
    let out = build_and_run("tests/runtime/method_generics.nova", "method_generics");
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/method_generics.stdout"))
            .expect("fixture")
            .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn where_clauses_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/where_clauses.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/where_clauses.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn where_clauses_build_standalone() {
    let out = build_and_run("tests/runtime/where_clauses.nova", "where_clauses");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/where_clauses.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn prelude_option_result_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/prelude_option_result.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/prelude_option_result.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn prelude_option_result_build_standalone() {
    let out = build_and_run(
        "tests/runtime/prelude_option_result.nova",
        "prelude_option_result",
    );
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/prelude_option_result.stdout"))
            .expect("fixture")
            .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

/// `nova run`'s Cranelift JIT cannot resolve the libm symbol `sqrt` at run
/// time on Linux only (`E0902`) -- `nova build`'s ahead-of-time link step
/// resolves the same symbol fine on the same platform, and this exact `nova
/// run` invocation passes on macOS and Windows. Filed as
/// <https://github.com/Sakeerin/nova/issues/3> rather than fixed here: the
/// right remedy is a design decision (explicitly load `libm` at JIT setup,
/// or document `extern` libm-family functions as build-only on Linux), not
/// a mechanical patch.
///
/// `#[ignore]`, not `#[cfg(not(target_os = "linux"))]`, and only on Linux:
/// an ignored test still shows up in every platform's test counts (`cargo
/// test`'s summary line, and `-- --ignored` on the advisory CI step), while
/// a `cfg`-ed-out one vanishes with no trace anywhere -- and invisibility is
/// exactly how the defects this PR exists to fix survived undetected.
/// Matches the precedent of ADR 0010's eight documented ignores. Unaffected
/// on macOS and Windows, where it keeps running (and passing) normally.
#[test]
#[cfg_attr(
    target_os = "linux",
    ignore = "E0902 at JIT time on Linux; see issue #3"
)]
fn extern_ffi_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/extern_ffi.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/extern_ffi.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn extern_ffi_build_standalone() {
    let out = build_and_run("tests/runtime/extern_ffi.nova", "extern_ffi");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/extern_ffi.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn extern_unresolvable_symbol_is_a_clean_error_not_a_panic() {
    let dir = std::env::temp_dir().join("nova-extern-unresolvable");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("bad.nova");
    std::fs::write(
        &file,
        "extern \"C\" { fn totally_bogus_symbol_xyz(x: Int) -> Int }\n\
         fn main() { println(\"${totally_bogus_symbol_xyz(3)}\") }\n",
    )
    .expect("write");
    let assert = nova().arg("run").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0902"), "stderr: {stderr}");
    // Must be a clean diagnostic, not a Rust panic nor a "compiler bug" label.
    assert!(!stderr.contains("panicked"), "should not panic: {stderr}");
    assert!(
        !stderr.contains("compiler bug"),
        "not a compiler bug: {stderr}"
    );
}

/// Regression for the `collect_impls` self-prepend bug (commit c4269ec):
/// `nova check` used to accept a self-less inherent method called on an
/// instance, and codegen then died with a Cranelift verifier error and
/// "internal codegen error (this is a compiler bug)". It must now be
/// rejected cleanly at type-check time with `E0014`, with no ICE.
#[test]
fn selfless_inherent_method_called_on_instance_is_e0014_not_an_ice() {
    let dir = std::env::temp_dir().join("nova-selfless-inherent-call");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("selfless_call.nova");
    std::fs::write(
        &file,
        "record P { v: Int }\n\
         impl P { fn make() -> P { P { v: 7 } } }\n\
         fn main() {\n\
             let p = P { v: 0 }\n\
             let q = p.make()\n\
             println(\"${q.v}\")\n\
         }\n",
    )
    .expect("write");
    let assert = nova().arg("run").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0014"), "stderr: {stderr}");
    // Must be a clean diagnostic, never the Cranelift verifier dump or the
    // "compiler bug" label the pre-fix codegen ICE produced.
    assert!(!stderr.contains("panicked"), "should not panic: {stderr}");
    assert!(
        !stderr.contains("compiler bug"),
        "not a compiler bug: {stderr}"
    );
}

/// Associated-function call syntax (`Type::f(args)`, commit 865bff4):
/// `P::new()` must produce the same value under both backends, mirroring
/// how every other feature in this file is checked for backend parity.
#[test]
fn assoc_fn_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/assoc_fn.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/assoc_fn.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn assoc_fn_build_standalone() {
    let out = build_and_run("tests/runtime/assoc_fn.nova", "assoc_fn");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/assoc_fn.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

/// Trait associated functions (`Type::name(…)` for a trait method with no
/// `self`), including dispatch through a generic parameter's bound. Checked
/// end-to-end under both backends because the bug class here is a *codegen*
/// one: a receiver lowered into a callee that has no `self` parameter type-checks
/// fine and is only caught by the backend's arity verifier, so no typeck- or
/// MIR-level test can stand in for actually running the program.
#[test]
fn trait_assoc_fn_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/trait_assoc_fn.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/trait_assoc_fn.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn trait_assoc_fn_build_standalone() {
    let out = build_and_run("tests/runtime/trait_assoc_fn.nova", "trait_assoc_fn");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/trait_assoc_fn.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

/// Supertraits (`trait Ranked: Named`): a bound `T: Ranked` calls the
/// supertrait's methods, a default body reaches them through `Self`, and
/// conditional impls (`impl<T: Ranked> Named for Boxed<T>`) discharge the
/// supertrait-derived bounds at monomorphization. Run end-to-end because the
/// interesting failure is a *dispatch* one: the type checker resolves the
/// supertrait call against the trait's signature while monomorphization picks
/// the impl function, so only executing the program proves they agree.
#[test]
fn supertraits_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/supertraits.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/supertraits.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn supertraits_build_standalone() {
    let out = build_and_run("tests/runtime/supertraits.nova", "supertraits");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/supertraits.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn generic_trait_methods_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/generic_trait_methods.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/generic_trait_methods.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn generic_trait_methods_build_standalone() {
    let out = build_and_run(
        "tests/runtime/generic_trait_methods.nova",
        "generic_trait_methods",
    );
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/generic_trait_methods.stdout"))
            .expect("fixture")
            .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn conflicting_cross_module_extern_signatures_report_e0075() {
    let dir = std::env::temp_dir().join("nova-extern-conflict");
    std::fs::create_dir_all(&dir).expect("temp dir");
    std::fs::write(
        dir.join("mod_a.nova"),
        "extern \"C\" { fn sqrt(x: Float) -> Float }\npub fn ca() -> Float { sqrt(16.0) }\n",
    )
    .expect("write a");
    std::fs::write(
        dir.join("mod_b.nova"),
        "extern \"C\" { fn sqrt(x: Int) -> Int }\npub fn cb() -> Int { sqrt(16) }\n",
    )
    .expect("write b");
    let main = dir.join("main.nova");
    std::fs::write(
        &main,
        "import mod_a::{ca}\nimport mod_b::{cb}\nfn main() { println(\"${ca()} ${cb()}\") }\n",
    )
    .expect("write main");
    let assert = nova().arg("check").arg(&main).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0075"), "stderr: {stderr}");
    assert!(!stderr.contains("panicked"), "should not panic: {stderr}");
}

#[test]
fn modules_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/modules/main.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/modules/main.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn modules_build_standalone() {
    let out = build_and_run("tests/runtime/modules/main.nova", "modules_main");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/modules/main.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn import_of_private_item_is_rejected() {
    let dir = std::env::temp_dir().join("nova-mod-priv");
    std::fs::create_dir_all(&dir).expect("temp dir");
    std::fs::write(dir.join("lib.nova"), "fn hidden() -> Int { 1 }\n").expect("write lib");
    let main = dir.join("app.nova");
    std::fs::write(
        &main,
        "import lib::{hidden}\nfn main() { let x = hidden() }\n",
    )
    .expect("write");
    let assert = nova().arg("check").arg(&main).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0001"), "stderr: {stderr}");
}

/// Two modules each defining a same-named function must lower to distinct
/// symbols and dispatch to their own definition — not collapse to one at
/// monomorphization. Regression for the module-merge mangling collision.
#[test]
fn modules_same_name_functions_dispatch_correctly() {
    let dir = std::env::temp_dir().join("nova-mod-collide-fn");
    std::fs::create_dir_all(&dir).expect("temp dir");
    std::fs::write(
        dir.join("lib.nova"),
        "fn helper() -> Int { 200 }\npub fn lib_val() -> Int { helper() }\n",
    )
    .expect("write lib");
    let main = dir.join("main.nova");
    std::fs::write(
        &main,
        "import lib::{lib_val}\n\
         fn helper() -> Int { 100 }\n\
         fn main() {\n\
             println(\"main=${helper()}\")\n\
             println(\"lib=${lib_val()}\")\n\
         }\n",
    )
    .expect("write main");
    // main's own helper() is 100; lib_val() calls lib's helper() = 200.
    nova()
        .arg("run")
        .arg(&main)
        .assert()
        .success()
        .stdout("main=100\nlib=200\n");
}

/// Two modules each defining a same-named record with a same-named inherent
/// method must dispatch each call to its own method body. Regression for the
/// impl-method symbol collision across modules.
#[test]
fn modules_same_name_methods_dispatch_correctly() {
    let dir = std::env::temp_dir().join("nova-mod-collide-method");
    std::fs::create_dir_all(&dir).expect("temp dir");
    std::fs::write(
        dir.join("lib.nova"),
        "record Box { v: Int }\n\
         impl Box { fn get(self) -> Int { self.v + 1000 } }\n\
         pub fn make_b() -> Int { Box { v: 7 }.get() }\n",
    )
    .expect("write lib");
    let main = dir.join("main.nova");
    std::fs::write(
        &main,
        "import lib::{make_b}\n\
         record Box { v: Int }\n\
         impl Box { fn get(self) -> Int { self.v } }\n\
         fn main() {\n\
             let a = Box { v: 1 }\n\
             println(\"main=${a.get()}\")\n\
             println(\"lib=${make_b()}\")\n\
         }\n",
    )
    .expect("write main");
    // main's Box.get is `self.v` = 1; lib's Box.get is `self.v + 1000` = 1007.
    nova()
        .arg("run")
        .arg(&main)
        .assert()
        .success()
        .stdout("main=1\nlib=1007\n");
}

/// A qualified/nested import path (`a::b`) is not supported and must be rejected
/// explicitly rather than silently binding the last segment's module.
#[test]
fn multi_segment_import_is_rejected() {
    let dir = std::env::temp_dir().join("nova-mod-qualified");
    std::fs::create_dir_all(&dir).expect("temp dir");
    std::fs::write(dir.join("foo.nova"), "pub fn marker() -> Int { 1 }\n").expect("write foo");
    std::fs::write(dir.join("bar.nova"), "pub fn marker() -> Int { 2 }\n").expect("write bar");
    let main = dir.join("main.nova");
    std::fs::write(
        &main,
        "import foo::bar\nfn main() { println(\"${marker()}\") }\n",
    )
    .expect("write main");
    let assert = nova().arg("check").arg(&main).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0900"), "stderr: {stderr}");
}

#[test]
fn traits_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/traits.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/traits.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn traits_build_standalone() {
    let out = build_and_run("tests/runtime/traits.nova", "traits");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/traits.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn check_reports_type_errors_with_code() {
    let dir = std::env::temp_dir().join("nova-check-test");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("bad.nova");
    std::fs::write(&file, "fn main() { let x: Int = \"hello\" }").expect("write test file");
    let assert = nova().arg("check").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0010"), "stderr was: {stderr}");
}

#[test]
fn check_passes_on_valid_program() {
    nova()
        .arg("check")
        .arg(repo_root().join("examples/02-fibonacci/src/main.nova"))
        .assert()
        .success();
}

/// `nova check` must reject an unsatisfied trait bound — it runs
/// monomorphization so its "ok" verdict matches what `nova run` accepts.
#[test]
fn check_rejects_unsatisfied_trait_bound() {
    let dir = std::env::temp_dir().join("nova-check-bound");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("bound.nova");
    std::fs::write(
        &file,
        "record P { v: Int }\n\
         trait Show { fn name(self) -> String }\n\
         impl Show for P { fn name(self) -> String { \"p\" } }\n\
         fn label<T: Show>(x: T) -> String { x.name() }\n\
         fn main() { println(label(5)) }\n",
    )
    .expect("write");
    let assert = nova().arg("check").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0013"), "stderr: {stderr}");
}

/// `nova check` must reject an `impl` of a subtrait whose supertrait is not
/// implemented for the same type — the whole point of `trait B: A` is that the
/// bound `T: B` may rely on `A`'s methods existing.
#[test]
fn check_rejects_impl_missing_a_supertrait() {
    let dir = std::env::temp_dir().join("nova-check-supertrait");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("supertrait.nova");
    std::fs::write(
        &file,
        "trait Named { fn name(self) -> String }\n\
         trait Ranked: Named { fn rank(self) -> Int }\n\
         record P { v: Int }\n\
         impl Ranked for P { fn rank(self) -> Int { self.v } }\n\
         fn main() { }\n",
    )
    .expect("write");
    let assert = nova().arg("check").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0072"), "stderr: {stderr}");
    assert!(
        stderr.contains("requires `Named`"),
        "the diagnostic should name the missing supertrait: {stderr}"
    );
}

/// An `async fn` with NO `.await` anywhere in it, merely called from `main`
/// and its result discarded, now COMPILES and RUNS -- Phase 2.3a Task 5
/// replaced the `E0088` rejection of this shape with the real state-machine
/// transform.
///
/// At `Float`, which is where the rejection came from in the first place: an
/// async fn's declared MIR return class comes from `ret_ty` (`Future<T>`,
/// always `MirTy::Ptr`) while its body produces `T` directly, and at
/// `T = Float` (`MirTy::F64`) those are different Cranelift register classes,
/// so the verifier rejected the function with "result 0 has type f64, must
/// match function signature of i64", surfaced as `internal codegen error
/// (this is a compiler bug)`. Both commands are still asserted, because
/// `nova check` runs the same lowering stage and used to reject here too.
///
/// **What this does and does not prove.** It proves the whole program
/// compiles, links through the JIT, and runs to a clean exit -- so the
/// wrapper's state allocation and fat-pointer construction are real machine
/// code that executes. It does NOT prove the async fn's BODY ran: at the time
/// this test was written nothing in Nova could poll a future — `Future` is a
/// nameable type, but naming one is not driving one, there is no await outside
/// an `async fn`, and an `extern` signature accepts only Int/Float/Bool — so
/// `f()`'s future here is built and dropped. `std/task`'s `block_on` is what
/// later made driving a future reachable from source; this fixture deliberately
/// does not use it, because what it pins is the await-free wrapper compiling and
/// running at `Float`. `nova-driver`'s `async_end_to_end` module is where the
/// body is actually driven to completion and its `Float` value checked, in
/// process, because that needs MIR-level calling code no `.nova` file can
/// express until Task 7's `std/task`.
///
/// Asserting the ABSENCE of the old crash text, not just `.success()`, is
/// deliberate: `nova run` prints diagnostics to stderr and still could have
/// exited zero on some paths.
#[test]
fn run_and_check_accept_and_run_an_await_free_async_fn_at_float() {
    let dir = std::env::temp_dir().join("nova-async-no-await-float");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("float_no_await.nova");
    std::fs::write(
        &file,
        "async fn f() -> Float { 1.5 }\n\
         fn main() { let x = f()\n  println(\"done\") }\n",
    )
    .expect("write test file");

    nova().arg("check").arg(&file).assert().success();

    let run_assert = nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("done\n");
    let run_stderr = String::from_utf8_lossy(&run_assert.get_output().stderr).to_string();
    assert!(
        !run_stderr.contains("E0088"),
        "an await-free async fn must no longer be rejected: {run_stderr}"
    );
    assert!(
        !run_stderr.contains("internal codegen error"),
        "must not reach the codegen ICE path: {run_stderr}"
    );
    assert!(
        !run_stderr.contains("this is a compiler bug"),
        "must not reach the codegen ICE path: {run_stderr}"
    );
}

/// The same shape at `Int` -- kept as the record of why the original defect
/// went unmeasured. `Future<Int>` and the body's actual `Int` both map to
/// `MirTy::I64`/a general-purpose register on x86-64 (unlike `Float`,
/// `MirTy::F64`), so the return-class mismatch was invisible to Cranelift's
/// verifier: this exact program ran to completion silently even while it was
/// miscompiled. It stays in the suite as the reason this branch mandates
/// instantiating at `Float`, not `Int`, for anything tied to register class.
#[test]
fn run_accepts_an_await_free_async_fn_at_int() {
    let dir = std::env::temp_dir().join("nova-async-no-await-int");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("int_no_await.nova");
    std::fs::write(
        &file,
        "async fn f() -> Int { 1 }\n\
         fn main() { let x = f()\n  println(\"done\") }\n",
    )
    .expect("write test file");

    nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("done\n");
}

/// An `async fn` whose body contains `.await` now COMPILES and RUNS -- Phase
/// 2.3a Task 6 replaced the last `.await`-shaped `E0088` rejection with the
/// resumable transform. Both commands are asserted because `nova check` runs the
/// same lowering stage and used to reject here too.
///
/// **What this does and does not prove.** It proves a body with a suspend point
/// in it survives the whole pipeline into machine code that links and runs: the
/// resume dispatch, the indirect poll of the inner future and the trap arms are
/// all real instructions Cranelift accepted. It does NOT prove `g`'s body ran,
/// for the same reason the await-free case above does not -- nothing in Nova can
/// poll a future until Task 7's `std/task`, so `g()`'s future here is built and
/// dropped. `nova-driver`'s `async_end_to_end` module is where a suspend and a
/// resume are actually executed and the awaited `Float` checked.
///
/// At `Float`: `mir_ty` collapses `Int` onto the same class as every pointer, so
/// an awaited value moved through the wrong one of them is invisible at `Int`.
#[test]
fn run_and_check_accept_and_run_an_async_fn_containing_await() {
    let dir = std::env::temp_dir().join("nova-async-with-await");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("with_await.nova");
    std::fs::write(
        &file,
        "async fn f() -> Float { 1.5 }\n\
         async fn g() -> Float { f().await }\n\
         fn main() { let x = g()\n  println(\"done\") }\n",
    )
    .expect("write test file");

    nova().arg("check").arg(&file).assert().success();

    let run_assert = nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("done\n");
    let run_stderr = String::from_utf8_lossy(&run_assert.get_output().stderr).to_string();
    assert!(
        !run_stderr.contains("E0088"),
        "an `async fn` containing `.await` must no longer be rejected: {run_stderr}"
    );
    assert!(
        !run_stderr.contains("internal codegen error"),
        "must not reach the codegen ICE path: {run_stderr}"
    );
    assert!(
        !run_stderr.contains("this is a compiler bug"),
        "must not reach the codegen ICE path: {run_stderr}"
    );
}

/// An `.await` in a loop, end to end through the CLI: the same suspend point
/// resumed on every iteration, and a back edge into a block the split
/// renumbered. A back edge left pointing at its pre-split id reaches the
/// resumable poll function's trap block, so this exits abnormally rather than
/// printing -- which asserting on stdout catches and `.success()` alone might
/// not, since a trap's exit status is platform-shaped.
#[test]
fn run_accepts_an_await_inside_a_loop() {
    let dir = std::env::temp_dir().join("nova-async-await-loop");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("await_loop.nova");
    std::fs::write(
        &file,
        "async fn one() -> Float { 1.0 }\n\
         async fn total(n: Int) -> Float {\n\
        \x20 let mut i = 0\n\
        \x20 let mut t = 0.0\n\
        \x20 while i < n { t = t + one().await\n i = i + 1 }\n\
        \x20 t\n\
         }\n\
         fn main() { let x = total(3)\n  println(\"done\") }\n",
    )
    .expect("write test file");

    nova().arg("check").arg(&file).assert().success();
    nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("done\n");
}

/// An `async fn main` runs, and runs its whole body.
///
/// The failure this asserts against is not a diagnostic but silence: the
/// transform gives the future-building wrapper the symbol its callers were
/// compiled against, and a wrapper allocates a state object and returns without
/// polling it, so an entry point left named that way exits 0 with empty stdout
/// and no diagnostic anywhere. Asserting the *stdout*, not just the exit code,
/// is what distinguishes "drove the future" from "built one and dropped it" --
/// and the `.await` in the body means the shim also has to survive a suspension
/// rather than only a body that happens to finish on its first poll.
#[test]
fn run_drives_an_async_main() {
    let dir = std::env::temp_dir().join("nova-async-main");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("async_main.nova");
    std::fs::write(
        &file,
        "async fn step(n: Int) -> Int {\n\
         \x20 yield_now().await\n\
         \x20 n + 1\n\
         }\n\
         async fn main() {\n\
         \x20 println(\"start\")\n\
         \x20 println(\"got ${step(41).await}\")\n\
         }\n",
    )
    .expect("write test file");

    nova().arg("check").arg(&file).assert().success();
    nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("start\ngot 42\n");
}

/// The `std/task` gate fixture: two tasks spawned, joined, and interleaved by
/// the executor, plus a `Float` result.
///
/// The order the counters' lines appear in belongs to the executor's queue
/// discipline (round-robin, `nova-runtime`'s `task.rs`), not to this test: the
/// `.stdout` fixture is **regenerated by running the program**, never reasoned
/// out and written by hand. The interleaving rather than the totals is what it
/// exists to pin -- a run-to-completion scheduler would produce the same
/// `total 6` with all of `a`'s lines before all of `b`'s.
///
/// The `Float` line is not decoration. `mir_ty` collapses `Int`, `Char` and
/// every pointer-like type onto one 64-bit integer class, so an `Int`-only
/// fixture cannot tell a value that travelled in its own machine class from one
/// reinterpreted out of the executor's `i64` -- `F64` is the only class that
/// crosses register banks, and `half 3.5` is what fails if `block_on`'s result
/// comes back as raw bits.
#[test]
fn gate_async_tasks_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/async_tasks.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/async_tasks.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through `nova build`, i.e. a standalone linked executable
/// rather than the JIT: object emission, the real linker, and a process whose
/// entry point is the compiled program rather than the compiler.
///
/// **This does not cross a backend boundary.** `build_and_run` invokes
/// `nova build` with no `--release`, and `--release` is what selects the LLVM
/// backend (`cmd/run.rs`'s `BuildCmd`); without it `nova build` uses the same
/// Cranelift backend `nova run` JITs with. So the state object's layout and the
/// poll ABI — which `nova-mir` and `nova-runtime` declare independently and both
/// backends reproduce — are exercised here from the Cranelift side only. **No
/// test executes async machine code emitted by LLVM**; that backend's async
/// coverage is IR-string assertions, with no run. Adding the release-backend
/// async run is follow-up work, deliberately not done in the fix wave that
/// corrected this comment.
#[test]
fn gate_async_tasks_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/async_tasks.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/async_tasks.nova", "async_tasks");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// The same fixture again with `NOVA_GC_STRESS=1` (collect on every
/// allocation) — the established third member of every gate trio.
///
/// **What this proves:** no premature free anywhere in a live async chain while
/// the collector runs at every allocation, end to end on generated code. The
/// fixture yields inside both spawned tasks, so state objects, their spilled
/// temps and their heap-valued contents all survive across real suspensions and
/// real collections, and the program still produces its exact expected output.
///
/// **What it does not prove: that the `PINNED` registry is honoured.** That
/// would need a suspended state object reachable from *nothing but* the
/// registry, and no state object in this fixture is. `nova_rt_task_block_on`
/// holds the root future's fat pointer as a live parameter for the whole drive,
/// so a conservative stack scan finds it; word 1 of it is the root state, whose
/// temp slots hold both `JoinHandle` records, each holding a `fut` whose word 1
/// is a spawned state. Every state in the chain therefore has a traced path from
/// the stack independent of the registry. The `#[ignore]`d collection tests
/// (ADR 0010) and not this configuration are the coverage of `PINNED` being
/// honoured, which is what `.github/workflows/ci.yml` and ADR 0010 already say.
/// The registry being *populated* is covered ungated, by `nova-runtime`'s
/// `gc::root_count` assertions.
#[test]
fn gate_async_tasks_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/async_tasks.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/async_tasks.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Interpolations of three to eight parts, across every interpolable part
/// type, an empty string, non-ASCII text, a user `Display` type, parts with
/// side effects, a loop, and an `.await` inside a part. A guard: it must pass
/// before and after interpolation is lowered to one n-ary concatenation,
/// because that change must not alter any output by a byte.
#[test]
fn interpolation_nary_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/interpolation_nary.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/interpolation_nary.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture with `NOVA_GC_STRESS=1` (collect on every allocation), so
/// a part or the parts array freed before the concatenation reads it shows up
/// as wrong output or a crash. It discriminates only where the collector frees
/// memory: wherever `gc::stack_base` has an implementation (ADR 0024).
#[test]
fn interpolation_nary_under_gc_stress() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/interpolation_nary.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/interpolation_nary.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Spawned tasks' `String` outputs survive the executor releasing each task's
/// GC root at completion, under `NOVA_GC_STRESS=1` (collect on every
/// allocation), including a spawned task that spawns and joins its own child.
///
/// **What this guards:** that a completed spawned task's state stays
/// reachable through its handle across the gap between release-at-completion
/// and `join`, which this fixture fills with collections. If the handle ever
/// stopped reaching the state, that gap is where the string would be freed,
/// and this would print garbage or crash.
///
/// **Its power is not shown by a mutation.** None run on this branch is
/// caught by this test alone. A `join` that went back to taking the executor's
/// output copy would not free anything here: it would panic, deterministically
/// and on every platform, which
/// `taking_a_spawned_tasks_output_after_completion_panics_naming_the_release`
/// (`nova-runtime`) pins.
///
/// **What it does not prove: soundness.** It discriminates only where the
/// collector frees memory, which is wherever `gc::stack_base` has an
/// implementation (ADR 0024). Even there, conservative over-retention can let it pass with
/// the rooting wrong, for the reason `gate_async_tasks_under_gc_stress`
/// documents. The release itself is pinned deterministically on every
/// platform by `nova-runtime`'s `a_spawned_tasks_root_is_released_at_completion`.
#[test]
fn a_spawned_tasks_string_output_survives_release_at_completion() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/spawned_output_survives_release.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/spawned_output_survives_release.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `sleep(ms)`, the first primitive that parks rather than spins, proved by
/// wake *order* rather than by elapsed time.
///
/// `slow` is spawned before `quick`, so spawn order alone would print `slow`
/// then `quick`. The fixture's expected output is the reverse: only a
/// scheduler that actually honours each task's deadline (Task 1's park set,
/// driven here through `sleep`'s `Wait::Deadline`) wakes `quick` first. A
/// broken implementation that ignores the deadline and simply re-queues a
/// parked task -- indistinguishable from `yield_now` -- produces `slow` then
/// `quick`, which is exactly the mutation
/// `crates/nova-runtime/src/task.rs`'s `run_to_completion` was hand-mutated to
/// produce while verifying this fixture (see the task 2 report). No duration
/// is asserted anywhere, only the two lines' order, per this suite's
/// standing rule against timing-flaky assertions.
#[test]
fn gate_task_sleep_order_runs() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/task_sleep_order.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/task_sleep_order.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Phase 2 gate 2.3: a concurrent producer/consumer over a bounded channel,
/// with timers, producing deterministic output.
///
/// Only the consumer prints, and that is what makes the output deterministic
/// while a timer is genuinely in play: the channel is FIFO, so the order of
/// the `got` lines is fixed by the order of sends however the two tasks
/// interleave, and the `sleep` changes only *when* each value moves. No
/// duration is asserted anywhere, per this suite's standing rule against
/// timing-flaky assertions -- the same rule `gate_task_sleep_order_runs`
/// above follows. The sleep demonstrates that channels and timers compose;
/// it is not what the assertion rests on.
///
/// Capacity 2 against 5 sends is deliberate: the producer fills the buffer
/// and blocks in `send` twice, so this covers the bounded path rather than
/// the case where a channel never fills. `tx.close()` is what ends the
/// consumer loop, since `recv` yields `None` only once the channel is closed
/// *and* drained -- without it the consumer waits forever.
#[test]
fn gate_producer_consumer_channel_runs() {
    nova()
        .arg("run")
        .arg(repo_root().join("examples/03-producer-consumer/src/main.nova"))
        .assert()
        .success()
        .stdout("got 1\ngot 2\ngot 3\ngot 4\ngot 5\ndone\n");
}

/// `block_on` called from inside an `async fn` ends the process with a
/// diagnostic, rather than unwinding out of the runtime through a generated
/// frame.
///
/// The whole async transform rests on no unwind crossing a poll function's
/// boundary: a Cranelift- or LLVM-emitted frame has no landing pads, no drop
/// glue and no unwind description, so an unwinder handed one has nothing to work
/// from. `std/task`'s `block_on` is the first thing that made a *runtime*
/// re-entrancy check reachable from compiled Nova code, which is why that check
/// aborts (`nova_rt_task_block_on`) instead of panicking. This is the test that
/// the reachable path really is the aborting one -- it is the only place the
/// abort is observable, since a `catch_unwind` cannot see one.
#[test]
fn run_aborts_when_an_async_fn_calls_block_on() {
    let dir = std::env::temp_dir().join("nova-nested-block-on");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("nested_block_on.nova");
    std::fs::write(
        &file,
        "async fn inner() -> Int { 1 }\n\
         async fn outer() -> Int { block_on(inner()) }\n\
         fn main() { println(\"total ${block_on(outer())}\") }\n",
    )
    .expect("write test file");

    // Accepted by every static stage: the hazard is a run-time property of the
    // executor, and nothing in the language forbids the call.
    nova().arg("check").arg(&file).assert().success();
    let assert = nova().arg("run").arg(&file).assert().failure().stdout("");
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("re-entrantly"),
        "the abort must say what was violated: {stderr}"
    );
    // The exit code and the message alone do not distinguish an abort from a
    // panic -- a panic unwinding out of the runtime also exits nonzero and also
    // prints this text. The `nova: panic:` prefix is the runtime's own abort
    // path (`abort_with`, the same prefix `nova_rt_panic_str` uses), and Rust's
    // panic handler's `panicked at` is what appears instead if the diagnostic
    // is ever turned back into a `panic!`. Both halves are needed: the first
    // alone passes for a panic whose payload happens to contain the prefix.
    assert!(
        stderr.contains("nova: panic:"),
        "the diagnostic must come from the runtime's abort path: {stderr}"
    );
    assert!(
        !stderr.contains("panicked at"),
        "the diagnostic must not unwind: an unwind here would have to pass \
         through a generated poll frame, which has no unwind description at \
         all: {stderr}"
    );
}

/// The headline case of `2026-08-08-joinhandle-task-identity`: the review's
/// exact forged-handle program, which used to pass `nova check` and then
/// hang forever with empty stdout and stderr (see ADR 0009). `JoinHandle`'s
/// field is public, so nothing stops building one directly
/// with a future that was never handed to `spawn` -- see the fixture's own
/// doc comment for why that used to name `block_on`'s own root task rather
/// than aborting.
///
/// Keyed on the future's own state address instead of a forgeable `Int` id,
/// there is no task left to misresolve to, so this must now abort with a
/// diagnostic instead of hanging -- asserted on the message, not merely on
/// failure, and the test completing at all is itself the proof it no longer
/// hangs.
///
/// The message names `nova_rt_task_join_future`, not `nova_rt_task_is_done`:
/// Task 3 rewrote `join` to call `task_join_future(self.fut).await` as its
/// first statement, so that is the first thing to resolve `self.fut` through
/// `task_id_of` and the first thing this program's forged handle can reach.
/// The contract violated is identical either way (`task_id_of`'s own "this
/// future was never spawned" message), only the caller's name changes.
#[test]
fn forged_join_handle_aborts_instead_of_hanging() {
    let file = repo_root().join("tests/runtime/forged_join_handle.nova");

    // Accepted by every static stage: the hazard is a run-time property of
    // the executor, and nothing in the language forbids constructing a
    // `JoinHandle` directly -- record fields are public (ADR 0007).
    nova().arg("check").arg(&file).assert().success();
    let assert = nova().arg("run").arg(&file).assert().failure().stdout("");
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains(
            "nova_rt_task_join_future: this future was never spawned, so there is no task to ask about"
        ),
        "the abort must name the unspawned-future contract it violated: {stderr}"
    );
    assert!(
        stderr.contains("nova: panic:"),
        "the diagnostic must come from the runtime's abort path: {stderr}"
    );
    assert!(
        !stderr.contains("panicked at"),
        "the diagnostic must not unwind -- an unwind here would have to pass \
         through a generated poll frame, which has no unwind description at \
         all: {stderr}"
    );
}

/// The forged handle again, on the case the state-address lookup did not close
/// on its own: a never-spawned future whose fresh state object lands on the
/// address of one the collector has already freed.
///
/// `forged_join_handle_aborts_instead_of_hanging` above cannot reach this. Its
/// program allocates almost nothing, so no collection happens, no address is
/// recycled, and the lookup misses for the ordinary reason. This fixture spawns
/// and joins a run of short tasks first, keeping none of them, so the map holds
/// entries whose state objects have since been freed, and only then builds the
/// forged handle -- see the fixture for why each part of that shape is
/// load-bearing. It aborts iff a freed state's entry went with it.
///
/// `NOVA_GC_STRESS=1` is what makes this discriminate at all (collect on every
/// allocation), and it discriminates only where the collector runs -- see the
/// fixture's own comment, and `nova-runtime`'s
/// `a_swept_states_key_is_dropped_so_a_recycled_address_cannot_misresolve` for
/// the same property asserted deterministically and on every platform.
///
/// `.stdout("")` is half the assertion, not tidiness: the fixture prints only
/// on the path where the join returned a value instead of aborting, so a
/// misresolution shows up as stdout content and not merely as a missing
/// diagnostic.
///
/// The message names `nova_rt_task_join_future`, not `nova_rt_task_is_done`,
/// for the same reason `forged_join_handle_aborts_instead_of_hanging`'s does:
/// Task 3's `join` resolves `self.fut` through `task_join_future` first.
#[test]
fn a_recycled_state_address_does_not_resolve_a_never_spawned_future() {
    let file = repo_root().join("tests/runtime/recycled_task_state.nova");

    nova().arg("check").arg(&file).assert().success();
    let assert = nova()
        .arg("run")
        .arg(&file)
        .env("NOVA_GC_STRESS", "1")
        .assert()
        .failure()
        .stdout("");
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains(
            "nova_rt_task_join_future: this future was never spawned, so there is no task to ask about"
        ),
        "a future the executor never saw must be rejected however its state \
         address was obtained: {stderr}"
    );
    assert!(
        stderr.contains("nova: panic:"),
        "the diagnostic must come from the runtime's abort path: {stderr}"
    );
    assert!(
        !stderr.contains("panicked at"),
        "the diagnostic must not unwind -- an unwind here would have to pass \
         through a generated poll frame, which has no unwind description at \
         all: {stderr}"
    );
}

/// The centrepiece of `2026-08-10-park-set` Task 3: two tasks that join each
/// other is what makes the deadlock diagnostic reachable from Nova source at
/// all. With the old spinning `join`, both tasks would re-check
/// `task_is_done` and `yield_now().await` forever, so the ready queue would
/// never empty and `run_to_completion` could never reach its deadlock arm --
/// a hang, not a diagnostic. Only a parking `join` lets both sides actually
/// leave the ready queue once each has staged its `Wait::Task`, which is
/// what lets the queue drain for real and the executor's exact (non-
/// heuristic) deadlock check fire. So this test passing -- completing at
/// all, with the right diagnostic -- is itself the proof that `join` parks.
///
/// The fixture's own header explains why this is a two-task mutual-join
/// cycle rather than "join a task that spins forever via `yield_now`": the
/// latter is a livelock indistinguishable from legitimate slow progress by
/// any sound check, and was confirmed by hand to hang regardless of whether
/// `join` spins or parks -- see task-3-report.md. See the fixture's own
/// header for why a regression here shows up as a hang rather than a failed
/// assertion.
#[test]
fn task_deadlock_reports_and_aborts_instead_of_hanging_forever() {
    let file = repo_root().join("tests/runtime/task_deadlock.nova");

    // Accepted by every static stage: the deadlock is a run-time property of
    // the executor's park set, and nothing in the language forbids joining a
    // task that never finishes.
    nova().arg("check").arg(&file).assert().success();
    let assert = nova().arg("run").arg(&file).assert().failure().stdout("");
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: deadlock:"),
        "the diagnostic must be the deadlock report, not a different abort: {stderr}"
    );
    assert!(
        stderr.contains("is waiting for task"),
        "the report must name what the parked task is waiting for: {stderr}"
    );
}

/// Pins reachability semantics end-to-end (mirrors
/// `nova-mir`'s `unreached_async_fn_compiles_cleanly`, one layer up): an
/// `async fn` that is declared but never called from `main` must still run
/// cleanly. Guards against an over-broad fix that rejects every `is_async`
/// function in the module regardless of whether `main` ever reaches it.
#[test]
fn run_succeeds_when_async_fn_is_never_called() {
    let dir = std::env::temp_dir().join("nova-async-unreached");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("unreached.nova");
    std::fs::write(
        &file,
        "async fn f() -> Float { 1.5 }\nfn main() { println(\"fine\") }\n",
    )
    .expect("write test file");
    nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("fine\n");
}

// === nova build: standalone executables ===

/// Build `source` to a standalone executable named `exe_name`, run it, and
/// return its stdout.
///
/// **The directory carries this process's id.** The 26 `exe_name`s are unique
/// *within* this binary, so there was never an intra-run collision — but
/// without a per-process component every `run_tests` invocation on the machine
/// wrote, executed and then deleted the *same absolute paths*. Two runs
/// overlapping at all (two checkouts, a worktree, a developer alongside CI, two
/// `cargo test` invocations) had one process deleting or overwriting an image
/// another was executing. That is a named candidate mechanism for this
/// binary's known flake, which hits a different test name each run and always
/// passes in isolation: one such failure was observed as exit code
/// `0xC0000005` (ACCESS_VIOLATION) with *empty* stdout and stderr, which is
/// what running a half-written or swapped-out image looks like and not what a
/// Nova-level bug looks like. It also broke this branch's own constraint that
/// every fixture path be unique per process — these were unique only per
/// machine. Not a proven diagnosis: Windows Defender scanning a freshly
/// written `.exe` explains the same symptom equally well, and a genuine
/// intermittent codegen bug is not excluded. It is cheap to eliminate, and
/// eliminating it either fixes the flake or narrows it.
///
/// **The per-test `remove_file` stays, and the directory itself is never
/// removed -- not recursively, and not even best-effort.** All 26 `exe_name`s
/// share this one directory inside a single process, and these tests run on
/// parallel threads. A per-test `remove_dir_all` would have tests deleting each
/// other's executables mid-execution, manufacturing the exact flake this change
/// exists to remove.
///
/// A best-effort *non*-recursive `remove_dir` looks safe by comparison: it can
/// only succeed when the directory is already empty, so it can never delete a
/// sibling's executable. **MEASURED: it is not safe.** A full-workspace run with
/// one added here failed three `*_build_standalone` tests at once, each with
/// `failed to write ...\<name>.exe.nova.obj: The system cannot find the path
/// specified. (os error 3)`. One test's `remove_dir` won a race against a
/// sibling that had already passed `create_dir_all` and was about to write into
/// the directory. Emptiness is not the invariant that matters; "no sibling is
/// between `create_dir_all` and `nova build`" is, and nothing available here can
/// establish it. So the directory is left behind: one empty per-process
/// directory in the system temp folder is a far cheaper residue than a
/// self-inflicted parallel-execution flake.
fn build_and_run(source: &str, exe_name: &str) -> String {
    let dir = std::env::temp_dir().join(format!("nova-build-tests-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("temp dir");
    let exe = dir.join(format!("{exe_name}{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(repo_root().join(source))
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let out = Command::new(&exe)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let _ = std::fs::remove_file(&exe);
    String::from_utf8(out).expect("program output is UTF-8")
}

/// The live-object count of every collection in a `NOVA_GC_DEBUG` log, in
/// order. Each collection logs
/// `nova-gc: collection C freed F bytes, L objects live (B bytes)`, and this
/// returns the `L`s.
fn gc_live_object_counts(stderr: &str) -> Vec<u64> {
    stderr
        .lines()
        .filter(|line| line.starts_with("nova-gc: collection"))
        .filter_map(|line| {
            let rest = &line[line.find(" bytes, ")? + " bytes, ".len()..];
            rest.split(' ').next()?.parse().ok()
        })
        .collect()
}

/// The GC reclaims garbage: a loop allocating far more than the heap threshold
/// keeps a bounded live set (rather than accumulating, as the old leaking
/// allocator did). Verified through the `NOVA_GC_DEBUG` collection log.
/// It runs wherever `gc::stack_base` has an implementation, which includes
/// every CI operating system (`docs/adr/0024-gc-stack-bounds-on-unix.md`).
#[test]
fn gc_reclaims_garbage() {
    let dir = std::env::temp_dir().join("nova-gc-reclaim");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("garbage.nova");
    std::fs::write(
        &file,
        "record Node { v: Int }\n\
         fn main() {\n\
             let mut i = 0\n\
             while i < 300000 {\n\
                 let n = Node { v: i }\n\
                 i = i + 1\n\
             }\n\
             println(\"done ${i}\")\n\
         }",
    )
    .expect("write");
    let assert = nova()
        .arg("run")
        .arg(&file)
        .env("NOVA_GC_DEBUG", "1")
        .assert()
        .success()
        .stdout("done 300000\n");
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova-gc: collection"),
        "expected at least one collection: {stderr}"
    );
    // The live object count reported by every collection must stay small —
    // proof that garbage is reclaimed rather than accumulated.
    let max_live = gc_live_object_counts(&stderr)
        .into_iter()
        .max()
        .unwrap_or(0);
    assert!(
        max_live > 0 && max_live < 1000,
        "live set should stay bounded, saw {max_live} live objects:\n{stderr}"
    );
}

/// `nova build --release` with no LLVM toolchain must fail cleanly and leave
/// the generated IR behind (forcing the no-toolchain path deterministically by
/// pointing `NOVA_CLANG`/`NOVA_LLC` at a nonexistent program).
#[test]
fn release_without_toolchain_emits_ir_and_errors() {
    let dir = std::env::temp_dir().join("nova-release-notool");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let exe = dir.join(format!("hello{}", std::env::consts::EXE_SUFFIX));
    // The intermediate IR is named `<output filename>.nova.ll` so it can never
    // alias the output path.
    let ll = exe.with_file_name(format!(
        "{}.nova.ll",
        exe.file_name().unwrap().to_string_lossy()
    ));
    let _ = std::fs::remove_file(&ll);
    let assert = nova()
        .arg("build")
        .arg("--release")
        .arg(repo_root().join("examples/01-hello-world/src/main.nova"))
        .arg("-o")
        .arg(&exe)
        .env("NOVA_CLANG", "nova_no_such_tool_xyz")
        .env("NOVA_LLC", "nova_no_such_tool_xyz")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("LLVM toolchain"), "stderr: {stderr}");
    // The IR is left for the user to compile / inspect.
    assert!(ll.exists(), "expected generated IR at {}", ll.display());
    let ir = std::fs::read_to_string(&ll).expect("read ir");
    assert!(ir.contains("define i32 @main"), "ir:\n{ir}");
    let _ = std::fs::remove_file(&ll);
}

/// Regression: intermediate files must never alias the output path, even when
/// `-o` itself ends in `.ll` (which would otherwise make the IR intermediate
/// the output file and later delete the built binary).
#[test]
fn release_intermediate_never_aliases_output() {
    let dir = std::env::temp_dir().join("nova-release-alias");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let out = dir.join("prog.ll"); // output deliberately named `.ll`
    let ir = dir.join("prog.ll.nova.ll"); // the non-aliasing intermediate
    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&ir);
    nova()
        .arg("build")
        .arg("--release")
        .arg(repo_root().join("examples/01-hello-world/src/main.nova"))
        .arg("-o")
        .arg(&out)
        .env("NOVA_CLANG", "nova_no_such_tool_xyz")
        .env("NOVA_LLC", "nova_no_such_tool_xyz")
        .assert()
        .failure();
    // The IR went to the distinct intermediate, not to the output path.
    assert!(ir.exists(), "expected IR at {}", ir.display());
    let _ = std::fs::remove_file(&ir);
    let _ = std::fs::remove_file(&out);
}

/// When a real LLVM toolchain is available, `--release` builds and runs an
/// optimized binary with identical output to the debug build. Skipped where
/// no `clang` is installed.
#[test]
fn release_builds_and_runs_when_clang_available() {
    let clang_ok = std::process::Command::new("clang")
        .arg("--version")
        .output()
        .is_ok();
    if !clang_ok {
        eprintln!("skipping: no clang on PATH");
        return;
    }
    let dir = std::env::temp_dir().join("nova-release-run");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let exe = dir.join(format!("hello_rel{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg("--release")
        .arg(repo_root().join("examples/01-hello-world/src/main.nova"))
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let out = Command::new(&exe)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    assert_eq!(String::from_utf8(out).expect("utf8"), "Hello, World!\n");
    let _ = std::fs::remove_file(&exe);
}

#[test]
fn build_hello_world_standalone() {
    let out = build_and_run("examples/01-hello-world/src/main.nova", "hello");
    assert_eq!(out, "Hello, World!\n");
}

#[test]
fn build_match_enum_standalone() {
    let out = build_and_run("tests/runtime/match_enum.nova", "match_enum");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/match_enum.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

#[test]
fn build_generics_standalone() {
    let out = build_and_run("tests/runtime/generics.nova", "generics");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/generics.stdout"))
        .expect("fixture")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

/// `std/core` end-to-end gate (Phase 2.1, Task 10): `Option`/`Result`'s full
/// method sets, a custom `Display` (direct, through a `T: Display` bound, and
/// via interpolation), `Debug`, `Eq`/`ne`, `Ord` for every primitive that has
/// it (including the non-uniform `Bool` and `String` impls), `Clone`, and
/// `Default` (including `Default for Char`) — round-tripped under `nova run`.
#[test]
fn std_core_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/std_core.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/std_core.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Same fixture, compiled to a standalone executable (Cranelift object
/// backend) rather than JIT-run — the other of the two backends this task's
/// gate must cover.
#[test]
fn std_core_build_standalone() {
    let out = build_and_run("tests/runtime/std_core.nova", "std_core");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/std_core.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    assert_eq!(out, expected);
}

/// Same fixture again, this time with `NOVA_GC_STRESS=1` (collect on every
/// allocation) — the established convention for proving root-scanning stays
/// correct under heavy `std/core` generic/trait allocation traffic.
#[test]
fn std_core_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/std_core.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/std_core.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `Hash` end-to-end (Phase 2.2a Task 6, ADR 0005 §2). Run rather than merely
/// type-checked because the payoffs are all runtime ones: the mixer's large
/// two's-complement constants must actually wrap rather than trap, the
/// `char_to_int` builtin lowers to a register move that no type could catch
/// being wrong, and the **low** bits of an `Int` hash must be spread because
/// `Map` will select buckets with `hash & (cap - 1)`.
///
/// `Int`, `Bool` and `Char` hashing is seeded per process, so each `Int`, `Bool`
/// or `Char` line in the fixture is either seed-invariant by construction or a
/// bound whose false-failure probability is derived rather than sampled — the
/// dichotomy `hash.nova`'s own header states, and the reason not to call the
/// whole golden seed-invariant. The two `String` lines are a third case, not
/// covered by that pair: they go through `nova_rt_str_hash`'s own seed, and
/// seeded FNV-1a followed by a finalizer is not injective, so their `diff=true`
/// halves are seed-dependent at a magnitude around 2^-64. What the fixture
/// prints is relations between hashes drawn under one seed, the derived bounds,
/// the complement theorems, and `mix64`'s published canonical vectors reached by
/// recovering the seed and cancelling it. Every derivation is in the fixture's
/// header, each bound's probability with it.
///
/// An earlier version of this paragraph read "The expected bucket histograms in
/// the fixture were computed independently from splitmix64's finalizer, so they
/// are an oracle rather than a recording of whatever the implementation happened
/// to print." Those histograms are gone — the seed randomises the exact counts
/// they pinned — but the oracle property is not, and that is the half worth
/// keeping. The bounds are computed from distributions rather than read off a
/// run — occupancy for the `keys -64..63 reach` and `buckets reached` lines, the
/// binomial for the negative-hash count — the two complement lines are
/// theorems about `mix64` being injective, and the canonical vectors are
/// published splitmix64 values. What changed is that a bound admits a range
/// where a histogram admitted one value, so a mutant can land inside one; the
/// fixture's scope note says which.
///
/// The fixture also carries the complement-pair regression. Because Nova's
/// `>>` is arithmetic, an unmasked `x ^ (x >> k)` yields the same value for
/// `x` and `-1 - x`, which made `mix64` fold 2-to-1 with *identical* hashes —
/// pairs that share a bucket at every capacity, so no resize separates them.
/// Seeding does not rescue that, because XOR with a constant commutes with
/// complement too. A single-sign sample looks textbook-uniform through it,
/// which is exactly why `h(0) != h(-1)`, the complement count and the
/// both-signs bucket bound are all in there.
#[test]
fn hash_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/hash.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/hash.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through the object-file backend: every assertion in it must
/// hold whichever backend compiled it, or the two are computing different hash
/// arithmetic.
///
/// This comment used to read "a hash must not depend on which backend compiled
/// it, or a `Map` built by one and read by the other would disagree about
/// buckets". That justification no longer holds: `Int` hashing is seeded per
/// process, so two processes disagree about buckets whatever compiled them, and
/// this test runs in a different process from `hash_run` regardless.
///
/// What the comparison still catches is a backend that mixes differently, and
/// what catches it is recorded PER MASK rather than as a claim about "the
/// bounds". Two earlier versions of this sentence quantified over that group and
/// both were false: first "the two bounds sit far from what a broken mixer
/// produces", then "the bounds are not part of that argument". The second was
/// generalised from mask 2, which is the one mask the bounds are blind to. The
/// roster that replaced them was in turn incomplete — it credited mask 1 to the
/// canonical vectors and the `keys -64..63` bound and named the complement count
/// only to say mask 2 was blind to it, which drops a credit the first of those
/// two sentences had actually made.
///
/// Measured by dropping each of `mix64`'s three shift masks in turn and running
/// the fixture in 30 separate processes per mask, 90 runs in all:
///
/// - The canonical vectors catch all three masks, in every run. The line never
///   printed `x1=true x3=true` under any mask. Which half reads false does vary
///   with the seed, because a mutated `mix64` breaks `mix64_inv`'s seed recovery
///   for some seeds and not others — so the line's verdict is stable while its
///   text is not.
/// - The two complement lines — `complement collisions over 0..63` and
///   `h(0) != h(-1)` — catch mask 1, 30 of 30, and they are mask 1's strongest
///   pin because they are theorems rather than measurements. Arithmetic shift
///   commutes with complement and `(!k) ^ s == !(k ^ s)`, so an unmasked stage 1
///   is exactly 2-to-1 under `x <-> -1-x` and every later stage is a function of
///   it: the count reads 64 against a golden of 0, and `h(0) != h(-1)` reads
///   false, at every seed rather than at almost every seed. `hash.nova`'s scope
///   note says the same thing from the fixture's side.
/// - The `keys -64..63 reach` bound also catches mask 1, 30 of 30, by the same
///   algebra: that key set is closed under `k -> -1-k`, so an unmasked stage 1
///   leaves at most 64 distinct hashes over its 128 keys, below the bound at
///   every seed.
/// - The negative-count bound also catches mask 3, 30 of 30. An unmasked final
///   shift XORs the sign bit with its own copy, so every hash is non-negative
///   and the count is 0, below the range at every seed.
/// - The `buckets reached` bound catches none of the three. Mask 2 is invisible
///   to every bound in the fixture and to both complement lines, 30 of 30, so it
///   rests on the canonical vectors — which is what `hash.nova`'s scope note
///   says.
#[test]
fn hash_build_standalone() {
    let out = build_and_run("tests/runtime/hash.nova", "hash");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/hash.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// `std/collections` end-to-end gate (Phase 2.2a, Task 9). The behaviour this
/// pins is *runtime* behaviour that no type-level or MIR-level test can reach:
/// probe chains, tombstones and the load-factor arithmetic are all values
/// computed while the program runs.
///
/// What the fixture covers, and why each item is in there rather than left to
/// a throwaway program:
///
/// - **Removal from the middle of a probe chain**, then a successful lookup
///   *past* the hole — including a chain that **wraps** off the end of the
///   table and continues at index 0. This is the single most likely bug in the
///   whole increment and it is invisible without a targeted test: a `remove`
///   that marks the slot empty instead of tombstoned passes every other
///   assertion here while silently losing every key inserted past it.
/// - **Tombstone reuse**: an insert after a removal must land in the freed slot
///   with `used` (occupied *plus* tombstones) unchanged, so a churn workload
///   cannot grow the table without bound.
/// - **A growth driven by tombstones alone**, which is the only thing that
///   tests `used` at all. Everywhere else in the fixture `len == used` at the
///   growth points, so the load threshold would behave identically read off
///   either field. The churn block drives `used` to 6 of 8 while `len` stays at
///   1 — six inserts on six distinct home buckets, five of them removed, so no
///   tombstone is ever on a later probe path and none is reused — and then
///   asserts that the rehash drops `used` back to `len`, leaves no `2` in the
///   state array, keeps both live keys, and **resurrects none of the five
///   removed ones**. A `len`-keyed threshold never fires there and the table
///   fills until `insert` hits the "found no free slot" panic its own comment
///   calls unreachable; a `grow` that reinserted every not-empty slot instead
///   of every occupied one brings all five deleted keys back (a tombstoned slot
///   still holds its old key and value). Both single-token mutations left the
///   pre-churn fixture byte-identical.
/// - **No shadowed duplicate**: re-inserting a key that lives *behind* one or
///   more tombstones replaces it in place — verified by removing it once
///   afterwards and confirming it is then absent, which a second buried copy
///   would fail.
/// - The **load-factor arithmetic** and two rehashes, with the live count and
///   every lookup correct across them. The printed capacity sequence also
///   shows no doubling skips a power of two, which is what re-entrant growth
///   would look like.
/// - A **user record as a `Map` key and a `Set` element**, with its own `Hash`
///   and `Eq` impls — the case that proves a user type can flow through the
///   `K: Hash + Eq` bound at all, where only `Int` and `String` had been used.
/// - `Map<String, Int>` for the runtime hash path (`str_hash` — seeded FNV-1a
///   then splitmix64's finalizer, per-process seed) and
///   **negative `Int` keys**, where `% cap` instead of `& (cap - 1)` would
///   produce a negative bucket index.
/// - `Vec` across three growths (0 → 4 → 8 → 16) with `pop`, `set`, `clear`
///   and `get` both in and out of range, plus `is_empty`'s `false` branch for
///   `Vec`, `Map` and `Set`.
///
/// Nothing in here panics: `panic` aborts the process, which would truncate
/// the remaining output. `Vec::set` out of range and `unwrap` on the wrong
/// variant have their own committed tests.
#[test]
fn collections_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/collections.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/collections.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through the object-file backend. `Map` bucket indices are
/// derived from `Hash`, so a backend that computed a hash differently would
/// build different probe chains — the state-array assertions in the fixture
/// would then diverge here but not under the JIT.
#[test]
fn collections_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/collections.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/collections.nova", "collections");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// The same fixture again with `NOVA_GC_STRESS=1` (collect on every
/// allocation) — the reason this gate exists. `Vec::push` and `Map::grow`
/// allocate a larger buffer and copy into it, and during `grow`'s window the
/// old key/value/state arrays are reachable *only* through its locals while
/// two further allocations happen. That is exactly where a conservative
/// non-moving collector fails if its root scan misses a stack slot, and the
/// symptom would be silent data loss rather than a crash.
#[test]
fn collections_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/collections.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/collections.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A record literal *inside* a `"${…}"` interpolation, end-to-end. The lexer
/// balances a hole's braces, so the literal's `}` no longer terminates the hole
/// (which used to fail with "expected `}` (in record literal), found `}`").
/// Run rather than merely checked because the payoff is that the value is
/// actually constructed and formatted: through interpolation's native
/// primitive conversion, through a `Display` impl, nested one level deeper,
/// and with a hole in a `no_struct_literal` position (an `if` condition).
#[test]
fn record_literal_inside_an_interpolation_runs() {
    let dir = std::env::temp_dir().join("nova-interp-record");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("interp_record.nova");
    std::fs::write(
        &file,
        "record R { v: Int }\n\
         record G { w: R }\n\
         trait Display { fn fmt(self) -> String }\n\
         impl Display for R { fn fmt(self) -> String { \"R(${self.v})\" } }\n\
         fn f(r: R) -> Int { r.v }\n\
         fn main() {\n\
             println(\"${f(R { v: 1 })}\")\n\
             println(\"${R { v: 2 }}\")\n\
             println(\"${G { w: R { v: 3 } }.w.v}\")\n\
             println(\"${if true { R { v: 4 }.v } else { 0 }}\")\n\
             if \"${f(R { v: 5 })}\" == \"5\" { println(\"cond\") }\n\
         }\n",
    )
    .expect("write");
    let expected = "1\nR(2)\n3\n4\ncond\n";
    nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout(expected);

    // Same program through the object-file backend, the other of the two.
    let exe = dir.join(format!("interp_record{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    Command::new(&exe).assert().success().stdout(expected);
    let _ = std::fs::remove_file(&exe);
}

/// An interpolation hole that never closes must be a clean diagnostic naming
/// the unterminated interpolation — not a panic, and not a hang.
#[test]
fn unterminated_interpolation_hole_is_a_clean_error() {
    let dir = std::env::temp_dir().join("nova-interp-unterminated");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("unterminated.nova");
    std::fs::write(
        &file,
        "record R { v: Int }\n\
         fn f(r: R) -> Int { r.v }\n\
         fn main() { println(\"${f(R { v: 1 }\") }\n",
    )
    .expect("write");
    let assert = nova().arg("check").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("unterminated string interpolation"),
        "stderr: {stderr}"
    );
    assert!(!stderr.contains("panicked"), "should not panic: {stderr}");
    assert!(
        !stderr.contains("compiler bug"),
        "not a compiler bug: {stderr}"
    );
}

#[test]
fn panic_aborts_with_message() {
    let assert = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/panic_unwrap.nova"))
        .assert()
        .failure();
    let out = assert.get_output();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stdout.contains('7'), "stdout was {stdout:?}");
    assert!(
        stderr.contains("nova: panic: called get on None"),
        "stderr was {stderr:?}"
    );
    assert!(!stdout.contains("unreachable"), "stdout was {stdout:?}");
}

/// `std/strings` is the third embedded std module (Phase 2.2b). `is_empty` is
/// the one method in it that needs no new intrinsic, so this pins that the
/// module is loaded and its inherent `impl String` resolves — independently of
/// the five intrinsics the rest of the surface needs.
#[test]
fn std_strings_module_is_loaded() {
    let dir = std::env::temp_dir().join("nova-strings-scaffold");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(
        &path,
        "fn main() { println(\"${\"\".is_empty()} ${\"x\".is_empty()}\") }",
    )
    .expect("write test file");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("true false\n");
}

/// `String::len` counts CODEPOINTS, not bytes — the whole point of Phase 2.2b.
/// `café` is 5 UTF-8 bytes but 4 codepoints; each CJK character here is 3
/// bytes. A byte-based implementation prints `5` and `9`.
#[test]
fn string_len_counts_codepoints_not_bytes() {
    let src = "fn main() { println(\"${\"café\".len()} ${\"日本語\".len()} ${\"\".len()}\") }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-len");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("4 3 0\n");
}

/// `str_chars` is the first intrinsic to build a Nova array in the runtime, so
/// it must reproduce codegen's `{ len, elems at 8 + 8*i }` layout exactly. A
/// wrong offset or a wrong length header is a SILENT MISCOMPILE, not a crash —
/// so this reads `.len()` back and indexes elements from Nova, which is the
/// only thing that actually exercises the layout the compiler assumes.
///
/// `char_at`'s whole contract is its two boundaries — `i == 0` (the `i < 0`
/// guard) and `i == len` (the `i >= cs.len()` guard) — so both are exercised
/// directly here, not just interior (`1`) and clearly-out-of-range (`9`, `-1`)
/// indices: `"héllo"` is 5 codepoints, so `char_at(0)` must be `Some('h')` and
/// `char_at(5)` (`== len`) must be `None`, never a bounds-check abort.
#[test]
fn str_chars_array_matches_codegen_layout() {
    let src = "fn main() {\n\
               let cs = \"a→🦀\".chars()\n\
               println(\"${cs.len()} ${cs[0]} ${cs[1]} ${cs[2]}\")\n\
               let e = \"\".chars()\n\
               println(\"${e.len()}\")\n\
               println(\"${\"héllo\".char_at(0).unwrap_or('?')} \
               ${\"héllo\".char_at(1).unwrap_or('?')} \
               ${\"héllo\".char_at(5).unwrap_or('?')} \
               ${\"héllo\".char_at(9).unwrap_or('?')} \
               ${\"héllo\".char_at(0 - 1).unwrap_or('?')}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-chars");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("3 a → 🦀\n0\nh é ? ? ?\n");
}

/// Round-trip and the half-open slice boundary. Per spec §4.2, `slice` is
/// `start` inclusive / `end` exclusive, `start == end` is valid and yields
/// "", and `reverse` reverses codepoints.
///
/// `"héllo wörld".slice(6, 11)` (`"wörld"`) is not decorative: every other
/// `slice` call anywhere in this test uses `start == 0`, so without a
/// nonzero-`start` case, `chars_to_string`'s `cs[start + i]` could regress to
/// `cs[i]` (dropping the offset) and every test here would still pass — see
/// the mutation-testing note in the Task 4 fix report. The multi-byte prefix
/// (`é` inside `"héllo"`, both in the source before offset 6) also proves the
/// offset is counted in codepoints, not bytes: a byte-based offset would land
/// mid-character and either panic or produce garbage.
#[test]
fn str_from_chars_round_trips_and_slice_is_half_open() {
    let src = "fn main() {\n\
               println(\"${\"a→🦀é\".chars().len()}\")\n\
               println(\"${\"héllo wörld\".slice(0, 5)}|${\"héllo\".slice(0, 0)}|\
               ${\"héllo\".slice(5, 5)}|${\"héllo\".slice(0, 5)}|\
               ${\"héllo wörld\".slice(6, 11)}\")\n\
               println(\"${\"a→🦀\".reverse()} ${\"\".reverse()}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-slice");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("4\nhéllo|||héllo|wörld\n🦀→a \n");
}

/// `String::slice`'s first panic: a negative `start`. Modelled on
/// `panic_aborts_with_message` — `panic` aborts the process, so this cannot
/// share a fixture with anything that must keep running afterward.
#[test]
fn string_slice_negative_start_panics() {
    let dir = std::env::temp_dir().join("nova-strings-slice-neg-start");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(
        &path,
        "fn main() { println(\"${\"abc\".slice(0 - 1, 2)}\") }\n",
    )
    .expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: String::slice start is negative"),
        "stderr: {stderr}"
    );
}

/// `String::slice`'s second panic: `end` past the string's length (`"abc"` has
/// 3 codepoints, so `end = 4` is out of range). `start == end` is deliberately
/// NOT tested here — that is the valid empty-slice case covered by
/// `str_from_chars_round_trips_and_slice_is_half_open`.
#[test]
fn string_slice_end_past_len_panics() {
    let dir = std::env::temp_dir().join("nova-strings-slice-end-oob");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, "fn main() { println(\"${\"abc\".slice(0, 4)}\") }\n").expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: String::slice end is past the end of the string"),
        "stderr: {stderr}"
    );
}

/// `String::slice`'s third panic: `start > end` (here `start == end + 1`, one
/// past the boundary where `start == end` would be the valid empty slice).
#[test]
fn string_slice_start_after_end_panics() {
    let dir = std::env::temp_dir().join("nova-strings-slice-start-after-end");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, "fn main() { println(\"${\"abc\".slice(2, 1)}\") }\n").expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: String::slice start is after end"),
        "stderr: {stderr}"
    );
}

/// Search is codepoint-indexed, and an empty needle matches at position 0
/// (spec §4.2). `index_of` on "héllo wörld" must report 6 for "wörld", not a
/// byte offset — a byte-based implementation reports 7.
#[test]
fn string_search_is_codepoint_indexed_and_empty_needle_matches() {
    let src = "fn main() {\n\
               let s = \"héllo wörld\"\n\
               println(\"${s.index_of(\"wörld\").unwrap_or(0 - 1)} \
               ${s.index_of(\"zzz\").unwrap_or(0 - 1)} \
               ${s.index_of(\"\").unwrap_or(0 - 1)}\")\n\
               println(\"${s.starts_with(\"hé\")} ${s.starts_with(\"x\")} \
               ${s.ends_with(\"rld\")} ${s.ends_with(\"x\")}\")\n\
               println(\"${s.contains(\"ö\")} ${s.contains(\"q\")} \
               ${s.contains(\"\")} ${s.starts_with(\"\")} ${s.ends_with(\"\")}\")\n\
               println(\"${\"\".index_of(\"a\").unwrap_or(0 - 1)} \
               ${\"aaa\".index_of(\"aa\").unwrap_or(0 - 1)} \
               ${\"abc\".starts_with(\"abcd\")}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-search");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("6 -1 0\ntrue false true false\ntrue false true true true\n-1 0 false\n");
}

/// Mutation-coverage gap the brief's own test above leaves open (same shape
/// as the Task 3 `char_at` and Task 4 `slice` lessons): every `ends_with` and
/// `index_of` call above compares a haystack STRICTLY LONGER than the needle,
/// so the pre-guards `n.len() > h.len()` (in both `ends_with` and
/// `index_of`) survive being mutated to `>=` — that mutant would wrongly
/// reject the same-length case (`n.len() == h.len()`) as "too long" — because
/// no assertion above ever has `n.len() == h.len()`. `"abc".ends_with("abc")`
/// and `"abc".index_of("abc")` (a full-string, same-length match) close that
/// gap; `"ab".ends_with("abc")` and `"ab".index_of("abc")` (needle strictly
/// LONGER than a nonempty haystack) pin the guard from the other side.
/// `"abcde".index_of("de")` is a plain-ASCII match at the very last valid
/// position (`last == h.len() - n.len() == 3`), independent of the Unicode
/// case above, so it kills both an `at <= last` → `at < last`/`>= last` typo
/// in the search loop's bound and an `at = at + 1` → `at = at + 2` typo in
/// its step (an every-other-position skip would jump straight over index 3
/// and miss the match).
///
/// Since 2026-10-02 `index_of` is a runtime byte search with no such guard,
/// bound or step. Its calls here still pin the same-length and
/// last-position results; the guard described above survives in
/// `ends_with`.
#[test]
fn string_search_same_length_and_last_position_boundaries() {
    let src = "fn main() {\n\
               println(\"${\"abc\".ends_with(\"abc\")} ${\"ab\".ends_with(\"abc\")}\")\n\
               println(\"${\"abc\".index_of(\"abc\").unwrap_or(0 - 1)} \
               ${\"ab\".index_of(\"abc\").unwrap_or(0 - 1)} \
               ${\"abcde\".index_of(\"de\").unwrap_or(0 - 1)}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-search-boundary");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("true false\n0 -1 3\n");
}

/// `split`'s pinned semantics (spec §4.2): a missing separator yields a
/// one-element array and NEVER an empty one; adjacent, leading and trailing
/// separators produce empty strings with no collapsing; and an EMPTY
/// separator splits into single codepoints — the JavaScript behaviour, chosen
/// because Rust adds boundary empties and Python raises, so there is no
/// consensus to inherit. `join` hangs off the separator, not the parts.
#[test]
fn string_split_and_join_match_the_pinned_semantics() {
    let src = "fn main() {\n\
               let a = \"a,b,c\".split(\",\")\n\
               println(\"${a.len()} ${a[0]}${a[1]}${a[2]}\")\n\
               let b = \"abc\".split(\",\")\n\
               println(\"${b.len()} ${b[0]}\")\n\
               let c = \",a,\".split(\",\")\n\
               println(\"${c.len()} [${c[0]}][${c[1]}][${c[2]}]\")\n\
               let d = \"a,,b\".split(\",\")\n\
               println(\"${d.len()} [${d[0]}][${d[1]}][${d[2]}]\")\n\
               let e = \"a→b\".split(\"→\")\n\
               println(\"${e.len()} ${e[0]}${e[1]}\")\n\
               let f = \"abc\".split(\"\")\n\
               println(\"${f.len()} ${f[0]}|${f[1]}|${f[2]}\")\n\
               println(\"${\"\".split(\"\").len()} ${\"\".split(\",\").len()}\")\n\
               let g = \"xx\".split(\"xx\")\n\
               println(\"${g.len()} [${g[0]}][${g[1]}]\")\n\
               println(\"[${\",\".join(a)}] [${\"\".join(f)}] [${\"-\".join([])}]\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-split");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova().arg("run").arg(&path).assert().success().stdout(
        "3 abc\n1 abc\n3 [][a][]\n3 [a][][b]\n2 ab\n3 a|b|c\n0 1\n2 [][]\n\
             [a,b,c] [abc] []\n",
    );
}

/// Mutation-coverage gap the brief's own test above leaves open (same shape
/// as the Task 3/4/5 lessons): every `join` call above uses a separator that
/// is either a single codepoint (`","`) or empty (`""`), and every `split`
/// separator is either one codepoint (`","`/`"→"`) or spans the WHOLE
/// haystack (`"xx"` in `"xx"`). That leaves gaps a one-character mutation
/// could hide in:
///
/// 1. A separator copied wrongly, say by repeating its first character, is
///    invisible with `","` (length 1) or `""` (nothing to copy).
///    `"->".join(["a", "b", "c"])` uses a two-codepoint separator with
///    DIFFERENT characters at each position, so the wrong copy writes
///    `"--"` where the real one writes `"->"`.
/// 2. A one-part special case that returned `""` would be caught by
///    `"-".join([])` only by accident. `",".join(["solo"])` pins it on its
///    own terms: the answer must be `"solo"`, unchanged, with no separator
///    on either side.
///
///    Both items were first written against a Nova-level `join`, with an
///    `out[w] = sep[k]` copy loop and a `parts.len() == 0` guard. Since
///    2026-10-02 the runtime builtin `str_join` does the join, and these
///    calls exercise it instead.
/// 3. `split`'s count/fill arithmetic is only ever exercised with a
///    one-codepoint separator repeated inside a longer haystack, or a
///    multi-codepoint separator spanning the ENTIRE haystack (`"xx"`) with
///    no room for a second match. `"a::b::c".split("::")` is a
///    two-codepoint separator occurring twice INSIDE a seven-codepoint
///    haystack (non-overlapping, neither match at either boundary), a
///    combination none of the brief's cases cover.
/// 4. Every separator tried so far is either non-repeating (`","`, `"→"`,
///    `"::"`) or spans the WHOLE haystack with no room to overlap (`"xx"`
///    in `"xx"`), so the two-pass invariant (pass 1 counts, pass 2 fills,
///    and they MUST walk identically) is only half pinned: a separator
///    that can self-overlap when stepped one codepoint at a time is never
///    tried. Mutating pass 1's step alone — `i = i + s.len()` to
///    `i = i + 1` at `lib.nova:300`, leaving pass 2's `lib.nova:314`
///    untouched — makes pass 1 find every overlapping occurrence of `"aa"`
///    in `"aaaa"` (3, at positions 0/1/2) instead of the 2 correct
///    non-overlapping ones, so `pieces` comes out at 4 instead of 3. Since
///    every piece of `"aaaa".split("aa")` is `""` regardless, content alone
///    cannot catch this — only the LENGTH can, which is why `${u.len()}` is
///    checked explicitly rather than just concatenating pieces.
///    `"ababab".split("abab")` (expect `["", "ab"]`, length 2) adds a case
///    with a nonempty trailing piece after an overlap-capable separator, so
///    the same mutation is pinned by both an all-empty and a
///    not-all-empty result.
/// 5. No test above uses a non-ASCII separator occurring more than once
///    (`"a→b".split("→")` is one occurrence; `"a::b::c".split("::")` occurs
///    twice but is ASCII). `"a→b→c".split("→")` covers both at once.
#[test]
fn string_split_and_join_cover_multi_codepoint_separators_and_one_part_join() {
    let src = "fn main() {\n\
               let s = \"a::b::c\".split(\"::\")\n\
               println(\"${s.len()} ${s[0]}|${s[1]}|${s[2]}\")\n\
               let t = \"a→b→c\".split(\"→\")\n\
               println(\"${t.len()} ${t[0]}|${t[1]}|${t[2]}\")\n\
               let u = \"aaaa\".split(\"aa\")\n\
               println(\"${u.len()} [${u[0]}][${u[1]}][${u[2]}]\")\n\
               let v = \"ababab\".split(\"abab\")\n\
               println(\"${v.len()} [${v[0]}][${v[1]}]\")\n\
               let parts = [\"a\", \"b\", \"c\"]\n\
               println(\"${\"->\".join(parts)}\")\n\
               let one = [\"solo\"]\n\
               println(\"${\",\".join(one)}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-split-join-boundary");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("3 a|b|c\n3 a|b|c\n3 [][][]\n2 [][ab]\na->b->c\nsolo\n");
}

/// The trim family and `repeat`. `repeat(0)` is "" and a negative count
/// panics (spec §4.2). Trimming an all-whitespace string yields "".
#[test]
fn string_trim_family_and_repeat() {
    let src = "fn main() {\n\
               let s = \"  héllo\\t\\n\"\n\
               println(\"[${s.trim()}][${s.trim_start()}][${s.trim_end()}]\")\n\
               println(\"[${\"   \".trim()}][${\"\".trim()}][${\"x\".trim()}]\")\n\
               println(\"[${\"ab\".repeat(3)}][${\"ab\".repeat(0)}][${\"\".repeat(5)}]\")\n\
               println(\"[${\"→\".repeat(2)}]\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-trim");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("[héllo][héllo\t\n][  héllo]\n[][][x]\n[ababab][][]\n[→→]\n");
}

/// `String::repeat`'s panic: a negative count. Modelled on
/// `panic_aborts_with_message` — `panic` aborts the process, so this cannot
/// share a fixture with anything that must keep running afterward. (An
/// earlier draft of this task pointed at a "`Vec::set` out-of-range test" as
/// the model instead; no such test exists in this file — the comment beside
/// `collections_run` claiming one does is stale — so `panic_aborts_with_message`
/// is the real, committed idiom for a process-aborting panic test.)
#[test]
fn string_repeat_negative_count_panics() {
    let dir = std::env::temp_dir().join("nova-strings-repeat-negative");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, "fn main() { println(\"${\"x\".repeat(0 - 1)}\") }\n").expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: String::repeat count must not be negative"),
        "stderr: {stderr}"
    );
}

/// Mutation-coverage gap the brief's own required test leaves open (same
/// shape as the Task 3–6 lessons): `string_trim_family_and_repeat` above only
/// ever trims ASCII whitespace (space, `\t`, `\n`) — none of the four
/// non-ASCII codepoints `char_is_whitespace` compares by scalar value
/// (U+00A0, U+2002, U+2003, U+3000) is exercised anywhere, so deleting or
/// mistyping any one of those four `if v == ...` lines is invisible to the
/// required test. All four are stacked on both sides of "mid" here (rather
/// than tested one at a time) because `trim_start_index`/`trim_end_index`
/// stop scanning at the FIRST non-whitespace codepoint they see: breaking any
/// single line makes the scan halt right there, leaving that codepoint and
/// everything after it (on that side) unstrimmed — so a wrong result on
/// EITHER side already proves at least one of the four is broken, without
/// needing four separate assertions. `\u{...}` is used rather than the raw
/// bytes because these are literally invisible/near-invisible characters in
/// a source file, and the brief's note that `\u{...}` lexes in a Nova STRING
/// literal (unlike a char literal) makes the escaped form both correct and
/// far more reviewable than an invisible byte would be.
#[test]
fn string_trim_covers_non_ascii_whitespace() {
    let src = "fn main() {\n\
               println(\"[${\"\\u{00A0}\\u{2002}\\u{2003}\\u{3000}mid\\u{3000}\\u{2003}\\u{2002}\\u{00A0}\".trim()}]\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-trim-unicode-ws");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("[mid]\n");
}

/// Mutation-coverage gap found in review, distinct from the non-ASCII gap
/// above: `trim_start` and `trim_end` are each called exactly once in
/// `string_trim_family_and_repeat`, both on `"  héllo\t\n"` — never
/// all-whitespace — so neither method's own all-whitespace fallback
/// (`trim_start_index`'s `cs.len()` fallback at `lib.nova:130`;
/// `trim_end_index`'s `floor` fallback at `lib.nova:138`) is ever reached
/// through them directly. Every all-whitespace input in the suite goes
/// through `trim()` instead, and `trim()`'s composition SELF-HEALS a wrong
/// `trim_start_index` result: whatever `a` it returns is fed straight back
/// in as `trim_end_index(cs, a)`'s `floor`, and for an all-whitespace string
/// `trim_end_index` always bottoms out at exactly `floor` (the whole range
/// is whitespace, so the scan never finds a reason to stop early) — so
/// `chars_to_string(cs, a, a)` always hits the `n <= 0` guard and yields ""
/// regardless of what `a` was. That makes "`trim`, `trim_start` and
/// `trim_end` are mutually distinguishable" (true, via the one asymmetric
/// string above) a DIFFERENT, weaker property than "each is independently
/// correct at the boundary where the whole string is whitespace" — which is
/// exactly where `trim_start`/`trim_end` diverge from `trim`'s
/// self-correcting composition. This test pins that boundary directly, on
/// each method's own call, bypassing `trim()` entirely. A tab-only case is
/// included since it costs nothing and confirms the fallback bug is not
/// specifically an ASCII-space artifact.
#[test]
fn string_trim_start_and_trim_end_pinned_on_all_whitespace() {
    let src = "fn main() {\n\
               println(\"[${\"   \".trim_start()}][${\"   \".trim_end()}]\")\n\
               println(\"[${\"\\t\\t\".trim_start()}][${\"\\t\\t\".trim_end()}]\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-trim-start-end-all-ws");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("[][]\n[][]\n");
}

/// Case mapping is WHOLE-STRING, not `Char -> Char`, because `ß` uppercases
/// to the two characters `SS`. A `Char -> Char` implementation cannot express
/// that and would silently corrupt such input — so `"ß".to_upper().len()`
/// being 2 is the assertion that proves the signature choice.
#[test]
fn string_case_mapping_is_whole_string_not_per_char() {
    let src = "fn main() {\n\
               println(\"${\"Straße\".to_upper()} ${\"ß\".to_upper().len()}\")\n\
               println(\"${\"HÉLLO WÖRLD\".to_lower()} ${\"\".to_upper()}|\")\n\
               println(\"${\"İ\".to_lower().len()} ${\"abc123\".to_upper()}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-case");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("STRASSE 2\nhéllo wörld |\n2 ABC123\n");
}

/// `("a\"b").dbg()` used to produce `"a"b"`, which is not a valid Nova
/// literal — the defect that motivated Phase 2.2b. Escaping needs to inspect
/// the string's contents, which `str_chars` now allows.
#[test]
fn debug_for_string_escapes_into_a_valid_literal() {
    let src = "fn main() {\n\
               println(\"${(\"a\\\"b\").dbg()}\")\n\
               println(\"${(\"back\\\\slash\").dbg()}\")\n\
               println(\"${(\"tab\\there\").dbg()}\")\n\
               println(\"${(\"\").dbg()} ${(\"é→\").dbg()}\")\n\
               }";
    // House idiom for a temp Nova source in this file — see
    // `check_reports_type_errors_with_code`. No `tempfile` dependency.
    let dir = std::env::temp_dir().join("nova-strings-dbg");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("\"a\\\"b\"\n\"back\\\\slash\"\n\"tab\\there\"\n\"\" \"é→\"\n");
}

/// Mutation-coverage gap the test above leaves open: it exercises `"`, `\\`
/// and `\t`, but never in isolation (always beside plain letters), and never
/// `\n`, `\r` or `\0` at all — four of `escape_common`'s six arms have no
/// dedicated case anywhere else in this file. `\r` and `\0` are the likeliest
/// to be typo'd and go unnoticed: unlike `\n`, a stray CR or NUL byte does not
/// visibly break a terminal line, so a wrong comparison or a wrong returned
/// escape string (e.g. swapping `\r`'s output with `\n`'s, or writing the
/// letter `O` for `\0`'s digit `0`) would be invisible in casual output and
/// invisible to every other test in this file. Each solo case is exactly the
/// one-codepoint string for that escape, so any such mutation surfaces as a
/// wrong line here with nothing else to mask it.
///
/// The last line puts all six escapes adjacent with no plain character
/// between them, which no per-arm-in-isolation case can: an off-by-one in the
/// character loop, or an `out` accumulation step that drops a piece, would
/// only show up when consecutive iterations each append a multi-character
/// escape back to back. It also carries the round-trip property directly:
/// `escape_common`'s escape letters are exactly Nova's own (`n`, `t`, `r`,
/// `0`), so the printed line is byte-for-byte the same text as the source
/// literal used to build the input string — confirmed here by tracing the
/// algorithm byte-by-byte by hand *before* running it (see the task report),
/// not by pasting whatever the program happened to print.
///
/// Written with raw strings (`r#"..."#`) rather than this file's usual
/// backslash-escaped `&str` literals: both the Nova source and the expected
/// stdout are dense with `"` and `\`, and a raw string passes every one of
/// them through unchanged instead of adding a third level of escaping on top
/// of Nova's own and the shell's.
#[test]
fn debug_for_string_escapes_every_control_arm_in_isolation() {
    let src = r#"fn main() {
    println("${("\\").dbg()}")
    println("${("\n").dbg()}")
    println("${("\t").dbg()}")
    println("${("\r").dbg()}")
    println("${("\0").dbg()}")
    println("${("\"").dbg()}")
    println("${("\\\n\t\r\0\"").dbg()}")
}
"#;
    let dir = std::env::temp_dir().join("nova-strings-dbg-arms");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova().arg("run").arg(&path).assert().success().stdout(
        r#""\\"
"\n"
"\t"
"\r"
"\0"
"\""
"\\\n\t\r\0\""
"#,
    );
}

/// The refactor shares one `escape_common` helper between `Debug for Char`
/// and `Debug for String`, and each keeps only the one quote its own literal
/// syntax needs escaped: `Char` escapes `'` but not `"` (a `"` needs no
/// escaping inside `'…'`), `String` escapes `"` but not `'` (symmetrically).
/// A one-character slip that pointed either impl's quote check at the other
/// quote character would still compile, and would still pass every other
/// test in this file — neither `'"'` nor `"'"` appears in any of them — so
/// each direction gets its own case here.
#[test]
fn debug_for_char_and_string_escape_only_their_own_quote() {
    let src = r#"fn main() {
    println("${('"').dbg()}")
    println("${("'").dbg()}")
}
"#;
    let dir = std::env::temp_dir().join("nova-strings-dbg-quote-cross");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova().arg("run").arg(&path).assert().success().stdout(
        r#"'"'
"'"
"#,
    );
}

/// `std/strings` end-to-end gate (Phase 2.2b, Task 10). Every index in the
/// module is a codepoint, so a byte-based regression shows up as a wrong
/// number here. Covers every numbered item of the design doc's §7 and every
/// row of its §4.2 table **that does not panic** — nothing in the fixture
/// may panic (a panic aborts the process and truncates the remaining
/// output), so §7 item 8's three `slice` panics and §4.2's `slice`/`repeat`
/// panic rows are deliberately excluded here and live in their own
/// `#[test]`s instead (`string_slice_negative_start_panics`,
/// `string_slice_end_past_len_panics`, `string_slice_start_after_end_panics`,
/// `string_repeat_negative_count_panics`) — across all 18 methods:
/// byte-vs-codepoint length, `chars()`'s array layout read back from Nova,
/// both `char_at` boundaries, `slice`'s half-open boundary plus a
/// nonzero-`start` offset with a multi-byte prefix, a round-trip through
/// `slice`+`join` for ASCII/accented/CJK/emoji input (the only way to
/// exercise `str_from_chars(str_chars(s)) == s` from a user module, since
/// neither builtin is itself callable outside an std module), every pinned
/// `split` row including a self-overlapping separator, `join`'s
/// separator-hangs-off-the-receiver shape, search boundaries (an anchored
/// vs. merely-occurring-somewhere needle, an odd-index mismatch inside the
/// shared `chars_match_at` primitive, empty needle, same-length
/// haystack/needle), the trim family including each of `trim_start`/
/// `trim_end`'s own all-whitespace fallback, an odd-length whitespace run,
/// non-ASCII whitespace and `\r`, `repeat`, `reverse`, whole-string case
/// mapping (`ß` -> `SS`, both directions on `""`), and `Debug for String`'s
/// escaping fix. See `tests/runtime/strings.nova`'s header for the full
/// item-by-item map.
#[test]
fn strings_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/strings.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/strings.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through the object-file backend. Not redundant with
/// `strings_run`: Task 8's review traced `nova_runtime::symbols()` to a
/// single caller, `compile_jit`, used only by `nova run` — `nova build`
/// links `nova_runtime.lib` at the OS linker level by the real `#[no_mangle]`
/// export name and never consults that table. An error confined to
/// `symbols()` would make the two backends disagree about the same program,
/// and only running the fixture through both can see it.
#[test]
fn strings_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/strings.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/strings.nova", "strings");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// The same fixture with `NOVA_GC_STRESS=1` (collect on every allocation) —
/// the reason this gate exists. `str_chars` and `str_from_chars` introduce
/// two new allocation shapes reachable from a builtin: a scanned array of
/// scalars, and a string, which was a leaf byte buffer plus a scanned header
/// and since 2026-10-04 is one leaf object holding both. Every method built
/// on them (`slice`, `split`, the trim family, `repeat`, `reverse`,
/// `to_upper`/`to_lower`) decodes to an intermediate `[Char]` and then
/// allocates again to build the result string, and that intermediate array
/// must stay live across the second allocation. A missed root here is
/// silently wrong text, not a crash. `join` no longer decodes: since
/// 2026-10-02 the runtime builtin `str_join` builds it. Since 2026-10-03 that
/// builtin allocates its result's buffer before it copies the parts in, so
/// this fixture's `join` calls also check that the parts survive that
/// allocation.
#[test]
fn strings_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/strings.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/strings.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `Vec::set` past the end aborts with its own message rather than
/// corrupting memory. The collections gate's doc comment (`collections_run`,
/// above) has claimed since Phase 2.2a that this test exists; it did not —
/// `git grep` finds only the comment — so the path was uncovered. Modelled on
/// `panic_aborts_with_message`, the file's actual idiom for a
/// process-aborting program. The message is read verbatim out of
/// `std/collections/lib.nova`'s `Vec::set` (both its `i < 0` and `i >=
/// self.len` guards share one message), not guessed.
#[test]
fn vec_set_out_of_range_aborts_with_message() {
    let dir = std::env::temp_dir().join("nova-collections-setoob");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(
        &path,
        "fn main() {\n\
         let mut v: Vec<Int> = Vec::new()\n\
         v.push(1)\n\
         v.set(5, 9)\n\
         }",
    )
    .expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: Vec::set index out of range"),
        "stderr: {stderr}"
    );
}

/// `Vec::set`'s OTHER guard: a negative index. The test above only trips
/// `std/collections/lib.nova:127`'s `i >= self.len` guard — deleting line 126's
/// separate `i < 0` guard entirely still passes it, since a negative index
/// then falls straight through to `self.data[i] = v`'s own array-bounds
/// check, which aborts with a *different*, generic message ("array index -1
/// out of bounds for length ...") rather than `Vec::set`'s named one. This
/// pins the negative-index guard on its own terms, in its own temp dir so
/// this and the test above (which run in parallel threads) never share a
/// `main.nova`.
#[test]
fn vec_set_negative_index_aborts_with_message() {
    let dir = std::env::temp_dir().join("nova-collections-setoob-neg");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(
        &path,
        "fn main() {\n\
         let mut v: Vec<Int> = Vec::new()\n\
         v.push(1)\n\
         v.set(0 - 1, 9)\n\
         }",
    )
    .expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: Vec::set index out of range"),
        "stderr: {stderr}"
    );
}

/// `unwrap` on a `None` aborts with its own message. Same provenance as
/// `vec_set_out_of_range_aborts_with_message` above — claimed by
/// `collections_run`'s doc comment since Phase 2.2a, never written. The
/// message is read verbatim out of `std/core/lib.nova`'s `Option::unwrap`.
#[test]
fn unwrap_on_the_wrong_variant_aborts_with_message() {
    let dir = std::env::temp_dir().join("nova-collections-unwrap");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(
        &path,
        "fn main() {\n\
         let o: Option<Int> = None\n\
         println(\"${o.unwrap()}\")\n\
         }",
    )
    .expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: called `unwrap` on a `None` value"),
        "stderr: {stderr}"
    );
}

// === Normalization seam 3: monomorphization (design doc §4.1) ===
//
// Trait bounds are discharged at monomorphization, not in `check_src`, so this
// seam cannot be exercised from `nova-typeck`'s unit suite at all — it needs the
// whole pipeline, which is why these live here.

/// A generic function whose signature mentions a projection, instantiated at
/// TWO different types. One instantiation would pass even if `subst` dropped
/// the binding and every projection resolved to the same thing; two cannot.
#[test]
fn a_projection_resolves_per_instantiation_at_monomorphization() {
    let src = "trait It { type Item\n fn get_item(self) -> Self::Item }\n\
               record W<T> { v: T }\n\
               impl<T> It for W<T> { type Item = T\n fn get_item(self) -> T { self.v } }\n\
               fn unwrap_item<I: It>(x: I) -> I::Item { x.get_item() }\n\
               fn main() {\n\
                   let a = unwrap_item(W { v: 7 })\n\
                   let b = unwrap_item(W { v: true })\n\
                   println(\"${a} ${b}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-mono");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("7 true\n");
}

/// The invalid-codegen path spec §4.2 and §9's risk 1 describe, closed.
///
/// A *parameter* declared `I::Item` is checked as `Assoc { on: Var(k) }`, because
/// a call site instantiates the callee's generic parameters as fresh inference
/// variables. No receiver is involved, so the `E0011` guard §4.2 relied on never
/// fires. With the determining argument first, `I` is pinned and the program
/// type-checks — and before this seam existed the projection survived to
/// lowering, where `mir_ty`'s defensive arm mapped it to `MirTy::Unit`.
///
/// Measured on the tree before this seam, which is sharper than the plan's
/// "codegen emitted garbage": `MirTy::Unit` parameters are *dropped* from the
/// Cranelift signature, so `f` was emitted taking ONE argument while `main`
/// called it with two, and the run died with
/// `WARN cranelift_codegen::verifier: Found verifier errors in function` /
/// `mismatched argument count for v4 = call fn1(v2, v3): got 2, expected 1`.
///
/// `y` is deliberately unused by the body: the point is the *signature* reaching
/// codegen, and using it would risk some other seam normalizing it first and
/// hiding what is under test.
#[test]
fn a_projection_parameter_on_a_pinned_generic_reaches_codegen_resolved() {
    let src = "trait It { type Item\n fn g(self) -> Int }\n\
               record W { v: Int }\n\
               impl It for W { type Item = Int\n fn g(self) -> Int { 1 } }\n\
               fn f<I: It>(x: I, y: I::Item) -> Int { 7 }\n\
               fn main() { println(\"${f(W { v: 1 }, 5)}\") }";
    let dir = std::env::temp_dir().join("nova-assoc-mono-param");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    let assert = nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("7\n");
    // The old failure was a *backend* crash, so assert stderr is clean too: a
    // regression that emitted invalid IR but still printed `7` by luck would
    // otherwise pass.
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        !stderr.contains("verifier"),
        "the projection must not reach codegen: {stderr}"
    );
}

/// The type arguments recorded at a *nested* call must be normalized too, not
/// only the instance's own signature and locals.
///
/// Inside `f`, `id`'s inferred type argument is `Param(0)::Item`, so each
/// instance of `f` records a projection there. Those arguments pick which
/// instance of `id` to emit and are fed to `mangle` — and `mangle_ty` maps
/// **every** `Ty::Assoc` to the single string `"X"`. So substituting without
/// normalizing gives `f::<W<Int>>` and `f::<W<Bool>>` the same callee symbol
/// `id.N$X`; mono's `done` set skips the second, and both calls dispatch to the
/// first one's code. That is a silent wrong answer of exactly the kind head-only
/// impl selection produced once before in this project.
///
/// Found by mutating `type_args: self.tys(type_args)` back to a bare `subst`,
/// which the rest of the suite survived. Measured under that mutation: Cranelift
/// aborts with `declared type of variable var2 doesn't match type of value v2`,
/// because `id`'s `Int` instance is asked to carry a `Bool`. Two instantiations
/// are load-bearing — with one, there is no second symbol to collide with.
#[test]
fn a_projection_in_a_nested_calls_type_arguments_is_normalized_too() {
    let src = "trait It { type Item\n fn get_item(self) -> Self::Item }\n\
               record W<T> { v: T }\n\
               impl<T> It for W<T> { type Item = T\n fn get_item(self) -> T { self.v } }\n\
               fn id<T>(x: T) -> T { x }\n\
               fn f<I: It>(x: I) -> I::Item { id(x.get_item()) }\n\
               fn main() {\n\
                   let a = f(W { v: 7 })\n\
                   let b = f(W { v: true })\n\
                   println(\"${a} ${b}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-mono-typeargs");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("7 true\n");
}

// === The `Iterator` trait and `Vec::iter` (design doc §5) ===
//
// The first real consumer of associated types: `std/core`'s `Iterator` with
// `type Item`, and `std/collections`' `VecIter<T>` binding `Item = T`. Every
// test here compiles a *user* program with no `import`, so it also pins that
// both names arrive by the std glob (ADR 0004).
//
// These are `run_tests` rather than `nova-typeck` unit tests on purpose: the
// projection is resolved at three separate seams and only the whole pipeline
// visits all three. They are also deliberately not folded into
// `tests/runtime/`'s fixtures — the fixture gate is a single program whose
// failure mode is one diff, while these isolate one property each.

/// Iterating a `Vec` by hand through the `Iterator` trait: no `for x in it`
/// desugar and no default methods exist yet (design doc §8), so this is what
/// iteration looks like today — a `while` plus a `match` on the `Option`.
///
/// The loop runs a **fixed** six `next()` calls over a three-element vector
/// rather than stopping at the first `None`, and that shape is load-bearing
/// three ways:
///
/// - It pins that `next` keeps answering `None` after exhaustion, not only
///   that it says `None` once. `nones=3` is the assertion.
/// - It makes a non-advancing `next` *observable instead of a hang*. Deleting
///   `self.i = self.i + 1` from `VecIter::next` yields element 0 six times:
///   `total=60 nones=0`, which fails here. A loop that exited on the first
///   `None` would spin forever and report nothing.
/// - The element values are 10/20/40, not 10/20/30, so that `total` alone
///   distinguishes the mutations. With 10/20/30 a non-advancing iterator sums
///   to the same 60 as the correct one, and only `nones` would have caught it.
///
/// `break` is avoided in the `match` arms: `break` followed by a newline and
/// an expression parses that expression as the break value (see the plan's
/// Global Constraints), and a counter is clearer than working around it.
#[test]
fn a_vec_iterates_to_exhaustion_through_the_iterator_trait() {
    let src = "fn main() {\n\
                   let mut v: Vec<Int> = Vec::new()\n\
                   v.push(10)\n\
                   v.push(20)\n\
                   v.push(40)\n\
                   let mut it = v.iter()\n\
                   let mut total = 0\n\
                   let mut nones = 0\n\
                   let mut n = 0\n\
                   while n < 6 {\n\
                       match it.next() {\n\
                           Some(x) => total = total + x,\n\
                           None => nones = nones + 1,\n\
                       }\n\
                       n = n + 1\n\
                   }\n\
                   println(\"total=${total} nones=${nones}\")\n\
                   let mut it2 = v.iter()\n\
                   let o: Option<Int> = it2.next()\n\
                   println(\"first=${o.unwrap_or(0)}\")\n\
                   let e: Vec<Int> = Vec::new()\n\
                   let mut ei = e.iter()\n\
                   match ei.next() {\n\
                       Some(x) => println(\"unexpected ${x}\"),\n\
                       None => println(\"empty ok\"),\n\
                   }\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-veciter");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("total=70 nones=3\nfirst=10\nempty ok\n");
}

/// `next` at exhaustion must **not** advance the cursor, and nothing above can
/// see the difference.
///
/// `VecIter::next`'s `if self.i >= self.v.len() { return None }` guard is
/// redundant for *safety* — `Vec::get` bounds-checks and would return `None`
/// anyway — so relaxing it to `>` still returns `None` at every index past the
/// end, and `a_vec_iterates_to_exhaustion_through_the_iterator_trait` above
/// passes byte-identically under that mutation. What the guard actually buys is
/// that `i` stops at `len`, and the only way to observe `i` from Nova is to
/// give the vector a new element for the cursor to find.
///
/// That works because `VecIter` holds the `Vec` record by pointer, so `it.v`
/// and `v` are the same object and a `push` during iteration is visible to the
/// iterator (documented at `VecIter`'s declaration). So this test doubles as
/// the pin on that alias-visibility, which is otherwise only asserted in a
/// comment.
#[test]
fn an_exhausted_vec_iterator_does_not_advance_its_cursor() {
    let src = "fn main() {\n\
                   let mut v: Vec<Int> = Vec::new()\n\
                   v.push(10)\n\
                   let mut it = v.iter()\n\
                   match it.next() { Some(x) => println(\"a=${x}\"), None => println(\"a=none\") }\n\
                   match it.next() { Some(x) => println(\"b=${x}\"), None => println(\"b=none\") }\n\
                   v.push(20)\n\
                   match it.next() { Some(x) => println(\"c=${x}\"), None => println(\"c=none\") }\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-veciter-cursor");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("a=10\nb=none\nc=20\n");
}

/// A generic function bounded by `Iterator` whose signature names the
/// projection, called at **two different** instantiations plus an empty one.
/// Design doc §7's gate item 3.
///
/// The receiver is `mut it`, not `it`. §7 originally wrote
/// `fn first<I: Iterator>(it: I)`; Task 8 made `mut self` on a trait method
/// enforced, so that spelling is now `E0060` and the `mut` is the rule working
/// rather than a workaround. `mut` on a *parameter* is what carries it — there
/// is no `let mut` to reach for when the iterator arrives as an argument.
///
/// Two functions, because `first` alone does **not** reach the monomorphization
/// seam and I measured that rather than assuming it. Made mono's normalization
/// cache its first answer and reuse it for every projection (the plan's
/// mutation 3), and `first`'s three instantiations still printed
/// `int=7 / str=hi / bool=none` byte-identically: `Option<Int>` and
/// `Option<String>` lower to the *same* `MirTy` — a pointer to a heap sum — so a
/// corrupted return type on `first`'s String instance changes nothing a backend
/// can see, and `main` is not generic, so typeck's own seam had already fixed
/// the types the `${…}` interpolations dispatch on.
///
/// `first_or` fixes that by naming `I::Item` **bare**, in both a parameter and
/// the return type, so the projection's resolution decides a machine class
/// (`I64` vs a pointer) instead of hiding inside a sum. Under the same mutation
/// it dies in Cranelift with `declared type of variable ... doesn't match type
/// of value`. The wrapped and unwrapped forms are both worth keeping: the
/// wrapped one is the spec's literal signature and the shape a user writes; the
/// unwrapped one is the one with teeth.
///
/// `it: I` deliberately precedes `dflt: I::Item`, so `I` is pinned by the first
/// argument before the projection parameter is checked — the ordering
/// `a_projection_parameter_on_a_pinned_generic_reaches_codegen_resolved` above
/// depends on for the same reason.
#[test]
fn a_generic_function_over_iterator_resolves_item_per_instantiation() {
    let src = "fn first<I: Iterator>(mut it: I) -> Option<I::Item> { it.next() }\n\
               fn first_or<I: Iterator>(mut it: I, dflt: I::Item) -> I::Item {\n\
                   match it.next() { Some(x) => x, None => dflt }\n\
               }\n\
               fn main() {\n\
                   let mut ns: Vec<Int> = Vec::new()\n\
                   ns.push(7)\n\
                   let mut ss: Vec<String> = Vec::new()\n\
                   ss.push(\"hi\")\n\
                   match first(ns.iter()) { Some(n) => println(\"int=${n}\"), None => println(\"int=none\") }\n\
                   match first(ss.iter()) { Some(s) => println(\"str=${s}\"), None => println(\"str=none\") }\n\
                   let e: Vec<Bool> = Vec::new()\n\
                   match first(e.iter()) { Some(b) => println(\"bool=${b}\"), None => println(\"bool=none\") }\n\
                   println(\"or_int=${first_or(ns.iter(), 0)}\")\n\
                   println(\"or_str=${first_or(ss.iter(), \"?\")}\")\n\
                   println(\"or_empty=${first_or(e.iter(), true)}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-iterator-generic");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    let assert = nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("int=7\nstr=hi\nbool=none\nor_int=7\nor_str=hi\nor_empty=true\n");
    // The mutation this test exists to catch fails in the *backend*, so a clean
    // stderr is part of the assertion: a regression that emitted invalid IR and
    // still printed the right bytes by luck would otherwise pass.
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        !stderr.contains("verifier") && !stderr.contains("panicked"),
        "no projection may reach codegen unresolved: {stderr}"
    );
}

/// The rooting chain `VecIter` introduces, under `NOVA_GC_STRESS=1` (collect on
/// every allocation).
///
/// This is the one risk in `VecIter` that is not a typing question. `next`
/// allocates on every call — `Vec::get` returns `Some(x)`, which is a heap
/// variant — and under stress every one of those is a collection point. The
/// backing `[String]` is reachable only as `it` -> `VecIter` -> `Vec` ->
/// `data`: three levels of heap indirection from one stack slot. Nothing in the
/// existing `collections` gate has that shape, because a `Vec` there is always
/// itself a live local.
///
/// `make()` is what makes the chain load-bearing: the vector is built in a frame
/// that has already returned, so `it` is the **only** root. Holding the `Vec` in
/// `main` as well would keep the array alive independently and the test would
/// prove nothing about `VecIter` holding it.
///
/// `Vec<String>` rather than `Vec<Int>` so the elements are heap objects too,
/// and the accumulator is built by interpolation so each loop turn allocates
/// again while the iterator's storage must stay live across it.
///
/// `VecIter<String>` is written out as `make`'s return type, which also pins
/// that the type is nameable from user code rather than only inferable.
#[test]
fn a_vec_iterator_keeps_its_backing_storage_alive_under_gc_stress() {
    let src = "fn make() -> VecIter<String> {\n\
                   let mut v: Vec<String> = Vec::new()\n\
                   v.push(\"a\")\n\
                   v.push(\"b\")\n\
                   v.push(\"c\")\n\
                   v.push(\"d\")\n\
                   v.push(\"e\")\n\
                   v.iter()\n\
               }\n\
               fn main() {\n\
                   let mut it = make()\n\
                   let mut out = \"\"\n\
                   let mut n = 0\n\
                   while n < 7 {\n\
                       match it.next() {\n\
                           Some(s) => out = \"${out}${s}\",\n\
                           None => out = \"${out}.\",\n\
                       }\n\
                       n = n + 1\n\
                   }\n\
                   println(\"out=${out}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-veciter-gc");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    // Both modes, from one program: a missed root here is silently wrong *text*,
    // not a crash, so the un-stressed run is the control that says the expected
    // string is right in the first place.
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("out=abcde..\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("out=abcde..\n");
}

/// `std/core`'s `Iterator` is implementable by **user** code, and an impl may
/// echo the trait's projection (`-> Option<Self::Item>`) instead of writing the
/// concrete type — design doc §5.1's "either spelling is accepted" row, checked
/// against the shipped trait rather than a test-local one.
///
/// Also a third instantiation of `first<I: Iterator>` that is not a `VecIter`
/// at all, which is what distinguishes "the trait works" from "the trait works
/// for the one implementor std happens to ship".
///
/// `Counter { n: 9 }` is bound to a local before being passed: a record literal
/// written directly inside a `match` scrutinee (`match first(Counter { n: 9 })`)
/// does not parse — the `{` is taken as the end of the call arguments. That is a
/// pre-existing parser limitation unrelated to iterators, worked around here
/// rather than papered over silently.
#[test]
fn a_user_record_can_implement_the_std_iterator_trait() {
    let src = "record Counter { n: Int }\n\
               impl Iterator for Counter {\n\
                   type Item = Int\n\
                   fn next(mut self) -> Option<Self::Item> {\n\
                       if self.n >= 3 { return None }\n\
                       let x = self.n\n\
                       self.n = self.n + 1\n\
                       Some(x)\n\
                   }\n\
               }\n\
               fn first<I: Iterator>(mut it: I) -> Option<I::Item> { it.next() }\n\
               fn main() {\n\
                   let mut c = Counter { n: 0 }\n\
                   match c.next() { Some(x) => println(\"a=${x}\"), None => println(\"a=none\") }\n\
                   let c0 = Counter { n: 0 }\n\
                   match first(c0) { Some(x) => println(\"b=${x}\"), None => println(\"b=none\") }\n\
                   let c9 = Counter { n: 9 }\n\
                   match first(c9) { Some(x) => println(\"c=${x}\"), None => println(\"c=none\") }\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-iterator-user-impl");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("a=0\nb=0\nc=none\n");
}

/// `Iterator::next` takes `mut self`, so calling it through an immutable
/// binding is `E0060` — on `std/core`'s own trait, not just a test-local one.
///
/// Task 8 pinned the rule on a synthetic `trait Bump`. This pins it on the
/// shipped trait, which is what a user actually meets, and is the reason
/// `let mut it` appears in every test above rather than being incidental
/// style. Without it, a caller could silently advance an iterator someone
/// else believes is unread through `next` itself — which is still exactly
/// what this test pins.
///
/// It is *not* what every method on this trait pins any longer.
/// `fold`/`count`/`any`/`collect` (added later, see `std/core/lib.nova`'s
/// comment above `fold`) deliberately dropped this same requirement so they
/// could run on a temporary receiver, and a side effect of that is a
/// non-`mut` binding being silently advanced through any of the four just the
/// same — `iterator_any_short_circuits_and_does_not_scan_past_the_first_
/// match` below pins that as accepted, current behavior, not an oversight.
#[test]
fn calling_next_on_an_immutable_vec_iterator_reports_e0060() {
    let src = "fn main() {\n\
                   let mut v: Vec<Int> = Vec::new()\n\
                   v.push(1)\n\
                   let it = v.iter()\n\
                   match it.next() { Some(x) => println(\"${x}\"), None => println(\"none\") }\n\
               }";
    let dir = std::env::temp_dir().join("nova-assoc-iterator-immutable");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    let assert = nova().arg("check").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("error[E0060]") && stderr.contains("`next` mutates its receiver"),
        "stderr: {stderr}"
    );
}

/// Associated types end-to-end gate (Phase 2.2c, Task 10). One program covering
/// every item of the design doc's §7 gate list that a fixture *can* cover —
/// items 1-5; its items 6-10 each fail to compile or abort, so they are
/// `#[test]`s in `crates/nova-typeck/src/check.rs` instead
/// (`a_bound_on_an_associated_type_reports_e0900`,
/// `an_impl_missing_an_associated_type_reports_e0070`,
/// `an_impl_binding_an_undeclared_associated_type_reports_e0071`,
/// `mut_self_trait_method_on_an_immutable_receiver_reports_e0060`,
/// `mut_self_trait_method_conformance_disagreement_is_e0072`).
///
/// Covers: an associated type bound to the impl's **own** generic parameter at
/// three instantiations (so every projection goes through `subst`); both
/// accepted spellings of an impl's signature (`-> T` and the echoed
/// `-> Self::Out`) plus `Self::Out` in a `let` annotation inside an impl body;
/// a trait with **two** associated types, instantiated once as
/// `Both<Int, String>` and once as `Both<String, Int>` so the two cannot be
/// confused; `it.next()` on a concrete `VecIter<Int>` typing as `Option<Int>`
/// with no annotation; a `Vec` iterated past exhaustion; a `Vec::new()` whose
/// first `next` is already `None`; and generic functions naming the projection
/// **bare** (`-> S::Out`, `-> P::Left`, `(dflt: I::Item) -> I::Item`) as well as
/// wrapped (`-> Option<I::Item>`).
///
/// The bare spelling is the load-bearing one and the reason this fixture is not
/// just `first`. Task 9 measured that `-> Option<I::Item>` at three
/// instantiations **survives** a mutation making monomorphization's
/// normalization cache its first answer, byte-identically: `Option<Int>` and
/// `Option<String>` lower to the same `MirTy`, so a wrong `Item` is invisible
/// after lowering, and `main` is not generic, so typeck's seam had already
/// fixed the dispatch types. Bare, a wrong `Item` is a wrong machine class and
/// dies in Cranelift. See the fixture's header for the mutation-to-line map.
#[test]
fn assoc_types_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/assoc_types.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/assoc_types.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through the object-file backend. Not redundant with
/// `assoc_types_run` for the reason `strings_build_standalone`'s comment gives
/// — `nova run` resolves runtime symbols through `nova_runtime::symbols()`
/// while `nova build` links `nova_runtime.lib` by export name and never
/// consults that table — and for one specific to this gate: the mutation this
/// fixture exists to catch fails in **code generation**, not in the type
/// checker, so the two backends are the two places it can fail differently.
#[test]
fn assoc_types_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/assoc_types.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/assoc_types.nova", "assoc_types");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// The same fixture with `NOVA_GC_STRESS=1` (collect on every allocation) — a
/// gate criterion, not belt-and-braces. `VecIter` introduces a three-level
/// rooting chain: the backing `[T]` is reachable only as
/// `it` -> `VecIter` -> `Vec` -> `data`, and `next` allocates a fresh `Option`
/// on every call, so the storage must survive a collection triggered by the
/// very call that reads it. The collector scans the stack plus callee-saved
/// registers, and that is precisely what makes an iterator held across a call a
/// root; a missed root here loses elements silently rather than crashing. The
/// `String` and `Char` iterators in the fixture matter for the same reason —
/// their elements are themselves heap objects, so a lost root shows up as wrong
/// text rather than a wrong number.
#[test]
fn assoc_types_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/assoc_types.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/assoc_types.nova"))
        .assert()
        .success()
        .stdout(expected);
}

// === Task 11 Step 6b: two source-reachable branches in `mono.rs` that had no
// test at all. Both survived mutation with the whole suite green.

/// A trait with `n+1` associated types `A0..An` whose impl chains each `Ak` to
/// `link(k)` and bottoms out at `An = Int`, plus a generic function that names
/// `I::A0` **only inside its own body**.
///
/// That last part is what makes monomorphization the *first* seam to resolve the
/// chain concretely, and it is the whole difficulty of reaching mono's `E0078`
/// from source. The typeck-side twins of these programs
/// (`a_binding_chain_that_resolves_to_an_enormous_type_is_a_diagnostic` and
/// `a_long_but_terminating_binding_chain_is_a_diagnostic` in
/// `crates/nova-typeck/src/check.rs`) give the trait a method whose *signature*
/// mentions `Self::A0`, so `check_impl_conformance` normalizes it with a
/// concrete `Self` and reports there — three times — and compilation stops
/// before mono runs. Here nothing in any signature mentions the projection:
/// inside `use_it` the type is `[Assoc { on: Param(0) }]`, which has no head, so
/// seam 1 correctly leaves it alone, and `main`'s call instantiates only
/// `(I) -> Int`.
///
/// `[I::A0]` rather than `Vec<I::A0>` for the diagnostic's sake, not the
/// compiler's: both reach the branch, but mono's `type_name` drops a record's
/// type arguments, so the `Vec` spelling reports "the associated types in
/// `Vec`" — naming a type that does not mention a projection at all. The array
/// spelling reports `[W::A0]`. (`type_name` dropping generic arguments is a
/// queued defect; this test is written so it cannot hide behind it.)
///
/// An empty array literal is the initializer because the element type is
/// genuinely uninhabited here: no value of `I::A0` can be produced without a
/// trait method returning it, and adding one would put the projection back into
/// a signature and move the diagnostic to typeck.
fn assoc_chain_in_a_generic_body(n: u32, link: impl Fn(u32) -> String) -> String {
    let decls: String = (0..=n).map(|k| format!(" type A{k}\n")).collect();
    let binds: String = (0..n)
        .map(|k| format!(" type A{} = {}\n", k, link(k)))
        .collect();
    format!(
        "record Pair<A, B> {{ a: A\n b: B }}\n\
         trait Chain {{\n{decls} fn g(self) -> Int }}\n\
         record W {{ v: Int }}\n\
         impl Chain for W {{\n{binds} type A{n} = Int\n\
         fn g(self) -> Int {{ 1 }} }}\n\
         fn use_it<I: Chain>(x: I) -> Int {{\n\
         let a: [I::A0] = []\n\
         a.len() }}\n\
         fn main() {{ println(\"${{use_it(W {{ v: 1 }})}}\") }}\n"
    )
}

/// Monomorphization's `E0078` branch, and **which of the two limits it names**.
///
/// Mono has its own normalization budget failure path, distinct from
/// `Checker::normalize`'s, and before this test it had no coverage of any kind:
/// making the branch unreachable left the whole suite green. It is not a
/// backstop — a 45-line program reaches it (the wide half below), which is why
/// this is a `nova check` test and not a hand-built `hir::Module`.
///
/// Both halves are here because the `detail` match in `mono.rs` has two arms and
/// a test that asserted only the code would accept either arm for either input.
/// The wide chain is 16 links, comfortably inside the depth limit of 64, so
/// blaming depth would tell the user to shorten a chain that is already short;
/// the deep chain resolves to 66 nodes, so blaming size would tell them to
/// simplify a type that is tiny. The same mutation on the typeck side
/// (`619f453`) survived a test that checked only the code.
///
/// Exactly one diagnostic each, asserted by counting: the typeck twins report
/// three for one root cause because conformance and `check_fn_body` each
/// normalize the same signature, and mono records only the *first* failure per
/// instance. A regression that moved the report back to typeck would show up
/// here as three.
#[test]
fn mono_reports_which_normalization_limit_a_projection_overflowed() {
    let dir = std::env::temp_dir().join("nova-mono-normalize-limits");
    std::fs::create_dir_all(&dir).expect("temp dir");
    // Wide: `type A(k) = Pair<Self::A(k+1), Self::A(k+1)>`, so `A0` resolves to
    // 2^17-1 nodes. The step allowance, not the depth one.
    let wide = dir.join("wide.nova");
    std::fs::write(
        &wide,
        assoc_chain_in_a_generic_body(16, |k| format!("Pair<Self::A{}, Self::A{}>", k + 1, k + 1)),
    )
    .expect("write");
    let assert = nova().arg("check").arg(&wide).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert_eq!(
        stderr.matches("error[E0078]").count(),
        1,
        "one overflow, one report: {stderr}"
    );
    assert!(
        stderr.contains("resolves to more than 10000 type nodes"),
        "a wide chain is a size report, not a depth report: {stderr}"
    );
    // The projection has to be nameable in the message; `[W::A0]` is what
    // `type_name` produces for the array of it.
    assert!(
        stderr.contains("`[W::A0]`") && stderr.contains("when instantiating `use_it`"),
        "the message must name both the type and the instance: {stderr}"
    );
    // Deep: `type A(k) = Self::A(k+1)`, 65 links, so the chain exceeds the depth
    // limit long before the step allowance (66 nodes total).
    let deep = dir.join("deep.nova");
    std::fs::write(
        &deep,
        assoc_chain_in_a_generic_body(65, |k| format!("Self::A{}", k + 1)),
    )
    .expect("write");
    let assert = nova().arg("check").arg(&deep).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert_eq!(
        stderr.matches("error[E0078]").count(),
        1,
        "one overflow, one report: {stderr}"
    );
    assert!(
        stderr.contains("the chain of bindings is more than 64 deep"),
        "a deep chain is a depth report, not a size report: {stderr}"
    );
}

/// A trait bound is satisfied only by an impl whose self type **fits the
/// argument structurally**, not merely one that shares its head.
///
/// `impl_satisfies` filters `module.impls` by `self_head`, then requires
/// `imp.match_args(arg)` to succeed. Dropping that second requirement — so any
/// impl on the same head satisfies the bound — left the entire suite green, and
/// it is not an equivalent mutant: `f(P { a: 1, b: true })` then **prints `7`
/// and exits 0** with a declared bound silently unenforced. That is the
/// head-only-selection class this project has already shipped once as a
/// miscompile (`d49f896`), and it is also the gate `E0079`'s unreachability
/// rests on — `match_args` on a non-fitting impl is what would otherwise hand
/// mono a `Ty::Error` self type with a projection on it.
///
/// The positive half is not optional. `P<Int, Bool>` alone would also pass if
/// `impl It for P<Int, Int>` were never selectable at all, which is the failure
/// mode the fix for a head-only bug most plausibly introduces. Both halves are
/// the same declarations with one literal changed.
#[test]
fn a_trait_bound_needs_an_impl_that_fits_structurally_not_just_by_head() {
    let program = |b: &str| {
        format!(
            "trait It {{ type Item\n\
             fn g(self) -> Int }}\n\
             record P<A, B> {{ a: A\n\
             b: B }}\n\
             impl It for P<Int, Int> {{ type Item = Int\n\
             fn g(self) -> Int {{ 1 }} }}\n\
             fn f<I: It>(x: I) -> Int {{ 7 }}\n\
             fn main() {{ println(\"${{f(P {{ a: 1, b: {b} }})}}\") }}\n"
        )
    };
    let dir = std::env::temp_dir().join("nova-impl-structural-fit");
    std::fs::create_dir_all(&dir).expect("temp dir");
    // `P<Int, Bool>` shares the head `Record(P)` with the impl and does not fit
    // it, so the bound is unsatisfied.
    let bad = dir.join("bad.nova");
    std::fs::write(&bad, program("true")).expect("write");
    let assert = nova().arg("run").arg(&bad).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("error[E0013]") && stderr.contains("`P: It`"),
        "stderr: {stderr}"
    );
    // The control: `P<Int, Int>` does fit, so the same program compiles and runs.
    let good = dir.join("good.nova");
    std::fs::write(&good, program("2")).expect("write");
    nova()
        .arg("run")
        .arg(&good)
        .assert()
        .success()
        .stdout("7\n");
}

/// `MapIter` and `FilterIter` (iterator-finishing plan, Task 3): the two lazy
/// adapters `std/core` provides, each a record plus an `Iterator` impl,
/// constructed directly here rather than through `.map()`/`.filter()` — Task 4
/// adds those — so this task is verifiable on its own. Covers three things at
/// once: `MapIter` alone, `FilterIter` alone, and the two chained (`MapIter`
/// wrapping a `FilterIter` wrapping a `VecIter`).
///
/// The chain's output is `Bool`, deliberately: `mir_ty` collapses `Int`,
/// `Char`, `String` and every heap type to one machine class (`MirTy::I64`/
/// `Ptr`), so an `Int`-only pipeline cannot distinguish "yields the right
/// value" from "yields *some* value of the same machine shape". `Bool` is
/// `MirTy::I8` — a different machine class from the vector's `Int` — so a
/// `MapIter` that forwarded the unmapped inner item, or a `FilterIter` whose
/// `Item` bound to a concrete `Int` instead of chasing `I::Item`, both have
/// somewhere to go visibly wrong instead of coincidentally still working.
///
/// The chain is also the first real-source appearance of the `Assoc { on:
/// Assoc }` shape: the outer `MapIter<I, U>`'s field `f: fn(I::Item) -> U`
/// needs `I::Item` where `I = FilterIter<VecIter<Int>>`, and `FilterIter`'s
/// own `type Item = I::Item` is itself a projection rather than a concrete
/// type — so resolving it chases through a second impl (`VecIter<Int>`'s)
/// before landing on `Int`.
#[test]
fn iterator_adapters_chain_and_are_lazy() {
    let src = "fn main() {\n\
                   let mut v = Vec::new()\n\
                   v.push(1)\n\
                   v.push(2)\n\
                   v.push(3)\n\
                   let mut m = MapIter { it: v.iter(), f: |n| n * 10 }\n\
                   for x in m { println(\"${x}\") }\n\
                   let mut f = FilterIter { it: v.iter(), keep: |n| n > 1 }\n\
                   for x in f { println(\"keep ${x}\") }\n\
                   let mut c = MapIter { it: FilterIter { it: v.iter(), keep: |n| n > 1 }, f: |n| n > 2 }\n\
                   for b in c { println(\"chain ${b}\") }\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-adapters");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    // chain yields Bool: filter keeps 2,3 then map gives false,true
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("10\n20\n30\nkeep 2\nkeep 3\nchain false\nchain true\n");
}

/// `record_field_index_and_ty` (`crates/nova-typeck/src/check.rs`) had the
/// same raw-`subst`-instead-of-`instantiate` gap `check_record_literal` did
/// above, on the field *read* path rather than construction: reading `m.f`
/// or `c.hit` back out of an already-built, now-concretely-typed record
/// substituted a projection on the record's own bounded parameter without
/// normalizing it, so `g(5)` and `x + 1` below failed structurally even
/// though `m`/`c` themselves built without complaint. Two shapes in one
/// test, since the bug needed a concrete instance of each to show up: a
/// function-typed field (`f: fn(I::Item) -> U`) read out and called, and a
/// plain field (`hit: I::Item`) read out and used directly.
#[test]
fn a_record_field_read_resolves_a_projection_through_a_now_concrete_parameter() {
    let src = "trait It { type Item\n\
                   fn next(mut self) -> Option<Self::Item> }\n\
               record M<I: It, U> { it: I, f: fn(I::Item) -> U }\n\
               record Cache<I: It> { it: I, hit: I::Item }\n\
               record Counter { n: Int }\n\
               impl It for Counter {\n\
                   type Item = Int\n\
                   fn next(mut self) -> Option<Int> { None }\n\
               }\n\
               fn main() {\n\
                   let m = M { it: Counter { n: 0 }, f: |x| x + 1 }\n\
                   let g = m.f\n\
                   println(\"${g(5)}\")\n\
                   let c = Cache { it: Counter { n: 0 }, hit: 7 }\n\
                   let x = c.hit\n\
                   println(\"${x + 1}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-record-field-read-projection");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("6\n8\n");
}

/// `MapIter::next` maps exactly one element per call, on demand — it is not
/// merely correct about *which* values come out (the tests above), it is lazy
/// about *when* `f` runs. `f` here is side-effecting (`println("call")`) so
/// that is directly observable: the `for` loop's desugar calls `next` once,
/// prints the mapped result, then `break`s. A lazy `MapIter` therefore prints
/// exactly one `call` before `got 10`; an eager one — say, a `MapIter` that
/// drained and mapped its whole source at construction, buffering the
/// results — would print `call` three times (once per element of `v`)
/// before the loop ever ran at all, since building `m` would need to finish
/// that up front.
#[test]
fn a_map_iter_calls_f_lazily_not_all_up_front() {
    let src = "fn main() {\n\
                   let mut v = Vec::new()\n\
                   v.push(1)\n\
                   v.push(2)\n\
                   v.push(3)\n\
                   let mut m = MapIter { it: v.iter(), f: |n| { println(\"call\") n * 10 } }\n\
                   for x in m { println(\"got ${x}\") break }\n\
                   println(\"done\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-map-iter-laziness");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("call\ngot 10\ndone\n");
}

/// Task 4 (iterator-finishing plan): the six default methods `Iterator`
/// provides so callers reach `MapIter`/`FilterIter` without ever naming them —
/// `map`, `filter`, `fold`, `count`, `any`, `collect`. Chains `filter` into
/// `map` into `collect` (a `Vec`), then separately drives `fold`/`count`/`any`
/// each over their own fresh `.iter()`, since every consumer here exhausts
/// its receiver and a second call needs a fresh cursor.
///
/// The last line is deliberate, not incidental: it chains `map` to `Bool` (so
/// the item type actually changes partway down the pipeline) and only then
/// consumes with `any`, so that consumer sees a **`Bool`** item rather than
/// the `Int` every earlier line uses — the one assertion here that could
/// catch a wrong item type surviving to the monomorphization seam instead of
/// merely a wrong count or a coincidentally-right value.
///
/// `assert_runs_with` does not exist in this file; this follows the same
/// inline `nova run` pattern every neighboring test in this module uses
/// (e.g. `a_map_iter_calls_f_lazily_not_all_up_front` above).
///
/// **Matches the plan's literal source exactly, unlike an earlier round of
/// this test.** The plan's Step 1 chains `fold`/`count`/`any`/`collect`
/// straight onto a call result — e.g. `v.iter().fold(0, |a, x| a + x)` — which
/// first failed with `E0060` (`place_root`,
/// `crates/nova-typeck/src/check.rs`, classifies a call result
/// `PlaceRoot::NotAPlace`, and a `mut self` receiver requires
/// `PlaceRoot::Mutable`). That was fixed at the design level, not by
/// rewriting this test to dodge it: all four consumers now take plain `self`
/// and rebind internally (`let mut it = self`, `trait Iterator`'s own doc
/// comment above `fold` explains why this aliases rather than copies), so the
/// receiver no longer has to already be a mutable place the caller named.
/// With that landed, the plan's original source needs no `let mut` workaround
/// at all and is reproduced here verbatim.
#[test]
fn iterator_default_methods_work_and_chain() {
    let src = "fn main() {\n\
      let mut v = Vec::new()\n\
      v.push(1)\n\
      v.push(2)\n\
      v.push(3)\n\
      let got = v.iter().filter(|n| n > 1).map(|n| n * 10).collect()\n\
      println(\"${got.len()}\")\n\
      println(\"${got.get(0).unwrap()}\")\n\
      println(\"${v.iter().fold(0, |a, x| a + x)}\")\n\
      println(\"${v.iter().count()}\")\n\
      println(\"${v.iter().any(|n| n > 2)}\")\n\
      println(\"${v.iter().any(|n| n > 9)}\")\n\
      println(\"${v.iter().map(|n| n > 2).any(|b| b)}\")\n\
    }";
    let dir = std::env::temp_dir().join("nova-iterator-default-methods");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("2\n20\n6\n3\ntrue\nfalse\ntrue\n");
}

/// Task 4 Step 5: laziness is the property the `Iterator::map` *default
/// method* exists to preserve, and nothing above can see it — a lazy and an
/// eager `.map()` produce identical values as long as nothing observes *when*
/// the source is pulled from. `a_map_iter_calls_f_lazily_not_all_up_front`
/// (above, from Task 3) already puts the side effect in the mapping closure
/// `f` and already goes through a directly-built `MapIter { .. }` literal, not
/// `.map()`. This test puts the side effect in the *source* iterator's own
/// `next` instead, and reaches the adapter through `.map()` — the one new
/// piece Task 4 adds — so it is `map`'s default-method body
/// (`MapIter { it: self, f: f }`, nothing more) that is on trial, not
/// `MapIter::next` a second time.
///
/// `PrintSrc` is a hand-written `Iterator` whose `next` prints `pull N` before
/// yielding `N`. `.map(|x| x * 10)` is built and then a marker (`built`)
/// prints *before* the result is touched at all. An eager `.map()` would have
/// had to drain `PrintSrc` to build its result, so every `pull` would print
/// before `built` does. A lazy one prints `built` with no `pull` at all yet,
/// and then exactly one `pull` per `.next()` call, interleaved with that
/// call's mapped result — not three `pull`s up front followed by three
/// results. That interleaving, not merely the final values, is what "lazy"
/// means operationally.
#[test]
fn iterator_map_default_method_is_lazy_over_a_side_effecting_source() {
    let src = "record PrintSrc { n: Int, max: Int }\n\
               impl Iterator for PrintSrc {\n\
                   type Item = Int\n\
                   fn next(mut self) -> Option<Int> {\n\
                       if self.n >= self.max { return None }\n\
                       println(\"pull ${self.n}\")\n\
                       let x = self.n\n\
                       self.n = self.n + 1\n\
                       Some(x)\n\
                   }\n\
               }\n\
               fn main() {\n\
                   let src = PrintSrc { n: 0, max: 3 }\n\
                   let mut m = src.map(|x| x * 10)\n\
                   println(\"built\")\n\
                   println(\"${m.next().unwrap()}\")\n\
                   println(\"${m.next().unwrap()}\")\n\
                   println(\"${m.next().unwrap()}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-map-default-is-lazy");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("built\npull 0\n0\npull 1\n10\npull 2\n20\n");
}

/// Needed to make Step 6 mutation (b) mean anything, and missing from the
/// plan: `any`'s own doc comment says it "short-circuits, which is why it is
/// not written over `fold`", but neither the plan's Step 1 test nor
/// `iterator_map_default_method_is_lazy_over_a_side_effecting_source` above
/// observes that. Step 1's two `any` calls match on the *last* element (`3`)
/// or not at all, so a full scan and a short-circuiting scan return the same
/// `Bool` either way — the mutation the plan itself prescribes (rewriting
/// `any` over `fold`, which visits every element) is invisible to every test
/// this task otherwise has. Without this, mutation (b) would be applied,
/// "pass" against the existing suite, and be reported as caught when it was
/// not — exactly the false confidence the quality bar warns about.
///
/// `CountingSrc` prints on every `next`, same technique as the `map` laziness
/// test above but with the match in the *middle* (`n > 1` first matches at
/// `2` of `0..5`) rather than at an edge, so a short-circuiting `any` prints
/// exactly `pull 0`, `pull 1`, `pull 2` and stops, where a full scan (e.g.
/// `any` rewritten over `fold`) would also print `pull 3` and `pull 4` before
/// the same `true`.
///
/// `src` is deliberately **not** `mut` (unlike an earlier round of this
/// test), and that is not merely "no longer necessary" — it is the point of
/// keeping it this way. Dropping `mut self` from `any` relaxed *two* of
/// `place_root`'s classifications, not only the temporary-receiver one this
/// whole design targeted: a caller's own binding no longer has to be declared
/// `mut` either. So this test doubles as the pin for that: a non-`mut` `src`
/// is silently advanced by `.any()` below with no diagnostic, which is
/// accepted, current behavior — not an oversight, and not something a future
/// change should tighten back to `E0060` without a deliberate decision to do
/// so. Also re-run after the `mut self` -> `self` design change specifically
/// to confirm the short-circuit itself survived the receiver rebinding
/// (`let mut it = self`, which sits directly in the path this test
/// exercises); the expected stdout is unchanged from before that change.
#[test]
fn iterator_any_short_circuits_and_does_not_scan_past_the_first_match() {
    let src = "record CountingSrc { n: Int, max: Int }\n\
               impl Iterator for CountingSrc {\n\
                   type Item = Int\n\
                   fn next(mut self) -> Option<Int> {\n\
                       if self.n >= self.max { return None }\n\
                       println(\"pull ${self.n}\")\n\
                       let x = self.n\n\
                       self.n = self.n + 1\n\
                       Some(x)\n\
                   }\n\
               }\n\
               fn main() {\n\
                   let src = CountingSrc { n: 0, max: 5 }\n\
                   println(\"${src.any(|n| n > 1)}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-any-short-circuits");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("pull 0\npull 1\npull 2\ntrue\n");
}

/// A design question carried from Task 2's review, not merely assumed:
/// `fold`/`any`/`collect` are default methods on `Iterator` itself, so their
/// bodies see `Self` at `Param(0)` (`crates/nova-typeck/src/check.rs`, the
/// `MethodOwner::TraitDefault` arm) exactly as a free function's own bounded
/// type parameter does. Task 3's mutation testing already observed the
/// diagnostic name for that placeholder directly — `` `Option<T0::Item>` `` in
/// Finding 8 of `task-3-report.md` — and Task 2 documented that a generic
/// `fn f<T: Iterator>(mut it: T)` binds its loop variable at that same
/// unnormalized projection, so an operation requiring `T::Item` concretely
/// (`n + x`, string interpolation) is `E0010`/`E0013` there — not a
/// regression, since the hand-written `while`+`match` equivalent behaves
/// identically.
///
/// So: do `fold`, `any` and `collect` actually work when called on a
/// *generic* `I: Iterator`, not only on a concrete `VecIter`, given that
/// their own signatures name `Self::Item` in a parameter or return type the
/// same way `first_or`'s `dflt: I::Item` does in
/// `a_generic_function_over_iterator_resolves_item_per_instantiation`? Answer,
/// measured directly rather than inferred from the above: **yes, as long as
/// the item is used opaquely.** `count_via_fold` never inspects `x` (`|a, x|
/// a + 1`), `any_via_generic` never inspects it either (`|x| true`), and
/// `len_via_collect` only calls `.len()` on the `Vec<I::Item>` `collect`
/// hands back — none of that requires `I::Item` to resolve to anything
/// concrete, so all three type-check, monomorphize and run correctly. Trying
/// to use the item concretely inside such a generic helper — `|a, x| a + x`,
/// or interpolating `x` — reproduces the exact `T0::Item`/E0010 and
/// `?0`/E0013 shapes Task 2 and Task 3 already documented, confirmed by
/// hand-testing both during this task. That does mean `v.iter().map(f)
/// .fold(...)` works while a generic
/// `fn sums<I: Iterator>(mut it: I) -> Int { it.fold(0, |a, x| a + x) }`
/// does not — a real, pre-existing gap, worth stating plainly rather than
/// leaving implicit.
///
/// **Correction, caught in review:** an earlier round of this comment claimed
/// the negative case above was "not re-pinned here since Task 2's own test
/// already owns that limitation." It does not, and nothing anywhere pinned
/// it: `a_generic_function_over_iterator_resolves_item_per_instantiation`
/// (Task 2) is purely positive — `I::Item` flows through `first`/`first_or`'s
/// signatures and is returned or matched, never operated on concretely — so
/// no existing test asserted the negative case failed, only that this task's
/// own hand-testing observed it once and moved on.
/// `a_generic_iterator_bound_cannot_use_its_item_concretely_in_fold`, below,
/// closes that.
///
/// None of the three helpers below declare `mut it: I` any more (an earlier
/// round of this test did): `fold`/`any`/`collect` take plain `self` now, so
/// nothing here requires the caller's own parameter to already be a mutable
/// place either.
#[test]
fn iterator_default_methods_work_through_a_generic_iterator_bound() {
    let src = "fn count_via_fold<I: Iterator>(it: I) -> Int {\n\
                   it.fold(0, |a, x| a + 1)\n\
               }\n\
               fn any_via_generic<I: Iterator>(it: I) -> Bool {\n\
                   it.any(|x| true)\n\
               }\n\
               fn len_via_collect<I: Iterator>(it: I) -> Int {\n\
                   it.collect().len()\n\
               }\n\
               fn main() {\n\
                   let mut v = Vec::new()\n\
                   v.push(1)\n\
                   v.push(2)\n\
                   v.push(3)\n\
                   println(\"${count_via_fold(v.iter())}\")\n\
                   println(\"${any_via_generic(v.iter())}\")\n\
                   println(\"${len_via_collect(v.iter())}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-default-methods-generic-bound");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("3\ntrue\n3\n");
}

/// The negative half of the design question above, pinned rather than only
/// described. Task 2 documented (and this task's own hand-testing
/// re-confirmed) that a generic `fn f<T: Iterator>(mut it: T)` binds a value
/// of type `T::Item` at the unnormalized projection, so an operation
/// requiring it concretely — here, `+` inside `fold`'s own closure — is
/// `E0010` naming that projection by its internal placeholder (`T0::Item`,
/// the same name Task 3's mutation testing observed independently in a
/// different diagnostic). Not a regression: the hand-written `while`+`match`
/// equivalent behaves identically, and this was true before Task 4 added a
/// single default method. Pinned so a future change to how generic default
/// methods normalize `Self::Item` either keeps failing this exact way on
/// purpose, or flips this assertion deliberately — not silently, in either
/// direction.
#[test]
fn a_generic_iterator_bound_cannot_use_its_item_concretely_in_fold() {
    let src = "fn sum_via_fold<I: Iterator>(it: I) -> Int {\n\
                   it.fold(0, |a, x| a + x)\n\
               }\n\
               fn main() {}";
    let dir = std::env::temp_dir().join("nova-iterator-generic-item-not-concrete");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    let assert = nova().arg("check").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("error[E0010]") && stderr.contains("T0::Item"),
        "stderr: {stderr}"
    );
}

/// The design this task was chosen on, pinned at exactly the shape a user
/// will write: `v.iter().filter(…).map(…).collect()` as one expression, no
/// intermediate binding anywhere in the chain. This was `E0060` (`collect`
/// mutates its receiver, which cannot be a temporary) until `fold`/`count`/
/// `any`/`collect` moved from `mut self` to plain `self`, each rebinding
/// internally (`let mut it = self`) instead of requiring the caller to have
/// already named a mutable place — `trait Iterator`'s own doc comment above
/// `fold` (`std/core/lib.nova`) explains why. Deliberately narrower than
/// `iterator_default_methods_work_and_chain` above (which exercises all six
/// methods and several values at once): this test's only job is to fail
/// loudly and specifically if the advertised chained form ever stops
/// compiling, rather than being one assertion among many in a larger test.
///
/// The second chain closes a coverage gap review found: `collect` is the one
/// new method whose own *return type* names the projection
/// (`Vec<Self::Item>`), which makes it the most exposed of the six to the
/// monomorphization seam — `mir_ty` collapses `Int`/`Char` into `MirTy::I64`
/// and `String`/`Fn`/`Sum`/`Record`/`Array` into `MirTy::Ptr`, and since `Ptr`
/// is `i64` on x86-64 those two classes are the same machine width (they do
/// stay distinct at codegen). `Bool` is `I8` and `Float` is `F64`, disjoint
/// from both, so only those two actually discriminate
/// a wrong item type from a coincidentally-right one (the same reasoning
/// Task 3 applied to its own chain, and the brief applied to `any` above but
/// never to `collect`). Every `collect` call elsewhere in this task's tests
/// collects `Int`; this one collects `Bool` instead
/// (`v.iter().map(|n| n > 2)`), so a `collect` that silently forwarded the
/// source's `Int` items instead of the mapped `Bool` ones has something to go
/// visibly wrong.
#[test]
fn iterator_adapter_chain_compiles_and_runs_as_a_single_expression() {
    let src = "fn main() {\n\
      let mut v = Vec::new()\n\
      v.push(1)\n\
      v.push(2)\n\
      v.push(3)\n\
      let got = v.iter().filter(|n| n > 1).map(|n| n * 10).collect()\n\
      println(\"${got.len()}\")\n\
      println(\"${got.get(0).unwrap()}\")\n\
      let bools = v.iter().map(|n| n > 2).collect()\n\
      println(\"${bools.len()}\")\n\
      println(\"${bools.get(2).unwrap()}\")\n\
    }";
    let dir = std::env::temp_dir().join("nova-iterator-chain-single-expression");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("2\n20\n3\ntrue\n");
}

/// The go/no-go check for the `mut self` -> `self` design change: `fold`,
/// `count`, `any` and `collect` now rebind their receiver internally
/// (`let mut it = self`) instead of requiring the caller's own binding to
/// already be mutable. Records are heap objects with no copy semantics
/// anywhere in this compiler (grepped for "moved value"/"use after move"/
/// "linear type"/"affine type" across every crate during Task 4's original
/// work; zero hits), so `it` is expected to alias exactly the storage `self`
/// pointed to rather than copy it — but "expected" is not "verified," and
/// this is precisely the kind of change a silent value-copy would make look
/// identical for every test that only checks a consumer's *return* value.
///
/// `Cursor` exposes its own cursor field (`n`) directly, so this reads the
/// iterator's storage back out through the *original* binding after a
/// consumer has run on it, rather than inferring aliasing indirectly through
/// a second `.next()` call. Two consumers, deliberately different: `any`
/// short-circuits (stops at the first match, `x > 1` first true at `2`), so
/// `a.n` reading `3` afterward (not `0`, a copy; not `5`, a full scan) proves
/// aliasing *and* confirms the short-circuit itself survived the receiver
/// rebinding, in one assertion. `count` runs to exhaustion, so `b.n` reading
/// `3` afterward confirms the same aliasing on the other kind of consumer —
/// one that always visits every element rather than stopping early.
#[test]
fn an_iterators_own_storage_still_advances_when_a_consumer_takes_plain_self() {
    let src = "record Cursor { n: Int, max: Int }\n\
               impl Iterator for Cursor {\n\
                   type Item = Int\n\
                   fn next(mut self) -> Option<Int> {\n\
                       if self.n >= self.max { return None }\n\
                       let x = self.n\n\
                       self.n = self.n + 1\n\
                       Some(x)\n\
                   }\n\
               }\n\
               fn main() {\n\
                   let mut a = Cursor { n: 0, max: 5 }\n\
                   println(\"${a.any(|x| x > 1)}\")\n\
                   println(\"${a.n}\")\n\
                   let mut b = Cursor { n: 0, max: 3 }\n\
                   println(\"${b.count()}\")\n\
                   println(\"${b.n}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-consumer-aliases-storage");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("true\n3\n3\n3\n");
}

/// `continue` inside `for x in <an iterator>`. Nothing covered it anywhere:
/// `tests/runtime/break_continue.nova` is range-only and `tests/runtime/
/// iterator.nova` has no `continue` at all. Written here rather than added to
/// that fixture so the gate's checked-in `.stdout` stays untouched.
///
/// Worth its own test because the two `for` desugars get this right by
/// *opposite* mechanisms, so a test of one says nothing about the other. The
/// range form has to deliberately hoist its increment above the body, precisely
/// because a `continue` would otherwise jump past it (its own comments in
/// `check_for_range`, `crates/nova-typeck/src/check.rs`, say so). The iterator
/// form gets it for free: `next()` is the `match` scrutinee, so it sits *in* the
/// body and a `continue` re-enters through it. That freeness is fragile in a
/// specific, plausible way: hoisting `next()` out of the body so the `while true`
/// placeholder can carry a real condition forces the advance to the *end* of the
/// body, which is exactly where a `continue` jumps past it — the range desugar's
/// hazard, imported. That restructure is a refactor rather than a one-line
/// mutation, so it was **not** run here; what was measured is narrower and
/// enough to justify the test. Removing `check_for_iterator`'s
/// `fcx.loop_depth` bracket fails this test and
/// `a_map_iter_calls_f_lazily_not_all_up_front` and nothing else in the
/// workspace — so `break` in this position already had exactly one pin, and
/// `continue` had none anywhere: before this test the only `continue` in any
/// fixture or suite was over an integer *range*.
///
/// `break` is exercised in the same loop, and the totals discriminate: skipping
/// `2` and stopping before `4` gives `1 + 3 = 4`, which no other combination of
/// "continue ignored" (`1+2+3 = 6`), "break ignored" (`1+3+4+5 = 13`) or "both
/// ignored" (`15`) produces. The element counter separates a `continue` that
/// skipped the rest of the body from one that skipped the *iteration*.
#[test]
fn continue_and_break_work_inside_a_for_loop_over_an_iterator() {
    let src = "fn main() {\n\
                   let mut v = Vec::new()\n\
                   v.push(1)\n\
                   v.push(2)\n\
                   v.push(3)\n\
                   v.push(4)\n\
                   v.push(5)\n\
                   let mut total = 0\n\
                   let mut seen = 0\n\
                   for x in v.iter() {\n\
                       seen = seen + 1\n\
                       if x == 2 { continue }\n\
                       if x == 4 { break }\n\
                       total = total + x\n\
                   }\n\
                   println(\"total=${total} seen=${seen}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-for-continue");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("total=4 seen=4\n");
}

/// `for x in it` where `it: I` is a **generic parameter bounded by `Iterator`**.
/// Nothing covered it: `a_generic_function_over_iterator_resolves_item_per_
/// instantiation` above drives `next()` by hand, and every `for`-over-iterator
/// test binds a concrete receiver.
///
/// It is the one `for` path whose loop variable binds at an **unnormalized**
/// projection. `check_for_iterator` reads the item type off `next`'s result with
/// a raw `payload.subst(&args)` — correct by design, since inside a generic
/// function there is no impl to normalize against yet — so `x`'s type stays
/// `Assoc { on: Param(i) }` all the way to monomorphization, and seam 3 is the
/// only thing that ever resolves it. That is exactly the configuration whose
/// failure mode was this area's worst historical bug: a projection reaching
/// `mir_ty` as `MirTy::Unit`, which drops the parameter from the Cranelift
/// signature rather than reporting anything.
///
/// **Instantiated at `Bool` and at `Float`, not just `Int`.** `mir_ty` maps
/// `Int` and `Char` to `I64` and every heap type to `Ptr` (also `i64` on
/// x86-64), so an `Int` item type is the weakest possible choice — a wrong
/// answer hides inside its own machine class. `Bool` is `I8` and `Float` is
/// `F64`; `Float` is the strictly stronger of the two, because it crosses
/// register banks, where `Bool`'s only values (0 and 1) survive an `I64`
/// confusion intact.
///
/// Two shapes, because counting alone would not notice a wrong item type.
/// `count_via_for` only increments, so it pins that the loop *runs* the right
/// number of times over a bounded generic. `first_via_for` carries the loop
/// variable back out at `Option<I::Item>` and lets `main` consume it
/// concretely — `if b.unwrap()` needs a real `Bool` and `${f.unwrap()}`
/// dispatches `Display` on a real `Float`. The `Bool` source yields `true`
/// first on purpose: a payload dropped or zeroed by a `MirTy::Unit` item type
/// would read back as `false`, so `true` is the value that cannot be faked.
#[test]
fn a_for_loop_over_a_generic_iterator_bound_binds_its_item_at_each_instantiation() {
    let src = "record BoolSrc { n: Int }\n\
               impl Iterator for BoolSrc {\n\
                   type Item = Bool\n\
                   fn next(mut self) -> Option<Bool> {\n\
                       if self.n >= 3 { return None }\n\
                       self.n = self.n + 1\n\
                       Some(self.n == 1)\n\
                   }\n\
               }\n\
               record FloatSrc { n: Int }\n\
               impl Iterator for FloatSrc {\n\
                   type Item = Float\n\
                   fn next(mut self) -> Option<Float> {\n\
                       if self.n >= 2 { return None }\n\
                       self.n = self.n + 1\n\
                       Some(2.5)\n\
                   }\n\
               }\n\
               fn first_via_for<I: Iterator>(it: I) -> Option<I::Item> {\n\
                   for x in it { return Some(x) }\n\
                   None\n\
               }\n\
               fn count_via_for<I: Iterator>(it: I) -> Int {\n\
                   let mut n = 0\n\
                   for x in it { n = n + 1 }\n\
                   n\n\
               }\n\
               fn main() {\n\
                   let b = first_via_for(BoolSrc { n: 0 })\n\
                   if b.unwrap() { println(\"bool=true\") } else { println(\"bool=false\") }\n\
                   let f = first_via_for(FloatSrc { n: 0 })\n\
                   println(\"float=${f.unwrap()}\")\n\
                   println(\"bools=${count_via_for(BoolSrc { n: 0 })}\")\n\
                   println(\"floats=${count_via_for(FloatSrc { n: 0 })}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-iterator-for-generic-bound");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("bool=true\nfloat=2.5\nbools=3\nfloats=2\n");
}

/// Iteration end-to-end gate (Phase 2.2d, Task 5). One program covering every
/// item of the increment's gate list — `for` over a `Vec` via `.iter()`, `for`
/// over an integer range (a regression guard, since Task 2 rewrote the function
/// that dispatches a `for` head), exhaustion plus one further `next()`, an
/// empty source whose *first* `next()` is already `None`, a two-stage
/// `.filter().map()` chain, all six default methods, and every generic block
/// instantiated at `Bool` **and** at `Float`.
///
/// That last item is the load-bearing one and the reason this fixture is not
/// simply the `Int` pipeline a reader would write first. `mir_ty` maps `Int`
/// *and* `Char` to `MirTy::I64` and `String`/`Fn`/`Record`/`Sum`/`Array` to
/// `MirTy::Ptr` — `pointer_type()`, `types::I64` on x86-64 — so at the level a
/// backend can see, `Int`, `Char`, `String` and every heap type are one type,
/// and an `Item` resolved to the wrong one of them is invisible after
/// lowering. Only `Bool` (`I8`) and `Float` (`F64`) have machine classes a
/// wrong answer cannot hide in. `tests/runtime/assoc_types.nova`'s header
/// records the measurement that established this; this fixture's own header
/// carries its mutation-to-line map.
#[test]
fn iterator_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/iterator.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/iterator.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through the object-file backend. Not redundant with
/// `iterator_run` for the reason `strings_build_standalone`'s comment gives —
/// `nova run` resolves runtime symbols through `nova_runtime::symbols()` while
/// `nova build` links `nova_runtime.lib` by export name and never consults that
/// table — and for one specific to this gate: an `Item` resolved to the wrong
/// machine class fails in **code generation**, not in the type checker, so the
/// two backends are the two places it can fail differently.
#[test]
fn iterator_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/iterator.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/iterator.nova", "iterator");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// The same fixture with `NOVA_GC_STRESS=1` (collect on every allocation) — a
/// gate criterion, not belt-and-braces. A `.filter().map()` chain is a *tower*
/// of records, so the backing array is reachable only as
/// `MapIter` -> `FilterIter` -> `VecIter` -> `Vec` -> `data` while every `next`
/// allocates a fresh `Option` and `collect` grows a `Vec` — a strictly deeper
/// rooting chain than `assoc_types_under_gc_stress`'s three levels. The
/// collector scans the stack plus callee-saved registers, which is what makes
/// an adapter held across a call a root; a missed root at any link loses
/// elements silently rather than crashing.
#[test]
fn iterator_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/iterator.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/iterator.nova"))
        .assert()
        .success()
        .stdout(expected);
}

// === Task 5 Step 6a: the three cases ADR 0007 section 1's safety argument
// rests on, none of which had a test.
//
// A bound on a record's type parameter is a **resolution scope, not a
// constraint** (ADR 0007): it makes a projection nameable in a field type and
// is not itself checked when the record is built. That decision is only
// defensible because of what happens instead — and "what happens instead" was
// written down twice before it was measured, wrong both times (first as a
// uniform `E0014`, then as a uniform `E0013`). It is not uniform. It is three
// different answers depending on whether the bound reaches a field type, and
// the third of them is a hole.
//
// All three need monomorphization, so none can be a `check_src` unit test in
// `nova-typeck`: `E0079` and `E0013` are both raised in `nova-mir`'s `mono`,
// after typeck has finished, and case 3 has to run to completion.

/// **Case 1 — the shape the stdlib actually ships, and the one that was
/// entirely unpinned.** `MapIter`/`FilterIter` carry a bound *because a field
/// type names a projection on it* (`f: fn(I::Item) -> U`). Substituting
/// `I := Int` leaves `Int::Item` in that field's declared type, nothing binds
/// `Item` for `Int`, and monomorphization rejects it — `E0079`, the
/// surviving-projection check built in Phase 2.2c Task 7.
///
/// Asserted **without driving the iterator**, because firing at *construction*
/// is the property. That makes the real behaviour earlier and stronger than
/// "the bound is unenforced" suggests, and it is why the ADR does not have to
/// argue that a bogus `MapIter` is merely inert: for this shape it cannot be
/// built at all.
///
/// Checked by the `Int::Item` spelling, not only by the code: `E0079` is also
/// the backstop for a projection surviving mono by any other route, so the code
/// alone would not distinguish this cause from that one.
#[test]
fn a_wrong_instantiation_of_a_projection_shaped_record_is_e0079_at_construction() {
    // No `.next()`, no `for`, no consumer — the value is built and dropped.
    let src = "fn main() {\n\
                   let m = MapIter { it: 5, f: |x| x }\n\
                   println(\"built\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-record-bound-e0079");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("error[E0079]") && stderr.contains("`Int::Item`"),
        "stderr: {stderr}"
    );
    // And it really is at construction: nothing ran.
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).to_string();
    assert!(
        !stdout.contains("built"),
        "rejected before `main` ran: {stdout}"
    );
}

/// **Case 2 — the bound reaches no field type, but is exercised through a
/// bounded impl method.** `Boxed<K: Hash + Eq, V>`'s bound is inert on the
/// record itself (neither `k: K` nor `v: V` names a projection), so nothing
/// stops `Boxed { k: NoHash { .. }, v: 7 }` being built. The
/// `impl<K: Hash + Eq, V>` block's bound is real, and instantiating `key` with
/// a `K` implementing neither trait is `E0013` — one diagnostic per unsatisfied
/// bound.
///
/// This is the shape an earlier round of the plan transcribed onto `MapIter`
/// and got wrong. `E0013` *was* measured, but on a record whose field types
/// name no projection, so case 1's earlier and stricter `E0079` never fires
/// here. Different shape, different diagnostic — which is why both are pinned
/// rather than one standing in for the other.
///
/// Asserted on the **bound spelling** (NoHash: Hash), not just the code:
/// `E0013` is the code for every unsatisfied bound in the language, so the code
/// alone would still pass if the diagnostic named the wrong trait or the wrong
/// type. Both bounds are checked, since reporting only the first would be a
/// silent regression in a diagnostic whose whole value is completeness.
#[test]
fn an_unused_record_bound_is_still_enforced_through_a_bounded_impl_method() {
    let src = "record Boxed<K: Hash + Eq, V> { k: K\n\
               v: V }\n\
               impl<K: Hash + Eq, V> Boxed<K, V> {\n\
                   fn key(self) -> K { self.k }\n\
               }\n\
               record NoHash { z: Int }\n\
               fn main() {\n\
                   let b = Boxed { k: NoHash { z: 1 }, v: 7 }\n\
                   let k = b.key()\n\
                   println(\"${k.z}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-record-bound-e0013");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("error[E0013]") && stderr.contains("`NoHash: Hash`"),
        "stderr: {stderr}"
    );
    assert!(
        stderr.contains("`NoHash: Eq`"),
        "one diagnostic per unsatisfied bound, not just the first: {stderr}"
    );
}

/// **Case 3 — the residual hole, pinned as accepted.** The same `Boxed`, the
/// same non-conforming `K`, but only the *unbounded* field is read, so no
/// bounded method is ever instantiated. It compiles, runs and prints. No
/// diagnostic anywhere.
///
/// So the claim "a bogus instantiation is never silently useless" — which an
/// earlier round of this plan asserted — is **false**, and this test is what
/// stops that being rediscovered as a bug. It also stops a future enforcement
/// change landing silently: threading type arguments through `MakeRecord` would
/// turn this program into an error, which should be a deliberate act with a
/// test to change rather than a quiet tightening.
///
/// Success is asserted **explicitly**, on the exact stdout. A test that merely
/// omitted an error assertion would also pass if the program failed to compile
/// for some unrelated reason.
#[test]
fn a_record_bound_no_field_type_uses_is_silently_accepted_when_never_exercised() {
    let src = "record Boxed<K: Hash + Eq, V> { k: K\n\
               v: V }\n\
               impl<K: Hash + Eq, V> Boxed<K, V> {\n\
                   fn key(self) -> K { self.k }\n\
               }\n\
               record NoHash { z: Int }\n\
               fn main() {\n\
                   let b = Boxed { k: NoHash { z: 1 }, v: 7 }\n\
                   println(\"${b.v}\")\n\
               }";
    let dir = std::env::temp_dir().join("nova-record-bound-accepted");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, src).expect("write");
    nova()
        .arg("run")
        .arg(&path)
        .assert()
        .success()
        .stdout("7\n");
}

// === nova test: the synthesized dispatching `main` (Task 3) ===

/// The synthesized `main` with no `NOVA_TEST_INDEX` set prints the
/// inventory: a count line, then one name per line. This is how `nova test`
/// (Task 5) will enumerate tests without a second compilation, and it is
/// also what a human gets by running the binary directly with no variable
/// set.
///
/// Asserts **exact** stdout, not `contains`. The mutation table this task
/// carries includes `unwrap_or(0)` in place of `unwrap_or(-1)` inside
/// `nova_rt_test_selector`, which makes a bare run silently execute test 0
/// (`alpha`) instead of printing the inventory. Verified directly: under
/// that mutation, stdout goes from `"2\nalpha\nbeta\n"` to `""` (`alpha`'s
/// own body is empty), which this exact-equality assertion correctly fails
/// on.
#[test]
fn a_test_binary_with_no_index_prints_its_inventory() {
    let dir = std::env::temp_dir().join("nova-test-inventory");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("inventory.nova");
    std::fs::write(&file, "@test\nfn alpha() { }\n@test\nfn beta() { }\n").expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["alpha", "beta"],
        "collection order feeds the printed inventory directly"
    );

    let assert = Command::new(&exe)
        .env_remove("NOVA_TEST_INDEX")
        .assert()
        .success();
    let out = String::from_utf8(assert.get_output().stdout.clone())
        .expect("stdout is UTF-8")
        .replace("\r\n", "\n");
    assert_eq!(out, "2\nalpha\nbeta\n");
    let _ = std::fs::remove_file(&exe);
}

/// `NOVA_TEST_INDEX=1` runs the second collected test and nothing else. The
/// two tests print distinguishable markers, so running the wrong one — or
/// both — is visible rather than merely a wrong count.
///
/// Asserts stdout is **exactly** `"B\n"`, not merely that `"B"` appears.
/// Asserting presence alone would still pass if the dispatch ran *both*
/// `alpha` and `beta` (stdout `"A\nB\n"` contains `"B"`), which is exactly
/// the failure mode a mutated dispatch condition (e.g. comparing `sel + 1`
/// against each index instead of `sel`) must be caught producing. Exact
/// equality both asserts the selected test's output and stands in for a
/// separate "and `A` is absent" check: no string equal to `"B\n"` also
/// contains `"A"`.
#[test]
fn a_test_binary_runs_exactly_the_selected_test() {
    let dir = std::env::temp_dir().join("nova-test-selected");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("selected.nova");
    std::fs::write(
        &file,
        "@test\nfn alpha() { println(\"A\") }\n\
         @test\nfn beta() { println(\"B\") }\n",
    )
    .expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["alpha", "beta"],
        "index 1 below selects beta only if collection order is [alpha, beta]"
    );

    let assert = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "1")
        .assert()
        .success();
    let out = String::from_utf8(assert.get_output().stdout.clone())
        .expect("stdout is UTF-8")
        .replace("\r\n", "\n");
    assert_eq!(out, "B\n");
    let _ = std::fs::remove_file(&exe);
}

/// A source file with both `@test` functions and its own `fn main()` must
/// still run the selected test, not the user's `main`. Before this fix,
/// `build_test_binary` appended the synthesized dispatcher to the *end* of
/// `module.functions`, but `nova-mir/src/mono.rs`'s entry-point search
/// (`.iter().find(|f| f.name == "main")`) takes the *first* match — so an
/// earlier user `main` won, compiled and linked cleanly with no diagnostic
/// anywhere, and the dispatcher became dead code mono never even emitted.
/// `nova build`/`nova run` *require* a `main` (`E0601`), so a program with
/// both tests and an entry point is the unremarkable case, not an edge one.
#[test]
fn a_test_binary_runs_the_selected_test_not_the_users_own_main() {
    let dir = std::env::temp_dir().join("nova-test-user-main");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("user_main.nova");
    std::fs::write(
        &file,
        "@test\nfn alpha() { println(\"TEST-RAN\") }\n\
         fn main() { println(\"USER-MAIN-RAN\") }\n",
    )
    .expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["alpha"]
    );

    let assert = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "0")
        .assert()
        .success();
    let out = String::from_utf8(assert.get_output().stdout.clone())
        .expect("stdout is UTF-8")
        .replace("\r\n", "\n");
    assert_eq!(out, "TEST-RAN\n");
    let _ = std::fs::remove_file(&exe);
}

/// Two different source files that happen to share a file stem — `main.nova`
/// is overwhelmingly the common fixture name, including 50-plus occurrences
/// in this very file — must not collide on `build_test_binary`'s output
/// path. Before this fix the output path was derived from the stem alone
/// inside one shared directory, so two different `main.nova` files (in two
/// different directories, as they always are among real fixtures) resolved
/// to the identical path — a real race under `cargo test`'s default
/// parallelism, and one Task 5's runner (which builds several fixtures)
/// would hit directly.
#[test]
fn test_binary_output_paths_do_not_collide_across_same_stem_sources() {
    let dir_a = std::env::temp_dir().join("nova-test-stem-collision-a");
    let dir_b = std::env::temp_dir().join("nova-test-stem-collision-b");
    std::fs::create_dir_all(&dir_a).expect("temp dir a");
    std::fs::create_dir_all(&dir_b).expect("temp dir b");
    let file_a = dir_a.join("main.nova");
    let file_b = dir_b.join("main.nova");
    std::fs::write(&file_a, "@test\nfn from_a() { }\n").expect("write a");
    std::fs::write(&file_b, "@test\nfn from_b() { }\n").expect("write b");

    let (exe_a, _) = nova_driver::build_test_binary(&file_a).expect("a compiles and links");
    let (exe_b, _) = nova_driver::build_test_binary(&file_b).expect("b compiles and links");

    assert_ne!(
        exe_a, exe_b,
        "two different main.nova files must not share an output path"
    );
    assert!(exe_a.exists(), "a's binary exists at {}", exe_a.display());
    assert!(exe_b.exists(), "b's binary exists at {}", exe_b.display());
    let _ = std::fs::remove_file(&exe_a);
    let _ = std::fs::remove_file(&exe_b);
}

// === std/test: assert, assert_eq, assert_ne (Task 4) ===

/// `assert_eq` must report BOTH values. A message that dropped one would
/// still look like a failure report, and every other assertion in std/test
/// would still "work" — so this asserts on the rendered text, not just that
/// the process panicked.
///
/// Asserts the message is **exactly** `"nova: panic: assertion failed: 1 !=
/// 3"`, not `contains("1") && contains("3")`. Those are single characters and
/// would match a line number, a byte offset, a file path, or the test index
/// too, so a two-fragment `contains` check passes against a completely
/// garbled message. This is the defect that has produced every Important
/// finding on this branch so far.
#[test]
fn assert_eq_failure_names_both_values() {
    let dir = std::env::temp_dir().join("nova-test-assert-eq-both-values");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("both_values.nova");
    std::fs::write(&file, "@test\nfn t() { assert_eq(1, 3) }\n").expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["t"]
    );

    let assert = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "0")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).replace("\r\n", "\n");
    assert_eq!(
        stderr.trim_end(),
        "nova: panic: assertion failed: 1 != 3",
        "stderr: {stderr}"
    );
    let _ = std::fs::remove_file(&exe);
}

/// `assert_eq<T: Eq + Debug>` instantiated at `Bool` and `Float`, not only
/// `Int`. `mir_ty` maps `Int` and `Char` to `MirTy::I64` and every heap type
/// to `MirTy::Ptr`, so only `Bool` (`I8`) and `Float` (`F64`) are disjoint
/// from both — and `Float` is the stronger of the two because it crosses
/// register banks while `Bool`'s 0/1 would survive an `I64` mix-up intact.
/// `String` is included too, since it is the one heap type whose `Debug`
/// output (quoted) differs textually from its `Display` output.
///
/// Each type gets a PASSING case and a FAILING one. Passing cases alone prove
/// nothing: `assert_eq(1, 1)`, `(true, true)`, `(0.5, 0.5)` and `("a", "a")`
/// all succeed even if `assert_eq` never compares its arguments — implement
/// `Eq::ne` as `{ false }` and every one of them still passes. The failing
/// case is what proves the comparison actually happened; the passing case
/// only proves it does not fire spuriously.
#[test]
fn assert_eq_works_at_bool_and_float_not_only_int() {
    let dir = std::env::temp_dir().join("nova-test-assert-eq-types");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("types.nova");
    std::fs::write(
        &file,
        "@test\nfn int_pass() { assert_eq(1, 1) }\n\
         @test\nfn int_fail() { assert_eq(1, 2) }\n\
         @test\nfn bool_pass() { assert_eq(true, true) }\n\
         @test\nfn bool_fail() { assert_eq(true, false) }\n\
         @test\nfn float_pass() { assert_eq(0.5, 0.5) }\n\
         @test\nfn float_fail() { assert_eq(0.5, 1.5) }\n\
         @test\nfn string_pass() { assert_eq(\"a\", \"a\") }\n\
         @test\nfn string_fail() { assert_eq(\"a\", \"b\") }\n",
    )
    .expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec![
            "int_pass",
            "int_fail",
            "bool_pass",
            "bool_fail",
            "float_pass",
            "float_fail",
            "string_pass",
            "string_fail",
        ],
        "collection order fixes which index below selects which case"
    );

    // (index, expected panic message; `None` means this index must pass with
    // no output at all, since a passing `assert_eq` prints nothing).
    let cases: [(usize, Option<&str>); 8] = [
        (0, None),
        (1, Some("nova: panic: assertion failed: 1 != 2")),
        (2, None),
        (3, Some("nova: panic: assertion failed: true != false")),
        (4, None),
        (5, Some("nova: panic: assertion failed: 0.5 != 1.5")),
        (6, None),
        (7, Some("nova: panic: assertion failed: \"a\" != \"b\"")),
    ];

    for (index, expected_panic) in cases {
        let assert = Command::new(&exe)
            .env("NOVA_TEST_INDEX", index.to_string())
            .assert();
        match expected_panic {
            None => {
                let assert = assert.success();
                let out = String::from_utf8_lossy(&assert.get_output().stdout).to_string();
                assert_eq!(
                    out, "",
                    "a passing assert_eq must print nothing (index {index})"
                );
            }
            Some(msg) => {
                let assert = assert.failure();
                let stderr =
                    String::from_utf8_lossy(&assert.get_output().stderr).replace("\r\n", "\n");
                assert_eq!(stderr.trim_end(), msg, "index {index}");
            }
        }
    }
    let _ = std::fs::remove_file(&exe);
}

/// `assert`/`assert_eq`/`assert_ne` must NOT leak into an ordinary program:
/// `std/test` is seeded only under `nova test` (`build_test_binary`), not
/// into `nova run`/`nova check`/`nova build`. A top-level `pub fn assert` in
/// an always-embedded module would be glob-imported into every module of
/// every program and take the name away from user code permanently.
///
/// Asserts the diagnostic message NAMES `assert`, not just that the compile
/// failed with code `E0001` — a bare code check would pass against an
/// `E0001` raised for any unrelated reason (e.g. a typo the fixture didn't
/// intend to introduce).
#[test]
fn assert_is_not_available_outside_nova_test() {
    let dir = std::env::temp_dir().join("nova-test-assert-not-available");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let path = dir.join("main.nova");
    std::fs::write(&path, "fn main() { assert(true, \"x\") }\n").expect("write");

    let assert = nova().arg("run").arg(&path).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0001"), "stderr: {stderr}");
    assert!(
        stderr.contains("cannot find function `assert` in this scope"),
        "stderr: {stderr}"
    );
}

/// `assert(cond, msg)` panics with exactly `msg` when `cond` is false, and is
/// silent when `cond` is true. Both cases are needed: a passing-only test
/// would not catch `assert`'s condition being inverted (`if cond` instead of
/// `if !cond`) — under that mutation `assert(true, ..)` panics and
/// `assert(false, ..)` does not, and neither case alone tells the two apart
/// from the correct behavior in a way an all-passing suite would notice.
#[test]
fn assert_panics_with_its_message_and_is_silent_when_true() {
    let dir = std::env::temp_dir().join("nova-test-assert-basic");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("basic.nova");
    std::fs::write(
        &file,
        "@test\nfn assert_pass() { assert(true, \"boom\") }\n\
         @test\nfn assert_fail() { assert(false, \"boom\") }\n",
    )
    .expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["assert_pass", "assert_fail"]
    );

    let pass = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "0")
        .assert()
        .success();
    let out = String::from_utf8_lossy(&pass.get_output().stdout).to_string();
    assert_eq!(out, "", "assert(true, ..) must print nothing");

    let fail = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "1")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&fail.get_output().stderr).replace("\r\n", "\n");
    assert_eq!(
        stderr.trim_end(),
        "nova: panic: assertion failed: boom",
        "stderr: {stderr}"
    );
    let _ = std::fs::remove_file(&exe);
}

/// `assert_ne(a, b)` panics with a message naming both (rendered with `==`,
/// since they are equal at the point it fires) when `a == b`, and is silent
/// when they differ. Both cases matter for the same reason `assert`'s do: a
/// swapped condition (`if a.eq(b)` written as `if a.ne(b)`, plausible as a
/// copy-paste from `assert_eq`'s body) would still compile and would still
/// pass an all-passing-inputs test.
#[test]
fn assert_ne_panics_when_equal_and_is_silent_when_different() {
    let dir = std::env::temp_dir().join("nova-test-assert-ne-basic");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("basic.nova");
    std::fs::write(
        &file,
        "@test\nfn ne_pass() { assert_ne(1, 2) }\n\
         @test\nfn ne_fail() { assert_ne(1, 1) }\n",
    )
    .expect("write");

    let (exe, tests) =
        nova_driver::build_test_binary(&file).expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["ne_pass", "ne_fail"]
    );

    let pass = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "0")
        .assert()
        .success();
    let out = String::from_utf8_lossy(&pass.get_output().stdout).to_string();
    assert_eq!(out, "", "assert_ne(1, 2) must print nothing");

    let fail = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "1")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&fail.get_output().stderr).replace("\r\n", "\n");
    assert_eq!(
        stderr.trim_end(),
        "nova: panic: assertion failed: 1 == 1",
        "stderr: {stderr}"
    );
    let _ = std::fs::remove_file(&exe);
}

// === nova test: the `nova test [filter]` CLI subcommand (Task 5) ===
//
// Unlike `run`/`build`/`check`, `nova test` takes no `[file]` argument
// (`nova-spec/40-TOOLING.md:20`: `nova test [filter]`) — it always compiles
// `src/main.nova` relative to the current directory, so every test below
// writes its fixture there and points `nova()` at that directory with
// `.current_dir`.

/// A project directory with `src/main.nova` containing `source`, under a
/// fresh, uniquely-named temp directory so parallel tests (and parallel runs
/// of this same suite) never share one `nova test` project.
fn write_test_project(unique_name: &str, source: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(unique_name);
    std::fs::create_dir_all(dir.join("src")).expect("temp project dir");
    std::fs::write(dir.join("src/main.nova"), source).expect("write fixture");
    dir
}

/// A passing test and a failing one, reported distinctly in one run: the
/// pass line says "ok", the failure line says "FAILED" and is followed by
/// the exact panic message, and the summary counts each into its own
/// bucket. Asserts the **entire** rendered stdout, not a substring of it —
/// this project's own retrospective (`2026-08-05-nova-test-design.md` §1)
/// found seven cases of a diagnostic checked by a single fragment that
/// would have matched a completely wrong message just as well.
#[test]
fn nova_test_reports_a_pass_and_a_failure_distinctly() {
    let dir = write_test_project(
        "nova-test-cli-pass-fail",
        "@test\nfn addition_works() { assert_eq(1 + 1, 2) }\n\
         @test\nfn addition_is_broken() { assert_eq(1 + 1, 3) }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test addition_works ... ok\n\
         test addition_is_broken ... FAILED\n\
         \x20\x20\x20\x20nova: panic: assertion failed: 2 != 3\n\
         \n\
         test result: FAILED. 1 passed; 1 failed; 0 trapped; 2 total\n"
    );
}

/// The `(code, hex)` pair `nova test`'s own report will show in its
/// `TRAPPED (exit code ...)` line, measured from a direct run of the same
/// compiled test binary. Shared by
/// `a_hard_trap_is_reported_as_a_trap_and_does_not_satisfy_should_panic` and
/// `a_trapping_tests_captured_output_is_shown_not_discarded` — both trap the
/// process the same way (a division by zero) and both need this pair to
/// build their expected string, so a divergence between them would only
/// mean one had bit-rotted.
///
/// On Windows a fault arrives as a concrete NTSTATUS, so `ExitStatus::code()`
/// is always `Some` and is returned verbatim — a real measurement, exactly
/// as both tests' own doc comments already describe (design doc §9 risk 4:
/// not portable, so measured rather than hard-coded).
///
/// On Unix, POSIX makes "exited normally" and "killed by a signal" mutually
/// exclusive, and a hard trap (a CPU-raised fault — SIGFPE, SIGILL, ...) is
/// the latter, so `.code()` is unconditionally `None` here: there is no code
/// to measure. `classify` (`crates/nova-cli/src/cmd/test.rs:112`) already
/// handles exactly this via `output.status.code().unwrap_or(-1)`, so `-1`
/// (`0xFFFFFFFF`) asserted below deliberately duplicates that production
/// constant rather than measuring anything — asserted because that is
/// genuinely what `nova test` will print, not because anything was
/// measured. That duplication still catches real regressions: `classify`
/// changing its fallback value, or the hex form being misrendered. What it
/// can no longer do is cross-check against a real reported status, because
/// a signal-terminated process on Unix never hands one back — this half is
/// strictly weaker than the Windows measurement above, not an equivalent
/// to it.
///
/// What IS asserted, and is why this does not degrade into a tautology that
/// passes for any nonzero exit: `.signal().is_some()` demands the process
/// was actually killed by a fatal signal. If a future change made this
/// program exit gracefully with some nonzero code instead of trapping,
/// `code()` would be `Some` and `signal()` `None`, and this assertion would
/// fail here — before either caller ever reaches its own comparison against
/// `nova test`'s reported output.
fn expect_trap_exit_code(status: &std::process::ExitStatus) -> (i32, u32) {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        assert!(
            status.signal().is_some(),
            "a hard trap must be killed by a fatal signal on Unix, not merely exit nonzero: {status:?}"
        );
        let code = -1i32;
        (code, code as u32)
    }
    #[cfg(windows)]
    {
        let code = status
            .code()
            .expect("a concrete exit code on this platform");
        (code, code as u32)
    }
}

/// The load-bearing test on this branch (design doc §5, §9 risk 4; brief
/// step 3). A division by zero exits nonzero with **no** `nova: panic:` line
/// on stderr — a hard trap, not a checked panic — measured directly below
/// rather than assumed. `@test(should_panic)` must NOT be satisfied by it:
/// the report must call it "TRAPPED", never "ok" or plain "FAILED", and the
/// summary must count it under `trapped`, not `passed` or `failed`.
///
/// Treating any nonzero exit as "panicked as expected" would let a
/// miscompile masquerade as a passing test. That is not hypothetical on this
/// project: `nova-typeck`'s
/// `a_next_returning_a_three_variant_sum_is_not_an_iterator` test documents a
/// real guard whose removal turned a clean type-check into exactly this
/// exit-132-on-legal-source shape.
///
/// The expected exit code is **measured directly on Windows**, not
/// hard-coded: the code an aborted process reports is platform- and
/// shell-dependent (design doc §9 risk 4 measured 127 and 132 for two
/// different aborts through Git Bash on this same project), so pinning a
/// literal number here would test one shell's translation of the exit code
/// rather than what `nova test` itself observed through Rust's own process
/// API. Measured once, independently, while building this test: the raw
/// code Windows reports for this exact program is `-1073741795`
/// (`0xC000001D`, `STATUS_ILLEGAL_INSTRUCTION` — Cranelift lowers a checked
/// `sdiv` with a `ud2`-style trap rather than letting the hardware `#DE`
/// fault propagate, which is also consistent with Git Bash's "Illegal
/// instruction" wording for the same program) — a different value from both
/// this project's own 127/132 Git Bash figures and this task's 0xC0000409 /
/// 0xC0000005 figures, because none of the three measured the same thing:
/// different program, different platform-vs-shell layer. That mismatch is
/// why Windows measures its own expectation rather than hard-coding one of
/// those unrelated figures.
///
/// Unix has no figure to measure in the first place: a signal-terminated
/// process reports no exit code at all. Below asserts a fatal signal was
/// delivered instead (confirming this really is a hard trap, not a graceful
/// nonzero exit) and pins the same `-1` (`0xFFFFFFFF`) `classify`
/// (`crates/nova-cli/src/cmd/test.rs:112`) itself falls back to via
/// `code().unwrap_or(-1)` — a deliberate duplication of that production
/// constant, not a second measurement, and correspondingly weaker: it
/// catches `classify`'s fallback changing or the hex form being
/// misrendered, but it cannot cross-check against a real reported status
/// the way the Windows half can, because a signal-terminated process on
/// Unix never hands one back. See `expect_trap_exit_code`'s own doc
/// comment for the full mechanism.
#[test]
fn a_hard_trap_is_reported_as_a_trap_and_does_not_satisfy_should_panic() {
    let dir = write_test_project(
        "nova-test-cli-hard-trap",
        "@test(should_panic)\nfn divides_by_zero() { let _ = 1 / 0 }\n",
    );

    // On Windows, measure the real exit code directly, the same way `nova
    // test` itself will see it, rather than assuming a portable number. On
    // Unix there is no code to measure, so `expect_trap_exit_code` asserts a
    // fatal signal instead and pins `classify`'s own fallback constant --
    // see its doc comment (and this test's, above) for why that is weaker
    // than a measurement but still a real check, not a tautology.
    let (exe, tests) = nova_driver::build_test_binary(&dir.join("src/main.nova"))
        .expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["divides_by_zero"]
    );
    let direct = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "0")
        .output()
        .expect("run the trap directly");
    assert!(
        !direct.status.success(),
        "a division by zero must exit nonzero"
    );
    let direct_stderr = String::from_utf8_lossy(&direct.stderr);
    assert!(
        !direct_stderr.contains("nova: panic:"),
        "must be a hard trap with no panic message, not a checked panic: {direct_stderr}"
    );
    let (code, hex) = expect_trap_exit_code(&direct.status);
    let _ = std::fs::remove_file(&exe);

    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        format!(
            "running 1 test\n\
             test divides_by_zero ... TRAPPED (exit code {code} (0x{hex:08X}))\n\
             \n\
             test result: FAILED. 0 passed; 0 failed; 1 trapped; 1 total\n"
        )
    );
}

/// `@test(should_panic)` passes when the panic is a *checked* one — array
/// out of bounds, which panics via `nova_rt_check_bounds`
/// (`nova-runtime/src/lib.rs`) — reported as an ordinary "ok", not called out
/// as anything special. Pairs with the hard-trap test above: together they
/// are the two halves of "should_panic passes on the middle row only, and
/// only that row" (design doc §5).
#[test]
fn should_panic_passes_on_a_checked_panic() {
    let dir = write_test_project(
        "nova-test-cli-should-panic-checked",
        "@test(should_panic)\nfn out_of_bounds_panics() { let xs = [1, 2, 3]\n let _ = xs[7] }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 1 test\n\
         test out_of_bounds_panics ... ok\n\
         \n\
         test result: ok. 1 passed; 0 failed; 0 trapped; 1 total\n"
    );
}

/// Not one of the four required tests, but the same "should_panic passes on
/// the middle row only" rule (design doc §5) has a second edge this project's
/// own gate list never separately exercises: a `should_panic` test that
/// simply completes without panicking. `should_panic` inverting *only* the
/// `Panicked` row (brief step 2) does not mean the `Passed` row is exempt
/// from `should_panic`'s requirement — "passes on the middle row only" reads
/// both ways. Left unhandled, a bug fix that accidentally removed the code
/// path a `should_panic` test exists to guard would make that test keep
/// "passing" forever, which is precisely the silent-regression failure mode
/// `@test(should_panic)` exists to prevent.
#[test]
fn should_panic_fails_distinctly_when_the_test_does_not_panic() {
    let dir = write_test_project(
        "nova-test-cli-should-panic-not-panicking",
        "@test(should_panic)\nfn does_not_actually_panic() { assert_eq(1, 1) }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 1 test\n\
         test does_not_actually_panic ... FAILED (expected a panic, but the test passed)\n\
         \n\
         test result: FAILED. 0 passed; 1 failed; 0 trapped; 1 total\n"
    );
}

// === `2026-08-08-joinhandle-task-identity`: `JoinHandle` keyed on its future,
// not a forgeable id ===
//
// The forged-handle hang itself is `forged_join_handle_aborts_instead_of_hanging`
// above (a `nova run` gate, since the whole point is that it must *complete*).
// The two cases below are its `@test(should_panic)` siblings -- observable
// this way because each test runs in its own process (`cmd/test.rs`'s design),
// so one `abort_with` cannot take any other test down with it -- plus the
// false-positive guard neither would catch on its own: an over-broad
// duplicate-spawn rejection (keying on mere `BY_STATE` presence rather than
// `Task::taken` liveness) would make ordinary double-spawning abort too, and
// nothing above would say so.

/// `join` on a handle built directly from a future that was never `spawn`ed
/// aborts, and spawning one future value twice aborts -- the two ways
/// `nova_rt_task_is_done`/`nova_rt_task_release`/`nova_rt_task_spawn` reject a
/// future they cannot (or must not) resolve. Both land on `abort_with`, which
/// `eprintln!`s the `nova: panic:` marker `cmd/test.rs`'s `classify` looks
/// for, so a `should_panic` test is satisfied by either -- the same
/// classification `should_panic_passes_on_a_checked_panic` exercises via
/// `nova_rt_check_bounds` instead.
#[test]
fn join_handle_rejects_a_never_spawned_future_and_a_live_duplicate() {
    let dir = write_test_project(
        "nova-test-join-handle-forgery-and-duplicate",
        "async fn spin() -> Int { 1 }\n\
         \n\
         @test(should_panic)\n\
         fn joining_a_never_spawned_handle_aborts() {\n\
         \x20\x20let h = JoinHandle { fut: spin() }\n\
         \x20\x20let _ = block_on(h.join())\n\
         }\n\
         \n\
         @test(should_panic)\n\
         fn spawning_the_same_future_twice_aborts() {\n\
         \x20\x20let f = spin()\n\
         \x20\x20spawn(f)\n\
         \x20\x20let _ = spawn(f)\n\
         }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test joining_a_never_spawned_handle_aborts ... ok\n\
         test spawning_the_same_future_twice_aborts ... ok\n\
         \n\
         test result: ok. 2 passed; 0 failed; 0 trapped; 2 total\n"
    );
}

/// The false-positive guard the design's own argument needs and the two
/// `should_panic` tests above cannot provide: two distinct calls to `spin()`
/// are two distinct futures (each allocates its own state object), so
/// spawning both must succeed and run to completion, not merely "not abort".
/// Without this, an over-broad duplicate-spawn rejection would have nothing
/// in this suite to catch it: neither `should_panic` test above spawns two
/// live, legitimately distinct futures, so neither would notice a rejection
/// that fired on that shape too.
#[test]
fn spawning_two_distinct_futures_from_the_same_call_site_still_works() {
    let dir = write_test_project(
        "nova-test-join-handle-double-spawn-guard",
        "async fn spin() -> Int { 1 }\n\
         async fn run_two_spawns() -> Int {\n\
         \x20\x20let a = spawn(spin())\n\
         \x20\x20let b = spawn(spin())\n\
         \x20\x20let ra = a.join().await\n\
         \x20\x20let rb = b.join().await\n\
         \x20\x20ra + rb\n\
         }\n\
         \n\
         @test\n\
         fn spawning_two_distinct_futures_still_works() {\n\
         \x20\x20assert_eq(block_on(run_two_spawns()), 2)\n\
         }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 1 test\n\
         test spawning_two_distinct_futures_still_works ... ok\n\
         \n\
         test result: ok. 1 passed; 0 failed; 0 trapped; 1 total\n"
    );
}

/// `join` is specified to be idempotent (`std/task/lib.nova`'s own doc
/// comment on `JoinHandle::join`): `task_release` is a no-op on its second
/// call, and the value is read back out of the state object's output slot
/// rather than taken, so it survives being read twice. Keying identity on
/// the future rather than an id does not disturb this -- both calls resolve
/// through the same `self.fut`, so there is only ever one task to ask.
#[test]
fn joining_a_handle_twice_returns_the_same_value_twice_with_no_abort() {
    let dir = write_test_project(
        "nova-test-join-handle-join-twice",
        "async fn spin() -> Int { 1 }\n\
         async fn run_join_twice() -> Int {\n\
         \x20\x20let h = spawn(spin())\n\
         \x20\x20let a = h.join().await\n\
         \x20\x20let b = h.join().await\n\
         \x20\x20a + b\n\
         }\n\
         \n\
         @test\n\
         fn joining_a_handle_twice_returns_the_same_value_twice() {\n\
         \x20\x20assert_eq(block_on(run_join_twice()), 2)\n\
         }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 1 test\n\
         test joining_a_handle_twice_returns_the_same_value_twice ... ok\n\
         \n\
         test result: ok. 1 passed; 0 failed; 0 trapped; 1 total\n"
    );
}

/// `nova test <filter>` selects a strict substring-matched subset
/// (`nova-spec/40-TOOLING.md:20`) and — this is the part a weaker test would
/// miss — the unselected test genuinely does not run, not merely go
/// unreported.
///
/// A filter bug that runs every test and only *prints* the selected ones
/// would still pass a test that checks nothing but the two "kept" lines
/// (task brief, step 1). To catch that shape too, `skip_c` (excluded by the
/// filter `"keep"`) spends real wall-clock time if — and only if — it
/// actually runs: a 40-billion-iteration loop, calibrated by direct
/// measurement while writing this test at roughly 1.6 billion iterations per
/// second on this machine (2 billion iterations measured at 1.257s via a
/// throwaway `nova build` + run), so it costs about 25–30 seconds if
/// executed and costs nothing at all if it is correctly skipped. The
/// filtered run below is asserted to finish in well under that — measured at
/// ~0.25s for the correctly-filtered path during development, so the 15
/// second bound leaves a wide, non-flaky margin without ever hanging: the
/// loop is large but finite, so even a buggy runner that does execute it
/// completes (slowly) rather than never returning. `assert_eq(i, ...)` at
/// the end (rather than discarding `i`) exists so the fast Cranelift
/// backend cannot prove the loop dead and remove it.
#[test]
fn a_filter_selects_a_strict_subset_and_the_others_do_not_run() {
    let dir = write_test_project(
        "nova-test-cli-filter",
        "@test\nfn keep_a() { assert_eq(1, 1) }\n\
         @test\nfn keep_b() { assert_eq(2, 2) }\n\
         @test\nfn skip_c() {\n\
         \x20\x20\x20\x20let mut i = 0\n\
         \x20\x20\x20\x20while i < 40000000000 { i = i + 1 }\n\
         \x20\x20\x20\x20assert_eq(i, 40000000000)\n\
         }\n",
    );

    let start = std::time::Instant::now();
    let assert = nova()
        .current_dir(&dir)
        .arg("test")
        .arg("keep")
        .assert()
        .success();
    let elapsed = start.elapsed();
    assert!(
        elapsed < std::time::Duration::from_secs(15),
        "the excluded test's ~25s loop must not have run; took {elapsed:?}"
    );
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test keep_a ... ok\n\
         test keep_b ... ok\n\
         \n\
         test result: ok. 2 passed; 0 failed; 0 trapped; 2 total\n"
    );
}

// === Fix round 1 (review): two "correct but unpinned" gaps ===

/// `should_panic` must be looked up **by the same index the test itself just
/// ran at**, not always at position 0. Every should_panic fixture above has
/// exactly one `@test` function, always at index 0 — `tests[i].should_panic`
/// and the bug `tests[0].should_panic` are indistinguishable at index 0, so
/// none of them could have caught a mis-association. This fixture puts
/// `should_panic` in the middle, at index 1, flanked by two ordinary
/// (`should_panic = false`) tests, so three different plausible
/// index-mistakes are all independently visible:
///
/// - a constant `tests[0]`: `beta_panics_checked` (index 1) would be
///   evaluated against index 0's `false`, turning its "ok" into "FAILED" —
///   a graceful wrong-verdict content mismatch. Measured: `nova test`
///   completes normally and prints a full, well-formed report with exactly
///   this one line wrong.
/// - `tests[i - 1]`: **not** a graceful content mismatch — measured to be a
///   genuine Rust panic that crashes the `nova` process outright, before
///   evaluating anything. `i - 1` is computed on a `usize`, and the very
///   first iteration is `i = 0` (`alpha_ok`), so it underflows immediately:
///   `thread 'main' panicked at ...: attempt to subtract with overflow`,
///   exit code 101. Measured stdout is only the `running 3 tests` header —
///   `beta_panics_checked` and `gamma_ok` never get a chance to print
///   anything, let alone the wrong thing.
/// - `tests[i + 1]`: also a genuine Rust panic, measured one iteration
///   later. `alpha_ok` (index 0) is evaluated against index 1's `true`
///   ("FAILED (expected a panic, but the test passed)") and
///   `beta_panics_checked` (index 1) against index 2's `false` ("FAILED"
///   with its own bounds-panic message) — both print exactly as a
///   content-mismatch framing would predict — but then `gamma_ok` (index 2)
///   reads `tests[3]`, past the end of this 3-element array, and the `nova`
///   process panics with `index out of bounds: the len is 3 but the index
///   is 3` before any `test result:` summary line prints.
///
/// So this single fixture's exact-output assertion fails under any of the
/// three shapes — the first because the content is wrong, the other two
/// because the `nova` process crashes and never reaches a `test result:`
/// line at all — not just the literal one the review reproduced.
#[test]
fn should_panic_is_matched_to_its_own_test_not_to_index_zero() {
    let dir = write_test_project(
        "nova-test-cli-should-panic-by-index",
        "@test\nfn alpha_ok() { assert_eq(1, 1) }\n\
         @test(should_panic)\nfn beta_panics_checked() { let xs = [1, 2, 3]\n let _ = xs[9] }\n\
         @test\nfn gamma_ok() { assert_eq(2, 2) }\n",
    );

    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 3 tests\n\
         test alpha_ok ... ok\n\
         test beta_panics_checked ... ok\n\
         test gamma_ok ... ok\n\
         \n\
         test result: ok. 3 passed; 0 failed; 0 trapped; 3 total\n"
    );
}

/// The filter matches a substring **anywhere** in the name, not only as a
/// prefix. `a_filter_selects_a_strict_subset_and_the_others_do_not_run`'s
/// filter `"keep"` happens to be a literal prefix of both names it selects,
/// so mutating `.contains` to `.starts_with` there still passes. Here
/// neither matching name *starts with* `"alpha"` — it sits in the middle of
/// one and at the end of the other — so `.starts_with("alpha")` would select
/// neither, shrinking `running 2 tests` to `running 0 tests` with no per-test
/// lines at all: an unmistakable difference from the exact output asserted
/// below.
#[test]
fn a_filter_matches_a_substring_anywhere_not_only_as_a_prefix() {
    let dir = write_test_project(
        "nova-test-cli-filter-substring-not-prefix",
        "@test\nfn zzz_alpha_zzz() { assert_eq(1, 1) }\n\
         @test\nfn keep_alpha() { assert_eq(2, 2) }\n\
         @test\nfn unrelated_beta() { assert_eq(3, 3) }\n",
    );

    let assert = nova()
        .current_dir(&dir)
        .arg("test")
        .arg("alpha")
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test zzz_alpha_zzz ... ok\n\
         test keep_alpha ... ok\n\
         \n\
         test result: ok. 2 passed; 0 failed; 0 trapped; 2 total\n"
    );
}

// === Task 6: `nova test` end-to-end gate ===
//
// `tests/runtime/nova_test.{nova,stdout}`, run three ways like every other
// `tests/runtime` fixture (`nova_test_run`, `nova_test_build_standalone`,
// `nova_test_under_gc_stress` — the registrations that take this workspace's
// gate-configuration count from 15 to 18). Unlike `iterator`/`assoc_types`/
// `strings`/`collections`/`std_core`, there is no JIT-vs-object-backend split
// available to give the trio's middle member a distinct meaning:
// `nova_driver::build_test_binary` always compiles through the object
// backend (the same one `nova build` uses; see its doc comment), so
// `nova run`'s JIT path is never exercised by `nova test` at all.
// `nova_test_build_standalone` therefore tests the compiled binary directly —
// bypassing the `nova` CLI subprocess for the compile-and-orchestrate step,
// the same way `a_hard_trap_is_reported_as_a_trap_and_does_not_satisfy_
// should_panic` above does for a single test, generalized here to all four.
//
// Two of the task brief's seven gate items are deliberately NOT inside
// `nova_test.nova` itself:
//   - A filtered run over this exact fixture is `nova_test_filter_run`
//     below — a filter selects a *subset* of the file, so it is not a fourth
//     way to run the whole thing, and Task 5's own tests already pin the
//     filter mechanism (substring, anywhere, not a prefix check); this test's
//     job is only to confirm filtering composes with the real fixture.
//   - An unknown attribute rejected as `E0082` is
//     `nova_test_reports_e0082_for_an_unknown_attribute` below, against its
//     own single-line fixture. It cannot live in `nova_test.nova`: `E0082` is
//     a compile error, and that file must compile cleanly for its other four
//     tests to run at all.

/// Copies the checked-in gate fixture's source into a temp project's
/// `src/main.nova`, since `nova test`'s only positional argument is a filter
/// (`nova-spec/40-TOOLING.md:20`: `nova test [filter]`, no `[file]`, unlike
/// `run`/`build`/`check`) — the entry file is always `src/main.nova` relative
/// to the current directory (`cmd/test.rs`'s `test_entry_file`). `unique_name`
/// keeps concurrent `cargo test` threads from colliding on one directory,
/// same convention as `write_test_project`.
fn write_gate_fixture_project(unique_name: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(unique_name);
    std::fs::create_dir_all(dir.join("src")).expect("temp project dir");
    let source = std::fs::read_to_string(repo_root().join("tests/runtime/nova_test.nova"))
        .expect("gate fixture exists");
    std::fs::write(dir.join("src/main.nova"), source).expect("write fixture");
    dir
}

fn read_gate_expected() -> String {
    std::fs::read_to_string(repo_root().join("tests/runtime/nova_test.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n")
}

/// Replace the two platform-specific numbers in a `TRAPPED (exit code N (0xH))`
/// line with fixed placeholders, leaving every other line byte-identical.
///
/// The gate fixture (`tests/runtime/nova_test.stdout`) asserts the runner's
/// full literal stdout, which is what makes it able to catch a collapsed
/// panicked/trapped distinction. But one token in it cannot be portable:
/// Windows translates a hardware fault into an NTSTATUS exit code
/// (`0xC000001D`, `STATUS_ILLEGAL_INSTRUCTION`), while on Linux and macOS the
/// same program dies from `SIGFPE` with no exit code at all, which
/// `classify` (`cmd/test.rs:112`'s `unwrap_or(-1)`) renders as `-1`. CI's
/// matrix (`.github/workflows/ci.yml`) runs ubuntu, windows and macos, so a
/// fixture pinning either raw value cannot hold on the other two platforms.
///
/// Only the numbers are elided; the surrounding structure — the test name,
/// the word `TRAPPED`, and the presence of both the decimal and the
/// parenthesized hex — is preserved, so a change in the report's *shape*
/// still fails the comparison. This is the same rule this file already
/// follows for its two trap tests,
/// `a_hard_trap_is_reported_as_a_trap_and_does_not_satisfy_should_panic` and
/// `a_trapping_tests_captured_output_is_shown_not_discarded`: never write a
/// literal exit code into an expectation, because the code an aborted
/// process reports is platform-dependent. Those two tests get their
/// `(code, hex)` pair from `expect_trap_exit_code` — a real measurement on
/// Windows, but on Unix (where a signal-terminated process reports no code
/// at all) a deliberate pin of `classify`'s own documented `-1`
/// (`0xFFFFFFFF`) fallback rather than a second measurement (see that
/// helper's doc comment). Either way the value is platform-appropriate and
/// asserted rather than written as a literal here, which is exactly why
/// normalizing this fixture loses no coverage — the real, or on Unix the
/// correctly-predicted, value is still pinned, just not in this file.
///
/// Splits on plain `'\n'` rather than [`str::lines`]: `lines()` also
/// swallows a trailing line terminator (`"a\n".lines().collect::<Vec<_>>()`
/// is just `["a"]`, indistinguishable from splitting `"a"` with no newline
/// at all), so `s.lines().collect::<Vec<_>>().join("\n")` silently drops a
/// trailing newline the input had. Measured directly by temporarily making
/// that swap: the test below's very first `assert_eq!` then fails with
/// `left: "...<HEX>))"` vs. `right: "...<HEX>))\n"` — the trailing newline
/// gone from the normalized side. `split`/`join` on the same literal
/// delimiter are exact inverses of one another (unlike `lines`/`join`), so
/// every byte that isn't inside a rewritten line — including a trailing
/// newline, or the lack of one — survives untouched. Every actual call site
/// (below, and in `nova_test_run`, `nova_test_build_standalone`,
/// `nova_test_under_gc_stress`) already has `"\r\n"` collapsed to `"\n"`
/// before calling this function: the unit test passes only `\n`-terminated
/// literals, and each of the three gate tests calls
/// `.replace("\r\n", "\n")` on the text it passes in — captured stdout
/// for `nova_test_run` and `nova_test_under_gc_stress`, but
/// `nova_test_build_standalone`'s own synthesized report string (built
/// from each subprocess's `result.stderr` and `result.status`; that
/// function never reads `result.stdout`) for the third. (The
/// fixture's own text, loaded by `read_gate_expected`, is independently
/// CRLF-normalized when read from disk — but it is never itself passed to
/// this function; it is only the literal right-hand side `assert_eq!`
/// compares this function's output against.) So plain `'\n'` splitting is
/// exact here; no `'\r'` ever reaches this function.
fn normalize_trap_codes(s: &str) -> String {
    const MARKER: &str = "TRAPPED (exit code ";
    s.split('\n')
        .map(|line| match line.find(MARKER) {
            // Rewrite only from the marker to the end of the parenthesized
            // payload, so anything before `TRAPPED` (the test name) is kept.
            // The `ends_with("))")` guard is what keeps a decoy line — one
            // that merely mentions "exit code", or a TRAPPED line missing
            // its hex form — from being rewritten. Verified directly against
            // `tests/runtime/nova_test.stdout` (post `\r\n` -> `\n`
            // normalization, as every caller applies): its one TRAPPED line
            // is the only line in that fixture ending in `"))"`.
            Some(i) if line.ends_with("))") => {
                format!("{}{}<CODE> (<HEX>))", &line[..i], MARKER)
            }
            _ => line.to_string(),
        })
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn normalize_trap_codes_elides_only_the_platform_specific_numbers() {
    // The gate fixture cannot hold a real exit code: Windows reports an
    // NTSTATUS (-1073741795 / 0xC000001D for an illegal instruction) while a
    // signal-killed process on Linux/macOS has no code at all and renders as
    // -1. Both must normalize to the same text, or the fixture can only ever
    // match one platform.
    let win = "test t ... TRAPPED (exit code -1073741795 (0xC000001D))\n";
    let unix = "test t ... TRAPPED (exit code -1 (0xFFFFFFFF))\n";
    assert_eq!(normalize_trap_codes(win), normalize_trap_codes(unix));
    assert_eq!(
        normalize_trap_codes(win),
        "test t ... TRAPPED (exit code <CODE> (<HEX>))\n"
    );

    // STRUCTURE MUST SURVIVE. If the runner ever stopped printing the hex
    // form, or dropped the "TRAPPED" word, or lost the test name, the
    // normalized text must change so the fixture comparison fails. A
    // normalizer that collapsed the whole line to a constant would hide
    // exactly the regressions this fixture exists to catch.
    assert_ne!(
        normalize_trap_codes(win),
        normalize_trap_codes("test t ... TRAPPED (exit code -1073741795)\n")
    );
    assert_ne!(
        normalize_trap_codes(win),
        normalize_trap_codes("test OTHER ... TRAPPED (exit code -1073741795 (0xC000001D))\n")
    );
    assert_ne!(
        normalize_trap_codes(win),
        normalize_trap_codes("test t ... FAILED (exit code -1073741795 (0xC000001D))\n")
    );

    // Lines with no trap must pass through byte-identically -- the fixture's
    // other five lines (the header, two `ok`s, a FAILED with its panic
    // message, and the summary) are fully portable and must stay asserted
    // exactly.
    let untouched = "running 4 tests\ntest a ... ok\n\ntest result: FAILED. 2 passed; 1 failed; 1 trapped; 4 total\n";
    assert_eq!(normalize_trap_codes(untouched), untouched);

    // A panic message that merely mentions the words must not be rewritten.
    let decoy = "    nova: panic: exit code -5 is wrong\n";
    assert_eq!(normalize_trap_codes(decoy), decoy);
}

/// Through the full `nova` CLI, exactly as a user would invoke it.
/// `.failure()` is correct, not a mistake: the fixture deliberately contains
/// a failing assertion and a hard trap (see its own header comment), so
/// `nova test` itself must exit nonzero even though two of its four tests
/// pass. The full stdout is asserted — not a pass/fail count and not a
/// substring — because a runner that collapsed the panicked/trapped
/// distinction would still exit nonzero here (the unrelated failing
/// `assert_eq` guarantees that), so only the exact per-test lines catch the
/// regression this fixture exists to protect against (task brief, item 4).
/// Captured and run through `normalize_trap_codes` rather than asserted with
/// `assert_cmd`'s `.stdout(expected)` predicate, which cannot normalize:
/// the trapped test's exit code is platform-specific (see
/// `normalize_trap_codes`'s doc comment), so it is the one part of stdout
/// not compared completely literally.
#[test]
fn nova_test_run() {
    let expected = read_gate_expected();
    let dir = write_gate_fixture_project("nova-test-gate-run");
    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    // stderr is attached below too, alongside stdout, even though only stdout
    // is compared: `.assert()` above has already captured it at no extra
    // cost (no re-run), and an ADR-0008 occurrence on this freshly built
    // binary could in principle leave stdout empty with its only diagnostic
    // on stderr — in which case stdout alone would print nothing useful.
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr);
    assert_eq!(
        normalize_trap_codes(&stdout),
        expected,
        "gate output mismatch. Raw, un-normalized stdout follows — the exit \
         codes in it are the evidence ADR 0008's open question needs, and \
         normalization would otherwise replace them with placeholders. \
         stderr follows too, in case stdout above is empty:\nstdout:\n{stdout}\n\
         stderr:\n{stderr}"
    );
}

/// The same fixture through `nova_driver::build_test_binary` called
/// directly, running the produced binary itself rather than going through
/// the `nova` CLI's subprocess at all. `crates/nova-cli` has no `[lib]`
/// target (only a `[[bin]]`), so an integration test cannot call
/// `cmd::test::run` directly — calling the driver crate and reconstructing
/// the report is the closest equivalent to `iterator_build_standalone`'s
/// "exercise a different code path than `_run`" intent that is actually
/// available here. Reconstructs the exact report `cmd/test.rs::run` would
/// print (mirroring its `classify` + reporting loop) and compares the
/// captured `String` with `assert_eq!`, rather than asserting on an
/// `assert_cmd::Command` the way `nova_test_run` does — matching the brief's
/// note that "the build variant compares captured stdout rather than
/// asserting on the command." `out` itself is still built from the real,
/// live exit code the child process reported (see the `TRAPPED` arm below)
/// exactly as `cmd/test.rs::run` would print it; only the final `assert_eq!`
/// runs it through `normalize_trap_codes`, for the same cross-platform
/// reason `nova_test_run` does.
#[test]
fn nova_test_build_standalone() {
    let expected = read_gate_expected();
    let dir = write_gate_fixture_project("nova-test-gate-build-standalone");
    let (exe, tests) = nova_driver::build_test_binary(&dir.join("src/main.nova"))
        .expect("test binary compiles and links");

    let mut out = format!(
        "running {} test{}\n",
        tests.len(),
        if tests.len() == 1 { "" } else { "s" }
    );
    let (mut passed, mut failed, mut trapped) = (0usize, 0usize, 0usize);
    // `NOVA_TEST_INDEX` addresses a test by its position in `tests` — source
    // order, which is also dispatch order in the synthesized `main`
    // (`nova_driver::synthesize_test_main`) — so the enumeration index `i`,
    // not `t.def_id`, is what selects it.
    for (i, t) in tests.iter().enumerate() {
        let result = Command::new(&exe)
            .env("NOVA_TEST_INDEX", i.to_string())
            .output()
            .unwrap_or_else(|e| panic!("failed to run {} for `{}`: {e}", exe.display(), t.name));
        let stderr = String::from_utf8_lossy(&result.stderr);
        let panic_line = stderr.lines().find(|line| line.contains("nova: panic:"));
        if result.status.success() {
            if t.should_panic {
                failed += 1;
                out.push_str(&format!(
                    "test {} ... FAILED (expected a panic, but the test passed)\n",
                    t.name
                ));
            } else {
                passed += 1;
                out.push_str(&format!("test {} ... ok\n", t.name));
            }
        } else if let Some(line) = panic_line {
            if t.should_panic {
                passed += 1;
                out.push_str(&format!("test {} ... ok\n", t.name));
            } else {
                failed += 1;
                out.push_str(&format!(
                    "test {} ... FAILED\n    {}\n",
                    t.name,
                    line.trim()
                ));
            }
        } else {
            trapped += 1;
            let code = result.status.code().unwrap_or(-1);
            let hex = code as u32;
            out.push_str(&format!(
                "test {} ... TRAPPED (exit code {code} (0x{hex:08X}))\n",
                t.name
            ));
        }
    }
    out.push('\n');
    let total = tests.len();
    let all_ok = failed == 0 && trapped == 0;
    out.push_str(&format!(
        "test result: {}. {passed} passed; {failed} failed; {trapped} trapped; {total} total\n",
        if all_ok { "ok" } else { "FAILED" }
    ));
    let _ = std::fs::remove_file(&exe);

    // No separate stderr is attached here the way the other two gate tests'
    // failure messages attach one: unlike those two, which run one top-level
    // `nova` subprocess and could in principle see it produce empty stdout
    // with a diagnostic only on stderr, this test's `out` is itself already
    // assembled per-subprocess from each test binary's own `result.stderr`
    // and `result.status` (see the loop above) — a TRAPPED line's real exit
    // code is already inlined into `out` directly from that `result.status`,
    // so `out` alone carries the evidence an ADR-0008 occurrence would leave.
    assert_eq!(
        normalize_trap_codes(&out.replace("\r\n", "\n")),
        expected,
        "gate output mismatch. Raw, un-normalized report follows — the exit \
         codes in it are the evidence ADR 0008's open question needs, and \
         normalization would otherwise replace them with placeholders:\n{out}"
    );
}

/// The same fixture with `NOVA_GC_STRESS=1` (collect on every allocation).
/// Each `@test` runs in its own process (`cmd/test.rs`'s whole design), and
/// `std::process::Command::env` only ever ADDS to an inherited environment
/// rather than replacing it, so setting the variable on the outer
/// `nova test` invocation reaches every process it spawns too — the same
/// propagation Task 4 independently confirmed for this exact mechanism
/// (`std::process::Command::env`, not a proxy for it). Compared through
/// `normalize_trap_codes` the same way `nova_test_run` is, and for the same
/// reason — see its comment.
#[test]
fn nova_test_under_gc_stress() {
    let expected = read_gate_expected();
    let dir = write_gate_fixture_project("nova-test-gate-gc-stress");
    let assert = nova()
        .env("NOVA_GC_STRESS", "1")
        .current_dir(&dir)
        .arg("test")
        .assert()
        .failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    // Same reasoning as `nova_test_run`'s comment above its own `stderr`
    // capture: already captured by `.assert()` at no extra cost, and
    // attached below in case an ADR-0008 occurrence leaves stdout empty with
    // its only diagnostic on stderr.
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr);
    assert_eq!(
        normalize_trap_codes(&stdout),
        expected,
        "gate output mismatch. Raw, un-normalized stdout follows — the exit \
         codes in it are the evidence ADR 0008's open question needs, and \
         normalization would otherwise replace them with placeholders. \
         stderr follows too, in case stdout above is empty:\nstdout:\n{stdout}\n\
         stderr:\n{stderr}"
    );
}

/// Gate item 5 ("a filter run"), composed with the real multi-item fixture
/// rather than a fresh throwaway one. Task 5's own
/// `a_filter_selects_a_strict_subset_and_the_others_do_not_run` and
/// `a_filter_matches_a_substring_anywhere_not_only_as_a_prefix` already pin
/// the filter *mechanism* (substring match, anywhere in the name, proven not
/// to be merely a prefix check); this test's job is narrower — confirm
/// filtering still composes correctly against this specific fixture.
/// `"is_correct"` is a substring of exactly one of the four names, so a
/// selected count other than 1 is immediately visible.
#[test]
fn nova_test_filter_run() {
    let dir = write_gate_fixture_project("nova-test-gate-filter");
    let assert = nova()
        .current_dir(&dir)
        .arg("test")
        .arg("is_correct")
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 1 test\n\
         test addition_is_correct ... ok\n\
         \n\
         test result: ok. 1 passed; 0 failed; 0 trapped; 1 total\n"
    );
}

/// Gate item 6 ("an unknown attribute rejected as `E0082`"), exercised
/// through `nova test` specifically rather than only `nova check` / the
/// resolver's own unit tests (which already cover `E0082` exhaustively —
/// Task 2). It cannot live inside `nova_test.nova`: `E0082` is a compile
/// error, and that file must compile cleanly for its other four tests to run
/// at all. Asserts the diagnostic's actual text, not only its code, matching
/// this branch's standing rule that a bare code check would still pass if
/// the message body were replaced with something unrelated.
#[test]
fn nova_test_reports_e0082_for_an_unknown_attribute() {
    let dir = write_test_project("nova-test-gate-e0082", "@tset\nfn foo() { }\n");
    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr);
    assert!(stderr.contains("E0082"), "stderr: {stderr}");
    assert!(
        stderr.contains("unknown attribute `@tset`; known attributes are: test"),
        "stderr: {stderr}"
    );
}

// === Final whole-branch review, condition 1 (CRITICAL): `@test async fn` must
// be refused, and the supported shape must still work ===
//
// `@test async fn` used to compile and report `ok` while running none of its
// body: the runner's dispatcher calls the collected symbol directly, and for an
// `async fn` that symbol is the future-building wrapper, so the call allocated a
// state object and returned a future nothing polled. A guaranteed-failing
// assertion inside such a test reported green.
//
// The fix refuses the shape (`E0084`) rather than shimming the dispatcher,
// because `@test fn t() { block_on(f()) }` is the shape the `nova test` design
// and Phase 2.3a's own design (§10) both specify for testing async code — the
// defect was acceptance, not a missing feature. The two tests below are the
// halves of that claim and only mean something together: the first that the
// refusal fires with an actionable diagnostic, the second that async code is
// still testable *and* that a wrong answer inside the supported shape really
// does fail. Without the second, the first would be indistinguishable from
// closing off async testing entirely.

/// The refusal fires through `nova test`, with a diagnostic that names the
/// working alternative.
///
/// End to end rather than only in `nova-typeck`
/// (`test_on_an_async_function_is_e0084`) because the dispatcher this protects
/// lives in `nova-driver` and is reached only on this path: a refusal that held
/// in the resolver's own tests but not here would leave the original defect
/// intact for every actual user of `nova test`.
#[test]
fn nova_test_rejects_an_async_test_function() {
    let dir = write_test_project(
        "nova-test-async-rejected",
        "async fn helper() -> Int { 41 }\n\
         @test\nasync fn t() { assert_eq(helper().await, 999) }\n",
    );
    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr);
    assert!(stderr.contains("E0084"), "stderr: {stderr}");
    assert!(
        stderr.contains("a `@test` function may not have an `async` body"),
        "the message must name `async`, not a generic bad signature: {stderr}"
    );
    // The note is the load-bearing half for a user: without it the refusal
    // reads as "async cannot be tested". Both fragments are asserted because
    // naming `block_on` without showing where it goes is not actionable.
    assert!(
        stderr.contains("block_on"),
        "the diagnostic must name the working alternative: {stderr}"
    );
    assert!(
        stderr.contains("@test fn t()"),
        "the diagnostic must spell the replacement out as source: {stderr}"
    );
    // The refusal must be a compile error, so nothing can be reported as a
    // test result at all -- a diagnostic printed beside a green `ok` line would
    // be the original defect with extra noise.
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout);
    assert!(
        !stdout.contains("... ok"),
        "no test may be reported as passing: {stdout}"
    );
}

/// The supported shape runs the async body, and a wrong answer inside it FAILS.
///
/// `helper` suspends at a real `yield_now().await` before producing its value,
/// so passing here cannot be satisfied by a future that was built and dropped:
/// the state machine has to be resumed after a suspension for `41` to exist at
/// all. The failing twin pins the same thing from the other side — the rendered
/// `41 != 999` is the value that came back out of the future, so a runner that
/// silently skipped the body could not produce it.
///
/// Asserts the entire rendered stdout rather than a fragment, the same reason
/// `nova_test_reports_a_pass_and_a_failure_distinctly` does.
#[test]
fn nova_test_runs_an_async_body_via_block_on_and_pins_a_wrong_answer() {
    let dir = write_test_project(
        "nova-test-async-block-on",
        "async fn helper() -> Int {\n  yield_now().await\n  41\n}\n\
         @test\nfn an_async_body_runs_under_block_on() { assert_eq(block_on(helper()), 41) }\n\
         @test\nfn a_wrong_answer_inside_block_on_fails() { assert_eq(block_on(helper()), 999) }\n",
    );
    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test an_async_body_runs_under_block_on ... ok\n\
         test a_wrong_answer_inside_block_on_fails ... FAILED\n\
         \x20\x20\x20\x20nova: panic: assertion failed: 41 != 999\n\
         \n\
         test result: FAILED. 1 passed; 1 failed; 0 trapped; 2 total\n"
    );
}

// === Whole-branch review, finding 1 (CRITICAL): `@test` functions must not
// break `nova check` / `nova build` / `nova run` ===
//
// Before this fix, a `@test` function was an ordinary item in every
// compilation unit regardless of `with_test_module` — `nova_resolver::
// collect_item` collected it, gave it a `DefId`, and `nova_typeck::check`
// type-checked its body exactly like any other function. That body is
// written assuming `std/test`'s `assert`/`assert_eq`/`assert_ne` are in
// scope; they are seeded only when compiling for `nova test`
// (`nova_driver::FrontendContext::check`'s own doc comment). So a source
// file containing so much as one `@test` function that called `assert_eq`
// could not be `nova check`ed, `nova build`t, or `nova run` at all —
// `error[E0001]: cannot find function `assert_eq`` on every call — even
// though `nova test` itself compiled and ran the identical file correctly.
// `nova check` is the editor path, so this reproduced on every keystroke in
// any project with tests, and `nova build && nova test` could never both
// succeed on one tree. Fixed by `nova_driver::strip_test_functions`, which
// removes every top-level `@test` function from the compilation unit before
// `nova_resolver::resolve_program` ever sees it, whenever `with_test_module`
// is `false`.

/// The reviewer's exact repro, reduced to a standalone fixture: a file with
/// `@test` functions calling `assert_eq` must compile clean under `nova
/// check`, `nova build` and `nova run` (previously: two `E0001`s under each,
/// one per `assert_eq` call), and the identical, unmodified file must still
/// run correctly under `nova test` — proving the fix removes `@test`
/// functions from non-test compilation without disturbing their real
/// execution. Asserts both halves, per the finding.
#[test]
fn test_functions_calling_assert_eq_do_not_break_check_build_or_run() {
    let dir = write_test_project(
        "nova-test-cli-critical-nontest-compile",
        "@test\nfn addition_is_correct() { assert_eq(2 + 2, 4) }\n\
         @test\nfn addition_is_wrong() { assert_eq(2 + 2, 5) }\n\
         fn main() { println(\"hello\") }\n",
    );
    let file = dir.join("src/main.nova");

    // `nova check`: previously two `E0001`s (one per `assert_eq` call).
    nova().arg("check").arg(&file).assert().success();

    // `nova build`: the same program, through the same broken path
    // (`build_file` -> `lower_to_mir` -> `FrontendContext::check(false)`).
    // The built binary runs the user's ordinary `main` — `@test` functions
    // are absent from this compilation entirely, not merely unreachable.
    let out_exe = dir.join(format!("built{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&out_exe)
        .assert()
        .success();
    let run = Command::new(&out_exe).output().expect("run built binary");
    assert!(run.status.success());
    assert_eq!(
        String::from_utf8_lossy(&run.stdout).replace("\r\n", "\n"),
        "hello\n"
    );
    let _ = std::fs::remove_file(&out_exe);

    // `nova run`: same broken path via the JIT (`run_file` -> `compile_file`
    // -> `FrontendContext::check(false)`).
    nova()
        .arg("run")
        .arg(&file)
        .assert()
        .success()
        .stdout("hello\n");

    // The identical file, completely unmodified, still compiles and runs
    // correctly under `nova test` — one pass, one fail, exact message.
    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test addition_is_correct ... ok\n\
         test addition_is_wrong ... FAILED\n\
         \x20\x20\x20\x20nova: panic: assertion failed: 4 != 5\n\
         \n\
         test result: FAILED. 1 passed; 1 failed; 0 trapped; 2 total\n"
    );
}

/// The same fix, but for a `@test` function that lives in an *imported*
/// module rather than the entry file itself. `nova_driver::
/// strip_test_functions` is applied to every module `load_modules` returns,
/// not only the entry file's — a `@test` function reached only through
/// `import` is just as capable of referencing `assert_eq` and hitting the
/// identical `E0001` if it is not also stripped there.
#[test]
fn test_functions_in_an_imported_module_do_not_break_check_or_build() {
    let dir = write_test_project(
        "nova-test-cli-critical-nontest-compile-imported",
        "import helper\nfn main() { println(\"hello\") }\n",
    );
    std::fs::write(
        dir.join("src/helper.nova"),
        "@test\nfn helper_test() { assert_eq(1 + 1, 2) }\n",
    )
    .expect("write imported module");
    let file = dir.join("src/main.nova");

    nova().arg("check").arg(&file).assert().success();

    let out_exe = dir.join(format!("built-imported{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&out_exe)
        .assert()
        .success();
    let _ = std::fs::remove_file(&out_exe);
}

// === Whole-branch review, finding 3 (Important): captured output must not
// be discarded for a non-passing test ===
//
// Before this fix, `Outcome::Trapped` carried only the raw exit code — a
// trapping test rendered `TRAPPED (exit code N)` and nothing else, no
// matter what it (or the runtime) had written to either stream — and a
// FAILED test's own `println` output was silently dropped too, since only
// the one matched panic-marker line from stderr survived. `classify`
// (`cmd/test.rs`) always had the full `Output` in hand; the fix carries it
// through to the report via `print_captured`, printed only for a stream
// that actually has something in it.

/// A test that `println`s before its `assert_eq` fails: the failure summary
/// still shows the panic message exactly as before, and now also shows what
/// the test itself printed, which used to be discarded entirely.
#[test]
fn a_failing_tests_own_stdout_is_no_longer_discarded() {
    let dir = write_test_project(
        "nova-test-cli-captured-stdout-on-failure",
        "@test\nfn prints_then_fails() {\n\
         \x20\x20\x20\x20println(\"about to fail\")\n\
         \x20\x20\x20\x20assert_eq(1, 2)\n\
         }\n",
    );
    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 1 test\n\
         test prints_then_fails ... FAILED\n\
         \x20\x20\x20\x20nova: panic: assertion failed: 1 != 2\n\
         \x20\x20\x20\x20---- stdout ----\n\
         \x20\x20\x20\x20about to fail\n\
         \n\
         test result: FAILED. 0 passed; 1 failed; 0 trapped; 1 total\n"
    );
}

/// A trap must show captured output too, not just the bare exit code — the
/// entire point of this finding: reporting a trap with *less* information
/// than an ordinary failure is backwards given this branch's central claim
/// that traps deserve their own outcome. The `(code, hex)` pair below comes
/// from `expect_trap_exit_code`, exactly as
/// `a_hard_trap_is_reported_as_a_trap_and_does_not_satisfy_should_panic`
/// uses it: measured directly on Windows, pinned to `classify`'s own
/// documented fallback on Unix rather than assumed either way (design doc
/// §9 risk 4: not portable) — see that test's doc comment, or the helper's,
/// for why the Unix half is weaker than a measurement but not a tautology.
#[test]
fn a_trapping_tests_captured_output_is_shown_not_discarded() {
    let dir = write_test_project(
        "nova-test-cli-captured-output-on-trap",
        "@test(should_panic)\nfn prints_then_traps() {\n\
         \x20\x20\x20\x20println(\"about to trap\")\n\
         \x20\x20\x20\x20let _ = 1 / 0\n\
         }\n",
    );

    let (exe, tests) = nova_driver::build_test_binary(&dir.join("src/main.nova"))
        .expect("test binary compiles and links");
    assert_eq!(
        tests.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
        vec!["prints_then_traps"]
    );
    let direct = Command::new(&exe)
        .env("NOVA_TEST_INDEX", "0")
        .output()
        .expect("run the trap directly");
    let (code, hex) = expect_trap_exit_code(&direct.status);
    let _ = std::fs::remove_file(&exe);

    let assert = nova().current_dir(&dir).arg("test").assert().failure();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        format!(
            "running 1 test\n\
             test prints_then_traps ... TRAPPED (exit code {code} (0x{hex:08X}))\n\
             \x20\x20\x20\x20---- stdout ----\n\
             \x20\x20\x20\x20about to trap\n\
             \n\
             test result: FAILED. 0 passed; 0 failed; 1 trapped; 1 total\n"
        )
    );
}

// === Whole-branch review, finding 4 (Important): an explicit filter
// matching zero tests must fail, not silently report success ===
//
// Before this fix, `nova test <typo>` printed `running 0 tests` / `test
// result: ok` and exited 0 — indistinguishable from an unfiltered run of a
// project with no tests at all, so a typo'd CI filter reported green having
// run nothing (ADR 0008 §2's own residual-gaps list named this).

/// `nova test <typo>` must exit nonzero and name the filter, not report
/// success having run nothing.
#[test]
fn an_explicit_filter_matching_nothing_is_a_failure() {
    let dir = write_test_project(
        "nova-test-cli-filter-matches-nothing",
        "@test\nfn addition_is_correct() { assert_eq(1 + 1, 2) }\n",
    );
    let assert = nova()
        .current_dir(&dir)
        .arg("test")
        .arg("nosuchtest")
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr);
    assert!(
        stderr.contains("no test name contains the filter `nosuchtest`"),
        "stderr: {stderr}"
    );
    // Nothing ran: no `running N tests`, no per-test line, no summary.
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout);
    assert_eq!(stdout, "", "stdout: {stdout}");
}

/// The one case finding 4 must NOT touch: an *unfiltered* run of a file with
/// no tests at all is not an error — nothing was mistyped; there is simply
/// nothing to run, same as before this fix.
#[test]
fn an_unfiltered_run_with_no_tests_still_succeeds() {
    let dir = write_test_project("nova-test-cli-no-tests-at-all", "fn main() { }\n");
    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 0 tests\n\
         \n\
         test result: ok. 0 passed; 0 failed; 0 trapped; 0 total\n"
    );
}

/// A function value in a test program: a closure, and a named function
/// passed as a value. The type checker numbers the functions it lifts for
/// them past every resolved definition, where the synthesized `main` took
/// its `DefId` too, so the first of them collided with it and codegen
/// failed ("mismatched argument count").
#[test]
fn a_test_program_may_hold_function_values() {
    let dir = write_test_project(
        "nova-test-cli-function-values",
        "fn inc(x: Int) -> Int { x + 1 }\n\
         fn apply(f: fn(Int) -> Int, x: Int) -> Int { f(x) }\n\
         @test\nfn a_closure() {\n    let f = |x: Int| x + 1\n    assert_eq(f(1), 2)\n}\n\
         @test\nfn a_named_function_as_a_value() {\n    assert_eq(apply(inc, 1), 2)\n    \
         assert_eq(Some(1).map(inc).unwrap_or(0), 2)\n}\n",
    );
    let assert = nova().current_dir(&dir).arg("test").assert().success();
    let stdout = String::from_utf8_lossy(&assert.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(
        stdout,
        "running 2 tests\n\
         test a_closure ... ok\n\
         test a_named_function_as_a_value ... ok\n\
         \n\
         test result: ok. 2 passed; 0 failed; 0 trapped; 2 total\n"
    );
}

// === Task 1 (std/fs on Strings increment): `std/io` error types, and the
// `eprint`/`eprintln` builtins ===

/// `IoError`/`IoErrorKind` resolve with no `import`, and `io_error_kind_of`
/// maps a runtime status code to the right variant — including an unmapped
/// code (`99`), which must fall to `Other` rather than doing something
/// undefined; that arm is otherwise unreachable from Rust.
#[test]
fn fs_io_types_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_io_types.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_io_types.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `eprint`/`eprintln` write to stderr, not stdout — the split is the whole
/// point, so this pins both streams exactly rather than only checking stdout.
/// A version that wrote either to stdout instead must fail this.
#[test]
fn eprint_family_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/eprint_family.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/eprint_family.nova"))
        .assert()
        .success()
        .stdout(expected)
        .stderr("ab\n");
}

// === Task 2 (std/fs on Strings increment): the boundary, `read_to_string`,
// and `write_string` ===

/// Reading a path that does not exist reports `NotFound`, round-tripped
/// through the status-code boundary in `crates/nova-runtime/src/fs.rs` and
/// back out through `io_error_kind_of` in `std/io`. Asserts on `kind` only,
/// never `message`, per the spec's diagnostics rule -- the OS's own wording
/// for "no such file" is platform-specific.
#[test]
fn fs_not_found_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_not_found.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_not_found.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture again through `nova build` -- a standalone linked
/// executable rather than the JIT (see `gate_async_tasks_build_standalone`'s
/// doc comment for why this does not itself cross the Cranelift/LLVM
/// boundary). Closes half of I4(b) from the final review: before this, no
/// `std/fs` fixture ran under anything but `nova run`, even though the
/// reviewer checked by hand that `nova build` works. This particular
/// fixture needs no temp directory or environment override -- it only reads
/// a path that must not exist -- so it is the cheapest fs fixture to route
/// through `build_and_run` as it stands.
#[test]
fn fs_not_found_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_not_found.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/fs_not_found.nova", "fs_not_found");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// **MEASURED, not assumed -- on Windows only (final review, I1).** Pins the
/// one arm of the Rust-side status↔kind mapping (`crates/nova-runtime/src/fs.rs`'s
/// `fail`) that is both reachable from `std/fs` and was previously unpinned:
/// `read_to_string` on a directory reports `PermissionDenied` here. Swapping
/// `PERMISSION_DENIED` with another status in `fail` (the review's own
/// mutation) now fails this fixture; before this test existed, that swap
/// survived the entire suite. `#[cfg(windows)]` because Windows is the only
/// platform this was measured on -- the same call reports a different kind
/// (`Other`, via `Uncategorized`) on POSIX, per `docs/adr/0011-io-error-kinds.md`,
/// so asserting `PermissionDenied` unconditionally would be wrong there, not
/// merely untested.
#[cfg(windows)]
#[test]
fn fs_permission_denied_run() {
    let tmp = unique_temp_dir("nova-fs-permission-denied");
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_permission_denied.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_permission_denied.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// Non-UTF-8 file contents report `InvalidData`, not a panic and not lossy
/// replacement.
///
/// **Before the byte-type increment's Task 4, `write_string` only accepted a
/// `String`, so the invalid bytes could only be placed on disk from Rust** --
/// this harness wrote them directly before invoking the fixture, with its own
/// process-id-namespaced directory and `.current_dir` (since the fixture then
/// read a bare relative filename). Task 4's `write` accepts `Bytes`, so the
/// fixture now writes its own non-UTF-8 payload via
/// `write(p, bytes_from_ints([0xFF, 0xFE])).await`, and this harness shrinks
/// to the same `unique_temp_dir` + `TMPDIR`/`TMP`/`TEMP` shape every other
/// `fs_` fixture that touches a real path already uses -- nothing
/// filesystem-specific to this one test remains here. See the task report
/// for the exact before/after.
#[test]
fn fs_invalid_data_run() {
    let tmp = unique_temp_dir("nova-fs-invalid-data");
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_invalid_data.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_invalid_data.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// Closes review findings I1/I2 on this task: `fs_not_found` and
/// `fs_invalid_data` above exercise only the error branch of
/// `read_to_string`/`write_string`, so neither `write_string` actually
/// touching disk nor `read_to_string`'s success arm delivering the right
/// payload was ever exercised by anything. Proven by mutation, not argued:
/// replacing `nova_rt_fs_write_string`'s body with a no-op returning success
/// left every target in the workspace passing, and discarding the payload in
/// `nova_rt_fs_read_to_string`'s `Ok` arm (returning `NOT_FOUND` instead)
/// left every test in this binary and in `fs.rs`'s own suite passing too.
/// See the task report for both transcripts.
///
/// A real write-then-read round trip needs a writable path, which is what
/// `temp_dir` (pulled forward from Task 3 for exactly this reason) supplies.
/// This is deliberately not named or shaped like Task 3's own
/// `fs_roundtrip.nova` (which additionally exercises `remove_file`):
/// `write_string`/`read_to_string` accept only a `String` and `std/fs` had no
/// delete operation when this fixture was written, so *this* harness deletes
/// the file directly, both before (a stale file from an interrupted prior
/// run must not produce a false pass) and after (leave nothing behind).
///
/// **The literal filename below used to be joined onto the OS-shared temp
/// directory directly** (Task 3 review): two concurrent `cargo test`
/// invocations of this same binary would then race on one path. The
/// before/after `remove_file` calls only ever protected against a *stale*
/// file left by a non-overlapping prior run; they cannot protect against a
/// second process deleting or overwriting the file out from under this one
/// mid-test. `unique_temp_dir` fixes the actual collision by redirecting
/// *this process's* view of `temp_dir()` (via `TMP`/`TEMP`/`TMPDIR`, scoped
/// to the child `nova` process only) to a directory namespaced by this test
/// binary's own process id, so the path this fixture computes at runtime can
/// no longer collide with another process's. See `unique_temp_dir`'s doc
/// comment for why this is an environment override rather than a Nova-level
/// change, and the task report for how this was verified.
#[test]
fn fs_write_then_read_run() {
    let tmp = unique_temp_dir("nova-fs-write-then-read");
    let path = tmp.join("nova_fs_write_then_read_8a41.txt");
    let _ = std::fs::remove_file(&path);

    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_write_then_read.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_write_then_read.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);

    // M4 (final review). MEASURED: temporarily hardcoding
    // `nova_rt_fs_temp_dir` to always create and return
    // `C:/nova-mutant-tempdir-probe`, ignoring `TMPDIR`/`TMP`/`TEMP` entirely,
    // still produced byte-identical stdout here -- `write_string` and
    // `read_to_string` both resolve `temp_dir()` themselves, so the mutant
    // stayed internally self-consistent. The assertion below is what caught
    // it: `fs_write_then_read.nova` never deletes what it writes, so
    // asserting the file exists at exactly the path this harness computed
    // from its own override -- before this harness's own cleanup removes it
    // -- pins that `temp_dir()` returned what those env vars said, not merely
    // *a* writable directory. Reverted after measuring; not one of this
    // fix wave's three required mutation transcripts, but cheap to check.
    assert!(
        path.exists(),
        "the write should have landed at {} (the path this harness computed \
         from its own TMPDIR/TMP/TEMP override), not merely somewhere writable",
        path.display()
    );

    let _ = std::fs::remove_dir_all(&tmp);
}

// === Task 3 (std/fs on Strings increment): exists, create_dir,
// create_dir_all, remove_file, remove_dir_all ===

/// A fresh directory under the OS temp root, namespaced by `label` and this
/// test binary's own process id, for a fixture that calls Nova's `temp_dir()`.
///
/// Every fixture below (and `fs_write_then_read_run` above) builds its path
/// as `"${temp_dir()}/<literal>"` *inside the compiled Nova program*, per
/// this task's brief -- so, unlike `fs_invalid_data_run`'s bare relative
/// filename plus `.current_dir`, pointing the spawned `nova` process's
/// working directory elsewhere would not change the path the fixture
/// actually touches: `temp_dir()` resolves the OS-wide shared temp
/// directory regardless of the current directory. What Nova's `temp_dir()`
/// *does* respond to is the same thing Rust's `std::env::temp_dir()` (which
/// `nova_rt_fs_temp_dir` calls directly) responds to: the `TMP`/`TEMP`
/// (Windows) and `TMPDIR` (POSIX) environment variables, read fresh every
/// call rather than cached at process start. Setting them only on the
/// spawned `nova` `Command` -- never via `std::env::set_var` on this test
/// binary's own process -- keeps the override scoped to that one child, so
/// it cannot bleed into a sibling test running on another thread of this
/// same binary (`cargo test`'s default parallelism runs many `#[test]`s
/// concurrently within one process, all sharing one real environment).
///
/// The process id, folded in after `label`, is what keeps two *separate*
/// invocations of this test binary (a developer re-running the suite while
/// a previous run is still finishing; two overlapping CI jobs on one
/// machine) from resolving `temp_dir()` to the same directory. `label`
/// alone already keeps sibling fixtures inside a single run from colliding
/// with each other. See `fs_write_then_read_run`'s doc comment for the
/// fixed, run-invariant path this replaces.
fn unique_temp_dir(label: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("{label}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("unique temp dir for a std/fs fixture");
    dir
}

/// `write_string`, `read_to_string`, `exists`, and `remove_file` in one pass
/// -- the operations Task 2 and this task between them add a status-boundary
/// wrapper for, chained through one real file.
///
/// **The stdout check alone does not exercise `remove_file`'s success arm**:
/// the fixture prints "removed" whether or not anything was actually
/// deleted. Proven, not assumed: replacing `nova_rt_fs_remove_file`'s body
/// with a no-op returning `OK` left this test passing against the stdout
/// check alone (see the task report for the transcript) -- the same shape
/// of gap Task 2's review found in `write_string`. The explicit `exists`
/// assertion below, checking the raw filesystem directly rather than
/// through the builtin, is what actually exercises the success arm.
///
/// **The `exists(p)` calls inside the fixture itself, bracketing
/// `remove_file`, are a review addition, not brief text.** Task 3's review
/// (finding I1) found that every `exists()` call anywhere in this suite ran
/// on a directory (`fs_dirs.nova`'s `d`, always freshly made by
/// `create_dir_all`), so changing `nova_rt_fs_exists` to call `.is_dir()`
/// instead of `.exists()` still passed every fixture and every
/// `nova-runtime` test. `p` here is a plain file, so `.is_dir()` and
/// `.exists()` disagree on it before removal (`false` vs. the expected
/// `true`) -- proven by mutation, transcript in the task report. This is the
/// one deliberate departure from "the fixture's text is the brief,
/// transcribed verbatim" in this task, made after review rather than
/// pre-emptively, and `fs_roundtrip.stdout` was updated to match (`true`
/// after the write, `false` after the remove).
#[test]
fn fs_roundtrip_run() {
    let tmp = unique_temp_dir("nova-fs-roundtrip");
    let written_path = tmp.join("nova_fs_roundtrip_5d2c.txt");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_roundtrip.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_roundtrip.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let removed = !written_path.exists();
    let _ = std::fs::remove_dir_all(&tmp);
    assert!(
        removed,
        "remove_file should have actually deleted {}, not merely reported success",
        written_path.display()
    );
}

/// A second `create_dir` on an existing directory reports `AlreadyExists`.
/// The fixture's own leading `remove_dir_all` (discarding the result: absent
/// is fine, present is cleaned up) makes this independent of a previous
/// run's leftovers; `unique_temp_dir` makes it independent of a *concurrent*
/// one. Together they cover both halves of the race this task's brief
/// called out -- see `fs_write_then_read_run`'s doc comment.
#[test]
fn fs_already_exists_run() {
    let tmp = unique_temp_dir("nova-fs-already-exists");
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_already_exists.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_already_exists.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// `exists` bracketing a nested `create_dir_all`: absent, then present, then
/// absent again. Three calls rather than one so that a `nova_rt_fs_exists`
/// hard-coded to either `true` or `false` fails this fixture -- proven by
/// mutation in the task report, not just argued here.
#[test]
fn fs_dirs_run() {
    let tmp = unique_temp_dir("nova-fs-dirs");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_dirs.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_dirs.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

// === Task 4 (std/fs on Strings increment): read_dir, DirEntry ===

/// `read_dir` returns entries sorted by name, with `DirEntry.is_file`/`is_dir`
/// coming from one `fs_kind` call per entry. One entry (`Zebra.txt`) is
/// capitalized deliberately, so that byte-lexicographic sort (what the
/// runtime's `names.sort()` actually does: capitals order before lowercase)
/// disagrees with every case-insensitive or creation-order enumeration this
/// project has observed -- a missing `names.sort()` was measured to survive
/// an earlier, all-lowercase version of this fixture on this host, because
/// this host's raw directory order already happened to be alphabetical for
/// same-case names. See `tests/runtime/fs_read_dir.nova`'s own header and the
/// task report for the measurement.
///
/// This one fixture is written to discriminate three separate mutations:
/// dropping the sort (order changes), swapping `fs_kind`'s file/dir status
/// codes (the `mid` line inverts), and a wrong array length (a line goes
/// missing). See the task report for all three transcripts.
#[test]
fn fs_read_dir_run() {
    let tmp = unique_temp_dir("nova-fs-read-dir");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_read_dir.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_read_dir.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// The same fixture again with `NOVA_GC_STRESS=1` (collect on every
/// allocation) -- closing the other half of I4(b) from the final review.
///
/// **Why this fixture is the one that matters most, among the fs fixtures.**
/// This branch's own GC-rooting unit tests
/// (`a_stashed_string_is_rooted_until_it_is_taken`,
/// `stash_overwriting_an_occupied_slot_does_not_leak_the_displaced_root`) use
/// `gc::root_count`, which reads the root registry directly and never runs a
/// collection at all -- deliberately, per their own doc comments, because a
/// real collection inherits the conservative scanner's documented
/// intermittent over-retention (`docs/adr/0010-conservative-scan-root-test-gating.md`).
/// That leaves the actual end-to-end property -- a stashed payload survives a
/// collection that happens between the intrinsic call and the take --
/// guarded by nothing in this suite before this test. `read_dir` is the
/// richest fs fixture for exercising it: `stash_array` allocates one
/// `NovaStr` per entry inside a freshly rooted block, so with a collection
/// forced on every allocation, each element's string must survive both its
/// own allocation and every later one before `read_dir`'s Nova wrapper reads
/// the array back out.
///
/// Uses its own `unique_temp_dir` label so this directory never collides with
/// `fs_read_dir_run`'s, even though `cargo test`'s default parallelism can
/// run both concurrently in the same process (same pid, different label).
#[test]
fn fs_read_dir_under_gc_stress() {
    let tmp = unique_temp_dir("nova-fs-read-dir-stress");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fs_read_dir.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_read_dir.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

// === byte-type increment, Task 1: `Bytes` joins `RESERVED_TYPE_NAMES` ===

/// `Bytes` must join `nova_resolver::RESERVED_TYPE_NAMES`, so a user's own
/// `record Bytes { .. }` is rejected with `E0089` rather than becoming a
/// silently-unusable declaration -- shadowed by the built-in in every
/// signature or `impl`, yet still constructible and matchable, which is
/// exactly the confusing split `RESERVED_TYPE_NAMES`'s own doc explains
/// reservation exists to prevent.
///
/// A checked-in fixture rather than this file's usual temp-dir string for an
/// `E00xx` test: every earlier pin of the reserved-name mechanism lives in
/// `nova-typeck`'s own `mod tests` (`check_src` against an inline string), so
/// this is the first end-to-end, CLI-level confirmation that the declaration
/// is rejected the same way through the real binary.
///
/// `check`, not `run`: the rejection happens at name resolution, long before
/// anything would execute, and `main` here is empty besides.
#[test]
fn bytes_reserved_declaration_is_rejected() {
    let file = repo_root().join("tests/runtime/bytes_reserved.nova");
    let assert = nova().arg("check").arg(&file).assert().failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(stderr.contains("E0089"), "stderr: {stderr}");
}

// === byte-type increment, Task 2: Bytes representation, len and to_string ===

/// End-to-end: `bytes_from_string` builds a `Bytes` value, `Bytes::len` reads
/// its byte length, and `Bytes::to_string` round-trips valid UTF-8 back to a
/// `String` through the `Some` arm of the `Option<String>` it returns.
#[test]
fn bytes_basics_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/bytes_basics.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/bytes_basics.nova"))
        .assert()
        .success()
        .stdout(expected);
}

// === byte-type increment, Task 3: the rest of the byte surface ===

/// End-to-end: `bytes_from_ints` builds a non-UTF-8 buffer (byte `255`), and
/// every new method round-trips against it -- `byte_at` (both the in-range
/// and out-of-range arms), `slice`, `concat`, `to_ints` fed back through
/// `bytes_from_ints` and compared with `eq`, `index_of`, and `contains`. Byte
/// `255` is deliberate: it makes the buffer invalid UTF-8 (closing Task 2's
/// surviving `bytes_is_utf8` mutation, since Task 2's own fixtures never
/// exercised the "not UTF-8" arm end-to-end) and it proves `byte_at` returns
/// an unsigned value rather than a sign-extended `-1`.
///
/// **Two `eq` calls, deliberately not one.** `bytes_from_ints(b.to_ints()).eq(b)`
/// reconstructs a buffer that is byte-for-byte identical to `b`, so a
/// length-only `eq` mutation (comparing `len` alone, never the bytes) cannot
/// be told apart from a real one there -- both answer `true`. The second call
/// compares two three-byte buffers differing only in their last byte, which a
/// length-only comparison gets wrong (`true`) where a real one answers
/// `false`. Measured, not assumed: see the task report's mutation transcripts
/// for the run where the first call alone let that mutation survive.
///
/// **Review findings P1 and P3, folded in here rather than as separate
/// fixtures.** `b.slice(1, 100)` and `b.slice(100, 200)` both push a bound
/// past the buffer's 3-byte length -- the first past `end`, the second past
/// `start` as well -- which the original fixture never did (its only
/// `slice(0, 2)` call is in range on both bounds), so a missing
/// `.min(bytes.len())` on `nova_rt_bytes_slice`'s `hi` survived undetected;
/// see the task report for the mutation transcript. `bytes_from_ints([97,
/// 97, 97]).index_of(bytes_from_ints([97, 97]))` is the byte-domain mirror of
/// `tests/runtime/strings.nova`'s `"aaa".index_of("aa")`: the needle matches
/// at both index 0 and index 1, so this is what would catch `index_of`
/// returning the last match instead of the first -- the original fixture's
/// only search (`"i"` in `"hi\xff"`) matches exactly once and cannot tell the
/// two apart.
///
/// **Final-review findings D6 and D7, folded in here too.** `b.byte_at(0 - 1)`
/// is the byte-domain mirror of `tests/runtime/strings.nova`'s
/// `"héllo".char_at(0 - 1)`: `byte_at`'s negative-index guard had no fixture
/// coverage, so a deleted `if i < 0 { return None }` reached the
/// `bytes_at` intrinsic with a negative index and aborted the process
/// instead of returning `None`. `b.index_of(b)`/`b.contains(b)` cover the
/// equal-length needle/haystack case `tests/runtime/strings.nova` already
/// covers for `String`: changing `index_of`'s `n.len() > h.len()` guard to
/// `>=` survived the whole suite before this, since no prior call had a
/// needle exactly as long as its haystack.
#[test]
fn bytes_api_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/bytes_api.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/bytes_api.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same fixture through `nova build` -- a standalone linked executable
/// rather than the JIT. Closes the `nova build` half of the byte-type plan's
/// definition of done (§9): unlike `std/fs`'s fixtures, which inherit `nova
/// build`/`NOVA_GC_STRESS=1` coverage from that increment's existing gate
/// wiring, no `bytes_*` fixture ran under either configuration before this --
/// a gap the plan's own self-review caught before implementation, rather than
/// after. This fixture needs no temp directory or environment override, so it
/// is as cheap to route through `build_and_run` as `fs_not_found` was for the
/// `std/fs` increment.
#[test]
fn bytes_api_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/bytes_api.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let out = build_and_run("tests/runtime/bytes_api.nova", "bytes_api");
    assert_eq!(out.replace("\r\n", "\n"), expected);
}

/// The same fixture again with `NOVA_GC_STRESS=1` (collect on every
/// allocation) -- the other half of the byte-type plan's `nova build` /
/// `NOVA_GC_STRESS=1` definition-of-done gap. `to_ints`/`from_ints` allocate a
/// fresh scanned array block, `slice`/`concat`/`bytes_from_ints` each allocate
/// a fresh `Bytes` object, and `index_of`/`contains` hold both
/// operands' arrays live across a Nova-level loop -- so a collection forced on
/// every allocation exercises every new intrinsic's rooting, not only the
/// four already covered by `bytes_basics`/`bytes_len`.
#[test]
fn bytes_api_under_gc_stress() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/bytes_api.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/bytes_api.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Review finding P2 (Important): `bytes_from_ints`'s `0..=255` contract is
/// documented in three places (the plan, `bytes.rs`'s doc comment, and
/// `std/bytes/lib.nova`'s), and nothing exercised it -- replacing the
/// `u8::try_from`/`abort_with` pair with a wrapping `v as u8` passed the
/// whole suite, since nothing anywhere called it with a value outside the
/// range. An abort cannot be observed as a stdout diff (the process ends
/// before producing any more output), so this follows the same shape as
/// `panic_aborts_with_message`/`run_aborts_when_an_async_fn_calls_block_on`:
/// `nova run` on a fixture that aborts, asserting failure and the exact
/// `nova: panic:` message on stderr, exactly as `nova_rt_bytes_from_ints`'s
/// own `abort_with` call emits it.
///
/// This is the "too high" direction (`256`, one past the range). See
/// `bytes_from_ints_rejects_a_value_below_the_range` for "too low" (`-1`) --
/// covered separately because `u8::try_from` rejects each for a different
/// reason (`-1` fails on sign, `256` fails on magnitude), and a mutation
/// could plausibly get one direction right and the other wrong (e.g. `if v >
/// 255 { abort } else { v as u8 }` accepts `256`'s rejection but wraps `-1`
/// silently).
#[test]
fn bytes_from_ints_rejects_a_value_above_the_range() {
    let assert = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/bytes_from_ints_too_high.nova"))
        .assert()
        .failure();
    let out = assert.get_output();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("nova: panic: nova_rt_bytes_from_ints: element out of range 0..=255"),
        "stderr was {stderr:?}"
    );
    // Nothing after the aborting call ever runs.
    assert!(!stdout.contains('1'), "stdout was {stdout:?}");
}

/// The "too low" direction (`-1`) of P2 -- see the sibling test above.
#[test]
fn bytes_from_ints_rejects_a_value_below_the_range() {
    let assert = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/bytes_from_ints_too_low.nova"))
        .assert()
        .failure();
    let out = assert.get_output();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("nova: panic: nova_rt_bytes_from_ints: element out of range 0..=255"),
        "stderr was {stderr:?}"
    );
    assert!(!stdout.contains('1'), "stdout was {stdout:?}");
}

// === byte-type increment, Task 4: byte-based fs::read and fs::write ===

/// `write`/`read` round-trip a non-UTF-8 payload (bytes `0`, `255`, `10`,
/// `254`, `65`) through a real file: `len`, `eq` against the original
/// payload, and `to_string().is_none()` (this buffer is not valid UTF-8), so
/// a version that routed through `String` anywhere in the path -- write or
/// read -- cannot pass. See the task report's mutation transcripts for the
/// specific implementations this fixture was checked against.
#[test]
fn fs_bytes_roundtrip_run() {
    let tmp = unique_temp_dir("nova-fs-bytes-roundtrip");
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_bytes_roundtrip.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_bytes_roundtrip.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// The same fixture again with `NOVA_GC_STRESS=1` (collect on every
/// allocation). `nova_rt_fs_read` stashes a freshly allocated `Bytes` object
/// into the current task's `Slot::Buffer` entry, GC-rooting it
/// for exactly the span between the intrinsic call and the wrapper's own read
/// of that slot (`crates/nova-runtime/src/fs.rs`) -- the same rooting
/// contract `fs_read_dir_under_gc_stress` exists to exercise for
/// `stash_array`, applied here to the payload slot's newest producer. Its own
/// label keeps this directory from colliding with `fs_bytes_roundtrip_run`'s,
/// even though `cargo test`'s default parallelism can run both concurrently
/// in the same process.
#[test]
fn fs_bytes_roundtrip_under_gc_stress() {
    let tmp = unique_temp_dir("nova-fs-bytes-roundtrip-stress");
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_bytes_roundtrip.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_bytes_roundtrip.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// `read`'s and `write`'s `Err` arms, neither exercised by
/// `fs_bytes_roundtrip_run` (which only ever takes the success path for
/// both). **Proven by mutation, not argued**: deleting the `if status == 0`
/// check from either wrapper in `std/fs/lib.nova` -- so it unconditionally
/// returns `Ok`, discarding a real failure status -- left every target in
/// this workspace passing, `fs_bytes_roundtrip_run` included, the identical
/// shape of gap `fs_write_then_read_run`'s own doc comment records for
/// `write_string`. See the task report for both transcripts.
///
/// Needs no `unique_temp_dir`: like `fs_not_found_run`, neither branch ever
/// creates anything on disk (the whole point is that both fail before
/// touching the filesystem), so there is nothing to namespace or clean up and
/// a bare relative path cannot collide with a concurrent run the way a
/// created file or directory could.
#[test]
fn fs_bytes_errors_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fs_bytes_errors.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fs_bytes_errors.nova"))
        .assert()
        .success()
        .stdout(expected);
}

// === Task 3 (read-write-and-stdio increment): `std/io`'s `Read`/`Write`
// surface over the three standard streams, and `read_to_end`'s default ===

/// The stdout marker `tests/runtime/io_streams.nova` writes: `"Q".repeat(300)`
/// plus a trailing newline. Built the same way here as there, rather than
/// copied out as a 301-character literal, so a future change to the repeat
/// count is a one-word diff to compare instead of a wall of `Q`s to eyeball.
/// Deliberately 256 bytes or longer: a write's byte count crosses the
/// runtime boundary as 8 little-endian bytes
/// (`crates/nova-runtime/src/io.rs`'s `stash_count`), and a Nova-level decode
/// that read back only the first of them would under-report any count at or
/// above 256 without a marker this long catching it.
fn io_streams_stdout_marker() -> String {
    format!("{}\n", "Q".repeat(300))
}

/// The exact stderr content `tests/runtime/io_streams.nova` writes -- nothing
/// else in that fixture ever writes to stderr.
const IO_STREAMS_STDERR_MARKER: &str = "NOVA_STDERR_ONLY_MARKER\n";

/// `Read`/`Write` against the three real standard streams: `nova run` as a
/// child process with stdout and stderr captured as two independent
/// `std::process::Output` buffers, stdin fed a fixed string from this
/// harness rather than a terminal (so this test cannot hang waiting on one).
///
/// **The cross-stream check is the point of this test, not a bonus.** A
/// `Write for Stdout` wired to the wrong OS stream (or the reverse) still
/// produces a program that runs, exits `0`, and prints the right status
/// lines -- only capturing both streams separately and checking that each
/// contains *only* its own marker catches that. This is not hypothetical:
/// Task 1's own report records that exactly this mutation
/// (`nova_rt_io_stdout_write` writing to stderr) survived that task's entire
/// test suite, because nothing at that layer observes which real OS stream
/// received the bytes -- closing that gap is what this test exists for.
#[test]
fn io_streams_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/io_streams.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let assert = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/io_streams.nova"))
        .write_stdin("hello-stdin")
        .assert()
        .success();
    let out = assert.get_output();
    let stdout = String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n");
    let stderr = String::from_utf8_lossy(&out.stderr).replace("\r\n", "\n");

    assert_eq!(stdout, expected, "stdout did not match the golden fixture");
    assert_eq!(
        stderr, IO_STREAMS_STDERR_MARKER,
        "stderr must hold exactly the stderr marker and nothing else"
    );

    let stdout_marker = io_streams_stdout_marker();
    assert!(
        stdout.contains(&stdout_marker),
        "stdout must contain its own marker: {stdout:?}"
    );
    assert!(
        stderr.contains("NOVA_STDERR_ONLY_MARKER"),
        "stderr must contain its own marker: {stderr:?}"
    );
    // The negative half. Without this pair, a mutation that leaks one
    // stream's bytes into the other (rather than swapping them outright)
    // could still pass the two `.contains()` checks just above -- each of
    // those only checks "did my own marker appear somewhere," which stays
    // true even when the wrong stream *also* picked it up. This is what
    // actually catches bytes landing on the wrong stream in that case.
    assert!(
        !stdout.contains("NOVA_STDERR_ONLY_MARKER"),
        "stdout must not contain stderr's marker: {stdout:?}"
    );
    assert!(
        !stderr.contains(&stdout_marker),
        "stderr must not contain stdout's marker: {stderr:?}"
    );
}

/// `io_streams_run` again through `nova build` -- a standalone linked
/// executable rather than the JIT -- exercising the same cross-stream
/// separation on the other backend. Written inline rather than through the
/// shared `build_and_run` helper: that helper keeps only stdout, and the
/// entire point here is comparing both streams independently.
#[test]
fn io_streams_build_standalone() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/io_streams.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    let dir = std::env::temp_dir().join("nova-io-streams-build");
    std::fs::create_dir_all(&dir).expect("temp dir");
    let exe = dir.join(format!("io_streams{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(repo_root().join("tests/runtime/io_streams.nova"))
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();

    let assert = Command::new(&exe)
        .write_stdin("hello-stdin")
        .assert()
        .success();
    let out = assert.get_output();
    let stdout = String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n");
    let stderr = String::from_utf8_lossy(&out.stderr).replace("\r\n", "\n");
    let _ = std::fs::remove_file(&exe);

    assert_eq!(stdout, expected, "stdout did not match the golden fixture");
    assert_eq!(
        stderr, IO_STREAMS_STDERR_MARKER,
        "stderr must hold exactly the stderr marker and nothing else"
    );
    assert!(
        !stdout.contains("NOVA_STDERR_ONLY_MARKER"),
        "stdout must not contain stderr's marker: {stdout:?}"
    );
    assert!(
        !stderr.contains(&io_streams_stdout_marker()),
        "stderr must not contain stdout's marker: {stderr:?}"
    );
}

/// `Read::read_to_end`'s default body (`read_all` in `std/io`), pinned
/// against fake readers with fully deterministic results. See `tests/runtime/
/// io_read_to_end.nova`'s own doc comment for how its `Chunks` reader
/// advances state between calls despite Nova records being values with no
/// `&mut`, and for why a separate `Failing` reader is there too.
#[test]
fn io_read_to_end_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/io_read_to_end.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/io_read_to_end.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Runs `path` (`tests/runtime/io_broken_stdout.nova` or
/// `io_broken_stderr.nova`) as a child process, deterministically breaking
/// the pipe behind whichever of its stdout/stderr the fixture writes to,
/// then returns the exit status and the full text of the *other* (healthy)
/// stream.
///
/// **MEASURED on Windows only (fix round 1: deleting `write_stdout`'s,
/// `write_stderr`'s, `flush_stdout`'s or `flush_stderr`'s status check was
/// reachable-but-untested).** The mechanism: `std::process::Command` with
/// all three standard streams piped, `spawn`, then this immediately drops
/// the parent's read end of `break_stdout`'s stream (`child.stdout`/
/// `child.stderr`) -- *before* touching `child.stdin` at all. Both fixtures
/// block on `stdin().read(1).await` as their very first action, so at the
/// moment this function drops that handle the child provably has not
/// written anything to either stream yet; only after the drop does this
/// function close `child.stdin`, releasing the child to run past its stdin
/// read. This ordering is what makes the break race-free rather than
/// merely likely: the child cannot reach its own writes until this
/// function's close-then-release sequence has already happened.
///
/// Once the target stream's only reader is gone, an OS write to it fails
/// (`BrokenPipe`, mapped by `fs.rs`'s `fail` to `IoErrorKind::Other`) --
/// confirmed by reading the healthy stream's own reported results, not
/// assumed from the exit status alone. Rust's `Stdout` is line-buffered, so
/// a payload ending in `"\n"` fails at the `write()` call itself, while one
/// without a trailing newline only fails later, at the next `flush()` --
/// `io_broken_stdout_run` exploits that split to reach `write_stdout` and
/// `flush_stdout` independently. `Stderr` turned out not to line-buffer at
/// all (measured in `io_broken_stderr_run`, not assumed), so the same split
/// reaches only `write_stderr`; see that test's own doc comment for what
/// this means for `flush_stderr`. See `io_broken_stdout.nova`/
/// `io_broken_stderr.nova` for why the healthy stream's reporting must go
/// through `print`/`eprint` and never `println`/`eprintln`.
///
/// Not attempted on non-Windows CI: the mechanism (drop a pipe's read end,
/// observe the writer's next operation fail) is standard POSIX behaviour
/// too, and grepping this workspace found no `SIGPIPE`/`signal`/`sigaction`
/// handling anywhere in `nova-runtime` that would turn a broken pipe into a
/// killed process instead of an `Err` -- Rust's own default of ignoring
/// `SIGPIPE` should apply unmodified. That is a reason to expect it works,
/// not a measurement that it does; this environment has no Linux or macOS
/// host to run it on, so the gate below is what was actually verified
/// against, not a guess about what would also pass.
#[cfg(windows)]
fn run_with_a_broken_pipe(
    path: &std::path::Path,
    break_stdout: bool,
) -> (std::process::ExitStatus, String) {
    use std::io::Read;
    use std::process::Stdio;

    let mut child = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova"))
        .arg("run")
        .arg(path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn nova run");

    // Drop the parent's read end of the stream under test first, while the
    // child is still provably blocked on its own stdin read -- see this
    // function's own doc comment for why that ordering is what removes the
    // race rather than merely narrowing it.
    let mut healthy: Box<dyn Read> = if break_stdout {
        drop(child.stdout.take().expect("stdout was piped"));
        Box::new(child.stderr.take().expect("stderr was piped"))
    } else {
        drop(child.stderr.take().expect("stderr was piped"));
        Box::new(child.stdout.take().expect("stdout was piped"))
    };

    // Release the child from `stdin().read(1)` by closing its stdin.
    drop(child.stdin.take().expect("stdin was piped"));

    let mut out = String::new();
    healthy
        .read_to_string(&mut out)
        .expect("read the healthy stream to completion");
    let status = child.wait().expect("wait for the child");
    (status, out)
}

/// `write_stdout`'s and `flush_stdout`'s `Err` branches, reached through a
/// genuinely broken stdout pipe rather than argued to be unreachable. See
/// `run_with_a_broken_pipe`'s own doc comment for the mechanism and its
/// Windows-only scope, and `io_broken_stdout.nova`'s for why it reports on
/// stderr through `eprint` alone.
#[cfg(windows)]
#[test]
fn io_broken_stdout_run() {
    let (status, stderr) = run_with_a_broken_pipe(
        &repo_root().join("tests/runtime/io_broken_stdout.nova"),
        true,
    );
    assert!(status.success(), "the child process itself must exit 0");
    assert!(
        stderr.contains("write_stdout: err"),
        "write_stdout must report Err against a broken pipe: {stderr:?}"
    );
    assert!(
        stderr.contains("write_stdout_buffered: ok"),
        "a write with no trailing newline must still buffer successfully: {stderr:?}"
    );
    assert!(
        stderr.contains("flush_stdout: err"),
        "flush_stdout must report Err when the deferred write it flushes fails: {stderr:?}"
    );
}

/// `write_stderr`'s `Err` branch, reached the same way as
/// `io_broken_stdout_run`, against stderr instead.
///
/// **`flush_stderr`'s `Err` branch is NOT reached here, measured rather
/// than assumed.** `io_broken_stdout_run`'s deferred-write trick relies on
/// `Stdout` being line-buffered; `Stderr` is not buffered at all --
/// confirmed directly below, not inferred, because the *second* write (the
/// one with no trailing newline, which buffers and reports `Ok` for
/// stdout) already fails immediately here too. With nothing ever buffered,
/// the following `flush()` has nothing to flush and reports `Ok`
/// unconditionally, even though the pipe is still broken. So of the four
/// wrappers a mutated status check could hide behind, this fixture closes
/// three (`write_stdout`, `flush_stdout` above, `write_stderr` here);
/// `flush_stderr`'s status check has no fixture-reachable failure -- **settled, not open.**
/// Rust 1.95's own source closes it: `StderrLock::flush` reaches the shared `RefCell<StderrRaw>`
/// and calls `handle_ebadf(sys::stdio::Stderr::flush, || Ok(()))`, and the Windows platform
/// module's `impl io::Write for Stderr` hardcodes `fn flush(&mut self) -> io::Result<()> { Ok(())
/// }` -- there is no staging layer for a write to fail through, so this call cannot report `Err`
/// on this platform, by construction, regardless of the pipe's state. No second fixture technique
/// was needed: a Nova program has no way to invalidate its own file descriptors any more severely
/// than closing their readers, which this technique already does, and that would not matter here
/// regardless. **Measured by reading the standard library's own source on Windows; the identical
/// claim for Unix is reasoned from the same shape, not run** -- no Unix host was available to
/// check it. The `flush_stderr: ok` assertion below stays; it correctly pins today's platform
/// behaviour.
#[cfg(windows)]
#[test]
fn io_broken_stderr_run() {
    let (status, stdout) = run_with_a_broken_pipe(
        &repo_root().join("tests/runtime/io_broken_stderr.nova"),
        false,
    );
    assert!(status.success(), "the child process itself must exit 0");
    assert!(
        stdout.contains("write_stderr: err"),
        "write_stderr must report Err against a broken pipe: {stdout:?}"
    );
    assert!(
        stdout.contains("write_stderr_buffered: err"),
        "unlike stdout's, a write to stderr with no trailing newline must \
         still fail immediately against a broken pipe -- stderr does not \
         line-buffer: {stdout:?}"
    );
    assert!(
        stdout.contains("flush_stderr: ok"),
        "with nothing buffered (stderr never buffered either of the writes \
         above), flushing stderr must report Ok even though the pipe is \
         broken -- there is nothing pending for it to fail on: {stdout:?}"
    );
}

/// Runs `path` (`tests/runtime/io_read_stdin_write_only.nova`) as a child
/// process whose **stdin is a write-only file handle**, and returns the exit
/// status and the full text of its stdout.
///
/// **Reuses `run_with_a_broken_pipe`'s spawn shape but needs none of its
/// ordering (final review, I2).** That function must drop a pipe's read end
/// before releasing the child from its own stdin block, because the break
/// and the child's read race each other, and getting the order wrong would
/// let the child observe a still-healthy stream. There is no such race
/// here: `Stdio::from(File::create(..))` hands the child a handle that was
/// never readable from the moment the process was created, so the child's
/// very first `stdin().read(..)` fails at spawn-adjacent OS call time
/// rather than blocking on anything this harness must later release. Both
/// the child's stdout and stderr stay healthy -- only stdin is broken --
/// so this can capture output the ordinary way with `Command::output`,
/// unlike `run_with_a_broken_pipe`'s manual drop-then-read sequencing.
///
/// **`File::create` is deliberately write-only, not read-write.** On
/// Windows this opens with `GENERIC_WRITE` alone, no `GENERIC_READ`, and a
/// spawned child inherits that same restricted handle rather than a
/// broader one -- confirmed by `io_read_stdin_write_only_run`'s own
/// measured result, not assumed from the API name.
#[cfg(windows)]
fn run_with_a_write_only_stdin(path: &std::path::Path) -> (std::process::ExitStatus, String) {
    use std::process::Stdio;

    let stdin_path = std::env::temp_dir().join("nova_io_read_stdin_write_only_probe.txt");
    let stdin_file = std::fs::File::create(&stdin_path)
        .expect("create a write-only file to hand the child as its stdin");

    let output = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova"))
        .arg("run")
        .arg(path)
        .stdin(Stdio::from(stdin_file))
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("run nova with a write-only stdin");

    // Best-effort: a leaked probe file does not affect correctness, and this
    // harness has no child-process failure path that would leave the file
    // locked on Windows the way a still-open handle would.
    let _ = std::fs::remove_file(&stdin_path);

    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    (output.status, stdout)
}

/// `read_stdin`'s `Err` branch (`std/io/lib.nova`), reached deterministically
/// through a write-only stdin handle rather than argued to be hard to reach.
///
/// **Closes the gap the branch's own records called "plausibly genuinely
/// hard" (final review, I2).** That characterisation was true only of the
/// broken-pipe *technique*: closing a stdin pipe yields ordinary EOF
/// (`Ok(0)`), a path `read_stdin` already handles as success. A write-only
/// handle is a different failure shape entirely -- the read never reaches
/// EOF because it never reaches "empty"; it is refused before any bytes are
/// considered, and this fixture is what proves that mechanically rather
/// than by argument. This is not merely as deterministic as the
/// broken-pipe fixtures above: it is *more* so, because there is no
/// ordering to get right and no race window at all -- the handle is
/// write-only from the instant the child exists, not made so by an action
/// this harness takes after spawning.
///
/// **Measured on this host, not assumed:** deleting `read_stdin`'s status
/// check (`std/io/lib.nova`, replacing its `Err(IoError { .. })` arm with
/// `Ok(fs_take_bytes())`, the exact mutation the design named) turned this
/// test's output from `read_stdin: err PermissionDenied` into
/// `read_stdin: unexpectedly ok, len 0`, failing the assertion below with
/// that exact string in the panic message. Reverting the mutation restored
/// a pass. This doc comment describes what was actually run against this
/// fixture, in that order, not a plan for what the mutation ought to do.
///
/// `#[cfg(windows)]` in the same style as `run_with_a_broken_pipe`'s two
/// fixtures -- measured on Windows, reasoned rather than measured on Unix,
/// because no Unix host is available here -- but for a different mechanism,
/// not the same one: those two gate on `SIGPIPE`/`EPIPE` for a *write* to a
/// broken pipe, while this technique is a *read*. Rust's own `unix.rs`
/// shows `StdinRaw::read` wrapped in `handle_ebadf(.., || Ok(0))`, and a
/// file opened `O_WRONLY` is textbook-POSIX `EBADF` on a `read()` call --
/// so on Unix this exact technique would fold to `Ok(0)`, the identical
/// value correct code already returns for real EOF. **That is a reason to
/// expect this specific technique gives no signal there, not merely an
/// unmeasured one**: unlike `run_with_a_broken_pipe`'s mechanism, which is
/// reasoned to also *work* on Unix, this one is reasoned to *fold away* on
/// Unix, which is why this fixture does not attempt a non-Windows variant
/// rather than shipping one untested.
#[cfg(windows)]
#[test]
fn io_read_stdin_write_only_run() {
    let (status, stdout) = run_with_a_write_only_stdin(
        &repo_root().join("tests/runtime/io_read_stdin_write_only.nova"),
    );
    assert!(status.success(), "the child process itself must exit 0");
    assert!(
        stdout.contains("read_stdin: err PermissionDenied"),
        "a write-only stdin handle must make read_stdin's intrinsic report \
         PermissionDenied, not silently succeed on an empty read: {stdout:?}"
    );
}

// === Task 3 (file-open-openoptions increment): `std/fs`'s `File`,
// `OpenOptions`, `open`, and `impl Read`/`Write for File` ===

/// Open for writing, write, flush, close, reopen for appending, write, reopen
/// for reading, `read_to_end`, close — then reopen for writing once more to
/// prove that leg truncates what the append left. Exercises `impl Write for
/// File` (`write` and `flush`), `impl Read for File` (through `read_to_end`'s
/// default body in `std/io`, over `File`'s own `read`), the inherent
/// `File::close`, and all three `OpenOptions` constructors, following
/// `fs_bytes_roundtrip_run`'s shape. See the fixture's own doc comment for why
/// the append, re-truncate and flush legs are there — each kills a mutation
/// that survived the whole suite before them.
#[test]
fn file_roundtrip_run() {
    let tmp = unique_temp_dir("nova-file-roundtrip");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/file_roundtrip.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/file_roundtrip.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// The increment's core resource-lifetime behaviour: `close` is idempotent,
/// reading, writing or flushing a handle this fixture itself closed is an
/// ordinary `IoError` of kind `Other` rather than a panic, and a Nova program
/// can forge a `File` naming no file this module ever opened (`fd` is not
/// privacy-enforced) and get the exact same safe treatment. See
/// `tests/runtime/file_lifetime.nova`'s own doc comment for why `open_or_die`
/// is fixture-local glue rather than `std/fs` surface, and why it opens
/// read+write rather than through `OpenOptions::writing()`.
#[test]
fn file_lifetime_run() {
    let tmp = unique_temp_dir("nova-file-lifetime");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/file_lifetime.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/file_lifetime.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// `create_new` against an existing path, and a path under a missing parent
/// directory, measured `AlreadyExists`/`NotFound` on this host -- consistent
/// with `std/io/lib.nova`'s own doc comment, which already lists
/// `AlreadyExists` and `NotFound` among the kinds a real OS condition pins,
/// with no platform qualifier attached to either the way it attaches one to
/// `PermissionDenied` (see `file_open_dir_run` below).
///
/// **Not platform-gated, unlike `file_open_dir_run`.** This fixture used to
/// bundle a third, genuinely platform-divergent check (opening a directory
/// for reading) into the same golden `.stdout`, which meant the whole
/// fixture -- these two portable checks included -- ran on Windows only.
/// Review (fix round 1, Important 1) found that was also the *only* thing
/// backing up two of the five mandated mutations (`open`'s status check
/// deleted; `create_new` hardcoded false), since `open`/`OpenOptions` are
/// new this task and no pre-existing test can catch a regression in them
/// the way `io_streams_run` backs up the shared decoder. Moving the
/// directory check to its own fixture (`file_open_dir.nova`,
/// `file_open_dir_run` below) is what lets these two run, and those two
/// mutations be caught, on every platform this project targets.
#[test]
fn file_errors_run() {
    let tmp = unique_temp_dir("nova-file-errors");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/file_errors.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/file_errors.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

/// Opening a directory for reading, split out of `file_errors_run` above
/// (fix round 1, Important 1) because it is the one genuinely
/// platform-divergent check among that fixture's original three --
/// measured `PermissionDenied` on this host, consistent with
/// `std/io/lib.nova`'s own doc comment's "(Windows only) `PermissionDenied`"
/// note. **Reasoned, not measured, since no POSIX host is available in this
/// environment:** POSIX `open(2)` permits read-only access to a directory
/// (needed for e.g. reading it back by fd), so this exact call would
/// plausibly *succeed* on Linux/macOS rather than fail, with a failure only
/// reachable from an actual `read()` afterward -- reporting `IsADirectory`,
/// a kind `crates/nova-runtime/src/fs.rs`'s `fail` has no arm for and
/// therefore maps to `Other`, not `PermissionDenied`. This fixture now
/// holds only this one check, so gating it -- rather than a fixture with
/// portable checks bundled in -- costs nothing on non-Windows platforms:
/// the same shape `fs_permission_denied_run` already uses for its own
/// directory-flavoured, Windows-only check.
#[cfg(windows)]
#[test]
fn file_open_dir_run() {
    let tmp = unique_temp_dir("nova-file-open-dir");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/file_open_dir.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/file_open_dir.nova"))
        .env("TMPDIR", &tmp)
        .env("TMP", &tmp)
        .env("TEMP", &tmp)
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_dir_all(&tmp);
}

// === Task 6 (I/O poller and std/net increment): std/net fixtures ===
//
// Every fixture below *except* `net_listener_accept_run` needs a real TCP
// peer at a port it cannot know in advance (the OS hands out an ephemeral
// one), so each of those tests binds one itself and hands the Nova program
// the port number through a file: `EchoServer` (and
// `write_refused_port_file`, for the one fixture that wants nothing
// listening) writes it, and the paired `.nova` fixture reads it back with
// `fs::read_to_string`.
//
// `net_listener_accept_run` is the exception and needs none of that
// machinery: both ends of its connection are Nova, in two tasks of one
// process, so it binds `127.0.0.1:0` itself and passes the kernel's choice
// to a spawned client as an ordinary argument. The paragraph below therefore
// does not describe it either -- with no port file, it has no port-file path
// to collide on.
//
// **That file's path is derived from the fixture's own name alone, not this
// process** — unlike `unique_temp_dir`, which folds in `std::process::id()`
// specifically to keep concurrent runs of this same binary from colliding.
// Two concurrent `cargo test` invocations racing the *same* test would
// collide on this path — the identical latent hazard `write_test_project`'s
// fixed `unique_name`-only directory already carries (see that function's
// own comment, above). A fixed port would be flakier (a stale process, or a
// genuinely concurrent suite run, could already hold it) and generating the
// `.nova` source itself would break the static-file-plus-golden convention
// every other runtime fixture in this file follows, so this hazard is
// accepted rather than engineered around, the same call this file already
// makes for `write_test_project`. None of these fixtures touch `TMPDIR`/
// `TMP`/`TEMP`: Nova's `temp_dir()` and this harness's own
// `std::env::temp_dir()` calls therefore resolve to the identical, real OS
// temp directory on both sides with no override needed.

/// A one-shot loopback TCP server for a `std/net` fixture: binds
/// `127.0.0.1:0`, writes the ephemeral port to a well-known path the paired
/// `.nova` fixture reads with `fs::read_to_string`, then accepts exactly one
/// connection and echoes back whatever it reads, byte for byte, until the
/// peer's own half closes.
///
/// `delay_ms`, when non-zero, sleeps once right after `accept` and before
/// the first read — long enough that a fixture's `read`/`read_timeout`
/// against this connection is guaranteed to find nothing yet and genuinely
/// suspend, rather than racing real loopback latency (which is normally fast
/// enough that a plain round trip could occasionally resolve before a
/// sibling task ever got a turn). `net_interleave_run` and `net_timeout_run`
/// both depend on this; `net_roundtrip_run` and `net_lifetime_run` pass `0`.
///
/// The accepting thread polls a non-blocking listener against `shutdown`
/// rather than blocking in `accept` forever, so a fixture that never
/// connects at all (a failing test, before it ever reaches `connect`) still
/// lets `Drop` join the thread and end the process cleanly instead of
/// leaking one parked in a blocking `accept` for the rest of this test
/// binary's life.
struct EchoServer {
    port_path: std::path::PathBuf,
    shutdown: std::sync::Arc<std::sync::atomic::AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl EchoServer {
    fn start(label: &str, delay_ms: u64) -> EchoServer {
        let listener =
            std::net::TcpListener::bind("127.0.0.1:0").expect("bind an ephemeral loopback port");
        listener
            .set_nonblocking(true)
            .expect("listener supports non-blocking accept");
        let port = listener
            .local_addr()
            .expect("bound listener has a local address")
            .port();
        let port_path = std::env::temp_dir().join(format!("nova_{label}_port.txt"));
        std::fs::write(&port_path, port.to_string())
            .expect("write the port file the paired fixture reads");

        let shutdown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let shutdown_for_thread = std::sync::Arc::clone(&shutdown);
        let handle = std::thread::spawn(move || {
            let mut stream = loop {
                match listener.accept() {
                    Ok((stream, _)) => break stream,
                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        if shutdown_for_thread.load(std::sync::atomic::Ordering::SeqCst) {
                            return;
                        }
                        std::thread::sleep(std::time::Duration::from_millis(5));
                    }
                    Err(_) => return,
                }
            };
            // Reverts to blocking for this thread's own reads/writes below —
            // this thread has nothing else to do while serving one
            // connection, so there is no reason to poll it too.
            if stream.set_nonblocking(false).is_err() {
                return;
            }
            if delay_ms > 0 {
                std::thread::sleep(std::time::Duration::from_millis(delay_ms));
            }
            let mut buf = [0u8; 4096];
            loop {
                match std::io::Read::read(&mut stream, &mut buf) {
                    Ok(0) | Err(_) => return,
                    Ok(n) => {
                        if std::io::Write::write_all(&mut stream, &buf[..n]).is_err() {
                            return;
                        }
                    }
                }
            }
        });

        EchoServer {
            port_path,
            shutdown,
            handle: Some(handle),
        }
    }
}

impl Drop for EchoServer {
    fn drop(&mut self) {
        self.shutdown
            .store(true, std::sync::atomic::Ordering::SeqCst);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
        let _ = std::fs::remove_file(&self.port_path);
    }
}

/// A port on `127.0.0.1` with nothing listening: reserve an ephemeral one,
/// then immediately drop the listener so the OS releases it again before any
/// fixture connects. `net_refused_run`'s loopback `connect` to this port
/// gets an OS-level refusal — an immediate RST, needing no network round
/// trip (`crates/nova-runtime/src/net.rs`'s own module doc comment) — rather
/// than a hardcoded high port number some other process on the host might
/// genuinely be listening on.
///
/// **Accepted, unengineered race:** between the `drop` below and the fixture's
/// own `connect`, nothing stops the OS handing that just-released port to some
/// other process, which would turn the expected refusal into a connection and
/// fail `net_refused_run`. Measured at 0 occurrences in 40 consecutive runs on
/// this project's own hosts, and closing it would mean holding a port open to
/// prove nothing is listening on it — so it is recorded here rather than
/// engineered around.
///
/// **The window is structurally narrower than that paragraph implies, measured
/// 2026-08-28.** Ephemeral ports are issued sequentially from a *system-wide*
/// cursor: 300 successive binds returned 300 distinct ports spanning 309, and
/// a freed port was not reissued for roughly 13,759 further binds. So the port
/// dropped below sits BEHIND the cursor, and the next bind — in this process or
/// any other — receives one ahead of it rather than this one. That is why the
/// count above stayed at zero, and it is a better reason than the count: a
/// mechanism, not a sample. The race is still real in principle, since nothing
/// forbids the cursor wrapping at exactly the wrong moment, so the decision to
/// record rather than engineer around it is unchanged — merely better founded.
///
/// The same measurement retracted a *different* claim, and the contrast is the
/// useful part: `dead_addr` in `crates/nova-runtime/src/net.rs` had this shape
/// blamed for an actual intermittent failure, on the theory that a concurrent
/// binder *in the same process* took the port. That mechanism is refuted. This
/// comment never made that claim — it said "some other process" from the start,
/// which is the version measurement did not touch.
fn write_refused_port_file(label: &str) -> std::path::PathBuf {
    let listener =
        std::net::TcpListener::bind("127.0.0.1:0").expect("bind an ephemeral loopback port");
    let port = listener
        .local_addr()
        .expect("bound listener has a local address")
        .port();
    drop(listener);
    let port_path = std::env::temp_dir().join(format!("nova_{label}_port.txt"));
    std::fs::write(&port_path, port.to_string())
        .expect("write the port file the paired fixture reads");
    port_path
}

/// `connect`, `impl Write for TcpStream`, `impl Read for TcpStream`, and
/// `TcpStream::close` against a real loopback echo server. See the
/// fixture's own header for why this alone cannot tell a real poller from a
/// blocking one — `net_interleave_run`, below, is the test that can.
#[test]
fn net_roundtrip_run() {
    let _server = EchoServer::start("net_roundtrip", 0);
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/net_roundtrip.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/net_roundtrip.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The fixture that decides the increment: asserts that a sibling task's own
/// output lands between a socket task's "wrote" and "read" lines, which only
/// a real, non-blocking poller can produce. See
/// `tests/runtime/net_interleave.nova`'s own header for the full reasoning,
/// including why `connect` runs before either task is spawned.
///
/// The paired server sleeps 150ms after accepting before echoing anything —
/// long enough for the counter task's three `yield_now` steps (each costing
/// no real wall-clock time at all) to run to completion while the reader
/// waits, on any machine this suite runs on, and short enough not to slow
/// the suite down.
#[test]
fn net_interleave_run() {
    let _server = EchoServer::start("net_interleave", 150);
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/net_interleave.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/net_interleave.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `TcpStream::read_timeout` in both directions: too-short and comfortably
/// long, against one real connection. See `tests/runtime/net_timeout.nova`'s
/// own header for why both directions matter.
///
/// The paired server sleeps 250ms after accepting before echoing anything —
/// comfortably longer than the fixture's own 80ms short deadline and
/// comfortably shorter than its 3000ms long one.
#[test]
fn net_timeout_run() {
    let _server = EchoServer::start("net_timeout", 250);
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/net_timeout.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/net_timeout.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `connect` against a loopback port nothing is listening on —
/// `ConnectionRefused`'s first producer end to end. See
/// `tests/runtime/net_refused.nova`'s own header.
#[test]
fn net_refused_run() {
    let port_path = write_refused_port_file("net_refused");
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/net_refused.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/net_refused.nova"))
        .assert()
        .success()
        .stdout(expected);
    let _ = std::fs::remove_file(&port_path);
}

/// The increment's core resource-lifetime behaviour for `TcpStream`: `close`
/// is idempotent, reading, writing or timing out a handle this fixture
/// itself closed is an ordinary `IoError` of kind `Other` rather than a
/// panic, `flush` stays a no-op even then, and a Nova program can forge a
/// `TcpStream` naming no connection this module ever opened (`fd` is not
/// privacy-enforced) and get the exact same safe treatment. See
/// `tests/runtime/net_lifetime.nova`'s own header, which follows
/// `file_lifetime.nova`'s shape exactly.
#[test]
fn net_lifetime_run() {
    let _server = EchoServer::start("net_lifetime", 0);
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/net_lifetime.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/net_lifetime.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `bind`, `local_port`, `accept` and both `close`s, end to end, with a real
/// connection crossing the listener. **The only `std/net` fixture with no
/// port file and no Rust peer**: both ends are Nova, in two tasks of one
/// process, so the listener binds `127.0.0.1:0` itself and hands the
/// kernel's choice to a spawned client task as a plain `spawn` argument.
///
/// This said "**the only `std/net` fixture that needs no `EchoServer`**",
/// which `net_refused_run` falsifies — its entire point is that nothing is
/// listening, so it touches no `EchoServer` either, and the section header
/// above this group already names it for exactly that reason. The property
/// stated above is the one that is genuinely exclusive, and it survives the
/// group growing: `net_refused_run` does write a port file, so this stays
/// the one `net_*` fixture needing neither a port file nor a Rust peer.
///
/// Also `local_port`'s only runtime fixture, which is why it exists as much
/// as the round trip is: `RtFunc::NetClose` and `RtFunc::NetLocalPort` are
/// indistinguishable in `RtFunc::signature`, and this pins the one direction
/// of that swap nothing else could. See the fixture's own header.
#[test]
fn net_listener_accept_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/net_listener_accept.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/net_listener_accept.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `Duration`'s three constructors and two accessors, over fixed inputs with
/// no real clock involved. See `tests/runtime/time_conversions.nova`'s own
/// header for why the fourth line (`from_micros(1).as_millis()` is `0`) is
/// pinned deliberately rather than accidental.
#[test]
fn time_conversions_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/time_conversions.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/time_conversions.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Four printed lines: `Duration`'s three constructors -- `from_secs`,
/// `from_millis`, `from_micros` -- each given one argument past its upper
/// cap, which an unclamped constructor would wrap into a negative `Int`,
/// plus `from_secs` given one argument past its lower cap, on the negative
/// side, which an unclamped constructor would wrap the other way -- into a
/// positive `Int` byte-identical to the correctly-clamped result on the
/// first line. That second direction is the more insidious failure: an
/// unclamped negative wraps to roughly +292 years, so `sleep` of it would
/// park for centuries where it should wake immediately. A fifth line covers
/// `Instant::duration_since` saturating at zero when the arguments are the
/// wrong way round. See `tests/runtime/time_saturation.nova`'s own header.
#[test]
fn time_saturation_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/time_saturation.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/time_saturation.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `Instant::now`/`elapsed`/`duration_since` against the real monotonic
/// clock. A real clock varies, so the fixture asserts a range rather than a
/// value; see `tests/runtime/time_elapsed.nova`'s own header. The fixture
/// sleeps 5ms and requires the measured elapsed time to cover it -- that
/// sleep is the only thing in the whole test suite that would fail against
/// a frozen or mis-wired clock, so it is load-bearing, not incidental, and
/// must survive any future trim of the suite's running time.
#[test]
fn time_elapsed_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/time_elapsed.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/time_elapsed.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// ISO-8601 rendering over fixed nanosecond inputs, so the assertion is on
/// known values rather than on a live clock. The six rows pin the epoch, two
/// leap days, the 2100 non-leap-year, a year boundary, and zero-padding.
#[test]
fn system_time_iso8601_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/system_time_iso8601.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/system_time_iso8601.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The live clock, asserted on shape rather than value: the year must be a
/// plausible four digits and the rendering must be exactly 24 characters
/// ending in `Z`. A process-relative reading would render as 1970 and fail
/// the first check.
#[test]
fn system_time_now_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/system_time_now.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/system_time_now.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `timeout` when the inner future completes well inside the deadline:
/// `Ok`'s branch runs, not `Err`'s. Prints which branch ran, not an
/// ordering, so a unit error in the comparison cannot pass by accident.
#[test]
fn timeout_ok_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/timeout_ok.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_ok.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `timeout` when the deadline elapses well before the inner future would
/// finish: `Err`'s branch runs, not `Ok`'s. The inner future is never
/// spawned, so abandoning it costs nothing further once the deadline fires.
#[test]
fn timeout_elapsed_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/timeout_elapsed.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_elapsed.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `timeout` returning the inner future's value, not the combinator's status.
///
/// The one fixture that distinguishes those -- see `tests/runtime/
/// timeout_value.nova`'s own header for why a "wrong slot" mutation can't be
/// demonstrated at the Nova-source level (the type checker rejects it) and
/// what this fixture actually guards instead. Measured, not reasoned: a
/// slot-layout bug in `poll_timeout` (writing the combinator's status into the
/// *inner's* output slot too) fails **this test and nothing else in the
/// workspace**. A `nova-mir` `Builtin::TaskOutput` lowering bug also makes this
/// fixture print `0` instead of `42`, but so does every other test that reads a
/// value through that lowering -- eight failures in this file when measured, and
/// not a stable number to quote (three measurements gave 18, 7 and 8) -- so this
/// fixture is not what guards that; an earlier version of the header claimed
/// otherwise for both.
#[test]
fn timeout_value_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/timeout_value.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_value.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `timeout` wrapping a `JoinHandle::join()` future on a task that finishes
/// well inside the deadline: one of the Task+Deadline pair that aborted the
/// process before Task 1 widened the executor's park set.
#[test]
fn timeout_join_ok_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/timeout_join_ok.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_join_ok.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `timeout` wrapping a `JoinHandle::join()` future on a task that sleeps
/// past the deadline: the other half of the Task+Deadline pair that aborted
/// the process before Task 1 widened the executor's park set. The spawned
/// task keeps running after the join is abandoned, so this fixture's own
/// sleep is kept short rather than dramatic.
#[test]
fn timeout_join_elapsed_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/timeout_join_elapsed.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_join_elapsed.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// An elapsed `timeout` over a join, followed by a second `join().await` in
/// the same task: the abandoned inner's `Wait::Task` must not survive into the
/// next suspension of that same task poll.
///
/// Before `poll_timeout` restored `PENDING_PARK`, this aborted the process
/// with "two parks staged in one poll" and an exit code of 127 -- from
/// ordinary Nova source. `.success()` plus the golden is therefore the whole
/// assertion: the abort produced neither.
#[test]
fn timeout_elapsed_then_join_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/timeout_elapsed_then_join.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_elapsed_then_join.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Two sequential elapsing `timeout`s over joins -- the same abandonment
/// leftover, crossed by a second combinator rather than by a bare `join`, and
/// the idiomatic shape (a retry loop, or two timed joins in sequence).
#[test]
fn timeout_elapsed_twice_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/timeout_elapsed_twice.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/timeout_elapsed_twice.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// No `init` call anywhere: the default threshold is `Info`, so `Trace` and
/// `Debug` are dropped while `Info`, `Warn` and `Error` reach stderr.
/// `Info` at threshold `Info` is what fails if `<` becomes `<=` -- though not
/// uniquely. Every fixture here logs a message at its own threshold, so all
/// five catch that mutation; this one is simply the cheapest to read. An
/// earlier version of this comment claimed it was the only one, which was
/// measured false by running the isolated mutation against all five.
///
/// The stdout golden is asserted as well, and pins what the stderr assertion
/// cannot: that the program ran to *completion*. Without it, a logger that
/// emitted three correct lines and then died would still pass.
#[test]
fn log_default_level_run() {
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/log_default_level.nova"))
        .assert()
        .success();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).replace("\r\n", "\n");
    let levels: Vec<&str> = stderr
        .lines()
        .map(|l| l.split_once(' ').expect("line starts with a timestamp").1)
        .collect();
    assert_eq!(
        levels,
        vec!["INFO yes-info", "WARN yes-warn", "ERROR yes-error"]
    );
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/log_default_level.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    let stdout = String::from_utf8_lossy(&out.get_output().stdout).replace("\r\n", "\n");
    assert_eq!(stdout, expected);
}

/// `init_with` at `Warn` raises the threshold above the default `Info`:
/// `info` is silenced while `warn` and `error` still reach stderr.
#[test]
fn log_init_with_threshold_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/log_init_with_threshold.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/log_init_with_threshold.nova"))
        .assert()
        .success()
        .stdout(expected);
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).replace("\r\n", "\n");
    let levels: Vec<&str> = stderr
        .lines()
        .map(|l| l.split_once(' ').expect("line starts with a timestamp").1)
        .collect();
    assert_eq!(levels, vec!["WARN kept-warn", "ERROR kept-error"]);
}

/// Logging once at the default threshold and then calling `init_with` to
/// raise it: the last write wins, so the first stderr line is at `Info`
/// (before the reconfigure) and the second is at `Error` (after). This is
/// the fixture that fails if a getter reads a hardcoded default instead of
/// the runtime's cell.
#[test]
fn log_reconfigure_after_logging_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/log_reconfigure_after_logging.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/log_reconfigure_after_logging.nova"))
        .assert()
        .success()
        .stdout(expected);
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).replace("\r\n", "\n");
    let levels: Vec<&str> = stderr
        .lines()
        .map(|l| l.split_once(' ').expect("line starts with a timestamp").1)
        .collect();
    assert_eq!(levels, vec!["INFO before", "ERROR after-kept"]);
}

/// `output: Stdout` moves the line off stderr entirely: this is the fixture
/// that fails if `eprintln` and `println` are swapped inside `emit`.
#[test]
fn log_stdout_output_run() {
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/log_stdout_output.nova"))
        .assert()
        .success();
    let output = out.get_output();
    let stderr = String::from_utf8_lossy(&output.stderr).replace("\r\n", "\n");
    assert_eq!(stderr, "", "stderr should be empty: {stderr}");
    let stdout = String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n");
    let lines: Vec<&str> = stdout.lines().collect();
    assert_eq!(lines.len(), 1, "stdout: {stdout}");
    let (_, rest) = lines[0]
        .split_once(' ')
        .expect("line starts with a timestamp");
    assert_eq!(rest, "INFO on-stdout");
}

/// All five labels, at threshold `Trace` so every one emits, routed to
/// stdout so a live clock doesn't need stderr capture too. This pins the
/// five label strings and their emit order at a threshold that admits every
/// level. It does *not* catch `Warn` and `Error` swapping in
/// `LogLevel::to_int` -- measured: at threshold `Trace` every level's
/// `to_int()` clears the filter regardless of numbering, and `label()`
/// (`std/log/lib.nova`) never consults `to_int()`, so the output is
/// byte-identical under that swap. `log_init_with_threshold_run` is the
/// fixture that catches it: its threshold is `Warn`, so the swap pushes
/// `Error` below it and `"ERROR kept-error"` disappears.
#[test]
fn log_level_labels_run() {
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/log_level_labels.nova"))
        .assert()
        .success();
    let output = out.get_output();
    let stderr = String::from_utf8_lossy(&output.stderr).replace("\r\n", "\n");
    assert_eq!(stderr, "", "stderr should be empty: {stderr}");
    let stdout = String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n");
    let levels: Vec<&str> = stdout
        .lines()
        .map(|l| l.split_once(' ').expect("line starts with a timestamp").1)
        .collect();
    assert_eq!(
        levels,
        vec!["TRACE a", "DEBUG b", "INFO c", "WARN d", "ERROR e"]
    );
}

/// `Log::init()` must install exactly the runtime's default -- `Info`
/// threshold, stderr -- not whatever `init_with` left behind. The fixture
/// first installs a configuration wrong in *both* fields (`Error` threshold,
/// `Stdout` destination); a correct `init()` overwrites it, so `debug` stays
/// silenced and `info` reaches stderr. This is the fixture that pins
/// `std/log/lib.nova`'s `init()` literal against the runtime's `DEFAULT`
/// (`crates/nova-runtime/src/log.rs`): a wrong level drops the `info` line
/// entirely, and a wrong destination moves it to stdout instead.
#[test]
fn log_init_resets_to_default_run() {
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/log_init_resets_to_default.nova"))
        .assert()
        .success();
    let output = out.get_output();
    let stderr = String::from_utf8_lossy(&output.stderr).replace("\r\n", "\n");
    let levels: Vec<&str> = stderr
        .lines()
        .map(|l| l.split_once(' ').expect("line starts with a timestamp").1)
        .collect();
    // Stdout is asserted *first*, deliberately, so a failure says which field
    // of `init()`'s default drifted rather than only that one did. The two
    // mutations this test exists to catch are otherwise indistinguishable: a
    // wrong level drops the line, a wrong destination moves it, and both leave
    // stderr empty. Checking stdout first separates them -- a misrouted line
    // shows up here as an unexpected extra line, while a dropped one leaves
    // stdout correct and fails the stderr assertion below.
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/log_init_resets_to_default.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    let stdout = String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n");
    assert_eq!(stdout, expected);
    assert_eq!(levels, vec!["INFO yes"]);
}

/// Zero-padding an Int: single digit, zero, a negative where the sign counts
/// toward the width, an over-wide value returned unpadded, and a negative
/// width clamped by the early return.
#[test]
fn fmt_int_pad_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fmt_int_pad.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fmt_int_pad.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Space-padding a String at a width above, equal to and below its length.
/// The brackets in the fixture make trailing padding visible in the golden.
#[test]
fn fmt_string_pad_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fmt_string_pad.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fmt_string_pad.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Fixed-place decimal rendering: two values whose default rendering is long
/// and imprecise, a zero-places truncation, and a trailing zero the value
/// does not itself carry.
#[test]
fn fmt_float_fixed_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/fmt_float_fixed.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fmt_float_fixed.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Non-finite `Float` values (NaN, +/- infinity) rendering as Rust renders
/// them, and a negative `places` clamped to zero rather than panicking.
#[test]
fn fmt_float_edge_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/fmt_float_edge.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/fmt_float_edge.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// One task, no contention: lock, read through the guard, release, and the
/// mutex is free again.
#[test]
fn sync_mutex_uncontended_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/sync_mutex_uncontended.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_uncontended.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A second `try_lock` fails while the first guard is live and succeeds after
/// it is released.
#[test]
fn sync_mutex_try_lock_fails_when_held_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/sync_mutex_try_lock_fails_when_held.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_try_lock_fails_when_held.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `release` twice on the same guard is a no-op. Note what this fixture
/// cannot see: it releases twice with no intervening acquire, so it passes
/// even with `MutexGuard`'s `released` flag removed.
/// `sync_mutex_stale_guard_cannot_steal_run` is the one that covers that.
#[test]
fn sync_mutex_release_is_idempotent_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/sync_mutex_release_is_idempotent.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_release_is_idempotent.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Two tasks each read a shared counter, suspend, then write it back, under
/// the mutex. Serialised the answer is 2; interleaved it is 1, because both
/// read 0 and the second write clobbers the first. The `yield_now` inside the
/// critical section is what makes this test able to fail -- a section with no
/// suspension point is already protected by cooperative scheduling.
#[test]
fn sync_mutex_two_tasks_serialise_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/sync_mutex_two_tasks_serialise.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_two_tasks_serialise.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The same lost-update test over a bare `Mutex<Int>` rather than a record
/// wrapper, which is what `MutexGuard::set` is for: `get` copies an `Int` out,
/// so mutating the copy cannot reach the mutex. This fixture does not compile
/// without `set`.
#[test]
fn sync_mutex_int_set_serialises_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/sync_mutex_int_set_serialises.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_int_set_serialises.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A guard released once, then released again after another task has taken the
/// lock, must not free it. This is the case `sync_mutex_release_is_idempotent`
/// cannot see: it releases twice with no intervening acquire, so an
/// unconditional `self.owner.locked = false` passes it. `MutexGuard`'s
/// `released` flag is what makes the documented idempotence true here. Pins
/// `release`'s use of that flag only -- `set`'s use is pinned by
/// `sync_mutex_stale_guard_cannot_write_run` below. Depends on the executor's
/// FIFO ready queue to place the stale release inside the holder's critical
/// section; the fixture's own comment says so and why it matters.
#[test]
fn sync_mutex_stale_guard_cannot_steal_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/sync_mutex_stale_guard_cannot_steal.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_stale_guard_cannot_steal.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A stale guard's `set` must not reach the protected value while another task
/// is inside its critical section. This is `set`'s half of what `released`
/// closes, and the half that shipped uncovered: deleting `set`'s early return
/// failed no test in the suite until this fixture existed. Same FIFO ready-queue
/// dependency as the fixture above, and the same warning in its comment.
#[test]
fn sync_mutex_stale_guard_cannot_write_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/sync_mutex_stale_guard_cannot_write.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/sync_mutex_stale_guard_cannot_write.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn channel_uncontended_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/channel_uncontended.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_uncontended.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn channel_full_refuses_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/channel_full_refuses.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_full_refuses.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn channel_fifo_order_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/channel_fifo_order.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_fifo_order.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn channel_close_refuses_send_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_close_refuses_send.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_close_refuses_send.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn channel_close_then_drain_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/channel_close_then_drain.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_close_then_drain.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A producer sending 5 values through a channel of capacity 2, and a consumer
/// draining it, each in its own task. The only fixture in which `send` and
/// `recv` actually suspend and resume. Every other `channel_*` fixture either
/// never calls the async pair at all -- the synchronous ones, which use
/// `try_send`/`try_recv` and so cannot suspend -- or calls it and answers
/// without ever reaching a yield: the two `*_suspends_only_to_retry` fixtures
/// deliberately never enter either retry path, and
/// `channel_send_refuses_when_closed` calls the async `send` twice, the first
/// succeeding on an empty capacity-2 channel and the second refused by
/// `send`'s own `closed` check, which precedes the yield. That partition is
/// stated as a property over the whole population rather than as a count on
/// purpose: a count over that population falsified this sentence twice
/// before, and the fixture registered below would have falsified it a third
/// time. Capacity
/// below the send count is what forces `send` to suspend, and it also makes
/// `head` wrap twice. Depends on the executor's FIFO ready queue
/// (`crates/nova-runtime/src/task.rs:184`) for a deterministic interleaving;
/// the fixture's own comment says so and why.
#[test]
fn channel_two_tasks_blocking_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_two_tasks_blocking.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_two_tasks_blocking.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Pins that `recv` does not suspend when a value is already buffered, i.e.
/// that its `yield_now().await` lives on the retry path and nowhere else --
/// measured against that yield moved to either side of the loop, before the
/// first `pop` and after the loop, both of which this catches. Loading the
/// channel before either task is spawned is what makes `consume`'s first `pop`
/// succeed so the retry loop is never entered; the fixture's `close` is a
/// termination guard rather than part of that, and its comment records why
/// deleting it would turn this failure into a hang.
///
/// `channel_two_tasks_blocking` is blind to the placement -- moving that
/// `yield_now` out of its retry loop leaves it and every other test in the
/// suite green, so this is the only test that fails for it, because its
/// interleaving never runs the retry-loop body twice in a row. Asserting the
/// invariant directly is not possible: a retry loop with no suspension point
/// livelocks rather than answering wrongly, so a fixture built that way would
/// hang CI instead of reporting. Same FIFO ready-queue dependency as the
/// fixtures above, recorded in the fixture's own comment.
#[test]
fn channel_recv_suspends_only_to_retry_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_recv_suspends_only_to_retry.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_recv_suspends_only_to_retry.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `send`'s half of what the fixture above pins for `recv`: a `send` with room
/// in the channel must enqueue without yielding. Moving `send`'s
/// `yield_now().await` out of the retry loop to before the first `push` leaves
/// both `channel_two_tasks_blocking` and the `recv` fixture green, so this is
/// the only test that fails for it. Unlike the `recv` twin this fixture has no
/// termination guard and so can HANG rather than fail if `push` regresses; its
/// own comment says why that is documented instead of fixed. Same FIFO
/// ready-queue dependency.
#[test]
fn channel_send_suspends_only_to_retry_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_send_suspends_only_to_retry.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_send_suspends_only_to_retry.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Pins `channel`'s `buffer < 1` clamp, which until this fixture existed was
/// executed by no test in the suite: every other channel fixture passes 1, 2
/// or 3, and no `channel(0)` or negative argument appeared anywhere in the
/// repo. Synchronous, so no regression of the clamp can hang. Both the zero
/// and the negative case are asserted because they fail differently without
/// the clamp -- capacity 0 refuses the first send, capacity -4 reaches
/// `[v; cap]` with a negative length -- and the clamp is what keeps a
/// negative modulus away from the ring's `%` arithmetic entirely.
#[test]
fn channel_clamps_buffer_below_one_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_clamps_buffer_below_one.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_clamps_buffer_below_one.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Pins the ENQUEUE modulo in `Channel::push`, `(head + len) % cap`, which
/// until this fixture was executed by no test in a state where it wraps: no
/// other fixture pushes while `head != 0`, so deleting `% self.cap` from that
/// line left all 44 targets green. Only the dequeue modulo in `pop` was
/// pinned. Found by the whole-branch review rather than by a record -- no
/// record claimed the line was covered, and none recorded it as a gap either,
/// which is the worse of the two.
///
/// Capacity 2, two sends, one receive so `head` advances to 1 with one value
/// still live, then a third send that must land at `(1 + 1) % 2 == 0`. The
/// drain asserts the order, `2 3`, not merely the count, so a wrapped write
/// that landed in the wrong slot fails rather than passes. Synchronous, so no
/// regression of the ring arithmetic can turn it into a hang.
#[test]
fn channel_enqueue_wraps_after_dequeue_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_enqueue_wraps_after_dequeue.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_enqueue_wraps_after_dequeue.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Pins that the async `send` returns false on a closed channel -- the one
/// place `send` and `try_send` are specified to differ, and, until this
/// fixture, pinned by neither. No other test calls `send` on a closed
/// channel: `channel_close_refuses_send` uses `try_send`, and
/// `channel_two_tasks_blocking`'s producer closes only after every send has
/// returned. Asserts the open case on the same channel first, so a `false`
/// is attributable to the `close` rather than to a broken `send`.
///
/// Bounded on the shipped code because the `closed` check precedes the
/// `yield_now().await`. It is NOT bounded under every regression: deleting
/// that check makes this fixture hang rather than fail, since `push` refuses
/// every value on a closed channel and `main` is the only task, so the retry
/// loop spins unpreemptably. Its own comment records why no fixture can fix
/// that. What it catches as a bounded diff is `push` losing its `closed`
/// guard, which flips the second line to true.
#[test]
fn channel_send_refuses_when_closed_run() {
    let expected = std::fs::read_to_string(
        repo_root().join("tests/runtime/channel_send_refuses_when_closed.stdout"),
    )
    .expect("expected-output fixture exists")
    .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/channel_send_refuses_when_closed.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn map_keys_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/map_keys.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/map_keys.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_stringify_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/json_stringify.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_stringify.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_stringify_escapes_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_stringify_escapes.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_stringify_escapes.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_parse_numbers_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_parse_numbers.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_parse_numbers.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_parse_strings_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_parse_strings.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_parse_strings.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_parse_values_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_parse_values.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_parse_values.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_round_trip_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_round_trip.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_round_trip.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `json_round_trip.nova` with `NOVA_GC_STRESS=1`, a collection on every
/// allocation. Since 2026-10-03 `json_quote` and `str_concat`, both reached
/// here, allocate their result's GC buffer first and only then read their
/// arguments' bytes into it. Those bytes must survive the collection that
/// allocation can run, and a missed root shows up as wrong text, not a crash.
/// `str_concat_n` and `str_join` work the same way and are covered under
/// stress by `interpolation_nary_under_gc_stress` and
/// `strings_under_gc_stress`. It discriminates only where the collector frees
/// memory: wherever `gc::stack_base` has an implementation (ADR 0024).
#[test]
fn json_round_trip_under_gc_stress() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_round_trip.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_round_trip.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `json_stringify_escapes.nova` with `NOVA_GC_STRESS=1`, for the same reason
/// as `json_round_trip_under_gc_stress`. Its `\"`, `\\`, `\n` and `\t` escapes,
/// and its `\u00XX` ones, are written after `json_quote` allocates.
#[test]
fn json_stringify_escapes_under_gc_stress() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_stringify_escapes.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_stringify_escapes.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `json_parse_strings.nova` with `NOVA_GC_STRESS=1`, for the three short
/// escapes `json_stringify_escapes.nova` does not write: `\r`, `\b` and
/// `\f`, each re-rendered by `json_quote` after it allocates.
#[test]
fn json_parse_strings_under_gc_stress() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_parse_strings.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .env("NOVA_GC_STRESS", "1")
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_parse_strings.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_traits_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/json_traits.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_traits.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_depth_leaf_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_depth_leaf.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_depth_leaf.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_depth_empty_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_depth_empty.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_depth_empty.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_render_deep_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_render_deep.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_render_deep.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn json_object_forged_map_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_object_forged_map.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_object_forged_map.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A cyclic value must fail by the guard's own named panic, not by a stack
/// overflow and not by running until the allocator gives up. Asserting the
/// message is the whole point: the failure this replaces carried none.
#[test]
fn json_stringify_cycle_panics_with_a_named_message() {
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_stringify_cycle.nova"))
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: stringify: nesting too deep or cyclic value"),
        "stderr: {stderr}"
    );
    assert!(
        !stderr.contains("has overflowed its stack") && !stderr.contains("memory allocation of"),
        "expected the guard, not a stack overflow or an allocator abort, stderr: {stderr}"
    );
}

/// The depth guard, pinned by a value that terminates either way, unlike the
/// cyclic fixture above: one level past `MAX_RENDER_DEPTH` (100001) panics
/// with the guard in place, and renders (exit 0) with it deleted. A deleted
/// guard therefore fails THIS test's `.failure()` assertion promptly, rather
/// than hanging the way the cyclic fixture does when the guard is gone.
#[test]
fn json_render_guard_panics_with_a_named_message() {
    let out = nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_render_guard.nova"))
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&out.get_output().stderr).to_string();
    assert!(
        stderr.contains("nova: panic: stringify: nesting too deep or cyclic value"),
        "stderr: {stderr}"
    );
    assert!(
        !stderr.contains("has overflowed its stack") && !stderr.contains("memory allocation of"),
        "expected the guard, not a stack overflow or an allocator abort, stderr: {stderr}"
    );
}

/// The depth guard's lower side: `MAX_RENDER_DEPTH` itself (100000) must
/// still render successfully. Together with
/// `json_render_guard_panics_with_a_named_message` (`MAX_RENDER_DEPTH + 1`,
/// 100001, which panics), the pair brackets the bound exactly from both
/// sides, so a mutation to the constant in either direction breaks one of
/// them. (An earlier version of this test sat at `MAX_RENDER_DEPTH - 1`,
/// 99999, which left the bound itself untested and did not catch a downward
/// mutation to the constant; fixed to 100000 for that reason.)
#[test]
fn json_render_guard_under_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/json_render_guard_under.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/json_render_guard_under.nova"))
        .assert()
        .success()
        .stdout(expected);
}

#[test]
fn hash_diffusion_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/hash_diffusion.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/hash_diffusion.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// The seed is per-process, so the same binary run twice must hash the same
/// string differently. This is the test written for that property; it fails
/// deterministically if the seed is replaced by a constant. Two independent
/// seeds colliding would defeat it, at a probability around 2^-64.
#[test]
fn str_hash_seed_varies_across_processes() {
    // Per-process directory: this branch's constraint that every fixture path
    // be unique per process, for the same reason `build_and_run` above
    // carries a pid (see its doc comment).
    let dir = std::env::temp_dir().join(format!(
        "nova-str-hash-seed-cross-process-{}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("seed.nova");
    std::fs::write(&file, "fn main() { println(\"${(\"alpha\").hash()}\") }\n").expect("write");
    let exe = dir.join(format!("seed{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(&file)
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    let run = || {
        let out = Command::new(&exe).assert().success();
        String::from_utf8_lossy(&out.get_output().stdout)
            .trim()
            .to_string()
    };
    let first = run();
    let second = run();
    assert_ne!(
        first, second,
        "str_hash must differ across processes; both runs printed {first}"
    );
}

/// Phase 1: search candidate keys for a set that collides under THIS
/// process's seed. This searches with `.hash()`, the runtime's real hash
/// builtin, rather than reimplementing the algorithm in Nova and predicting
/// collisions from the seed directly — `std/bytes`/`std/strings` give Nova
/// enough to walk a String's bytes, so a reimplementation is possible, but
/// it would pin a second copy of the algorithm and fail for the wrong
/// reason if the two ever diverged.
///
/// Two passes rather than a bucket-of-lists, because Nova's array
/// construction has a repeat form and a list form and no nested growable
/// structure worth building here. The first pass stops at the 32nd key in
/// some bucket; the second collects that bucket's first 32 indices, which
/// are exactly the keys the first pass counted.
const PHASE1_SRC: &str = r#"const CAP: Int = 64
const WANT: Int = 32
const BUDGET: Int = 4000

fn main() {
    let mut counts = [0; CAP]
    let mut target = -1
    let mut i = 0
    while i < BUDGET {
        let k = "k${i}"
        let b = k.hash() & (CAP - 1)
        counts[b] = counts[b] + 1
        if counts[b] >= WANT { target = b; break }
        i = i + 1
    }
    if target < 0 {
        println("found false")
        return
    }
    let mut picked = [0; WANT]
    let mut out = ""
    let mut n = 0
    let mut j = 0
    while j < BUDGET {
        let k = "k${j}"
        if (k.hash() & (CAP - 1)) == target {
            picked[n] = j
            out = "${out}${j} "
            n = n + 1
            if n == WANT { break }
        }
        j = j + 1
    }
    // Self-check: bucket the emitted set with phase 2's own arithmetic. Under this
    // process's seed every picked key shares `target`, so this is the whole
    // set size; if it is not, the set being handed to phase 2 is not the set
    // phase 1 claims to have found.
    let mut own = [0; CAP]
    let mut m = 0
    while m < n {
        let k = "k${picked[m]}"
        own[k.hash() & (CAP - 1)] = own[k.hash() & (CAP - 1)] + 1
        m = m + 1
    }
    let mut conc = 0
    let mut q = 0
    while q < CAP {
        if own[q] > conc { conc = own[q] }
        q = q + 1
    }
    println("found true")
    println("count ${n}")
    println("concentration ${conc}")
    println("indices ${out}")
}
"#;

/// Phase 2: re-hash phase 1's set in a FRESH process, therefore under a
/// fresh seed. `__INDICES__` is replaced by the comma-separated indices
/// phase 1 printed. Keys are `"k" + index` by construction, so an index
/// transfers the key exactly.
const PHASE2_TEMPLATE: &str = r#"const CAP: Int = 64

fn main() {
    let idx = [__INDICES__]
    let mut counts = [0; CAP]
    let mut i = 0
    while i < idx.len() {
        let k = "k${idx[i]}"
        let b = k.hash() & (CAP - 1)
        counts[b] = counts[b] + 1
        i = i + 1
    }
    let mut largest = 0
    let mut j = 0
    while j < CAP {
        if counts[j] > largest { largest = counts[j] }
        j = j + 1
    }
    println("keys ${idx.len()} largest ${largest}")
}
"#;

/// A key set built to collide under one process's seed must NOT collide in
/// a fresh process. This is precomputation resistance, executing rather
/// than argued: before this test the property rested on measurements taken
/// in a throwaway harness and recorded in prose.
///
/// Phase 1 pins something in its own right: given direct access to the hash,
/// finding a colliding key set is cheap — 32 keys share one bucket after a
/// median of roughly 1300 candidates scanned, well inside the 4000 budget.
/// That is NOT the limit the records disclose, and must not be read as
/// demonstrating it. Their excluded adversary observes timing and adapts,
/// whereas calling `.hash()` needs code running inside the target process,
/// which is a stronger capability; the timing case is not exercised here.
///
/// The thresholds are derived, not chosen to look generous. Phase 1's
/// budget of 4000 is about 2.6 times the observed worst case: over 200
/// random seeds a bucket reached 32 keys after a median of 1319 candidates,
/// 1463 at the 95th percentile and 1508 at the worst, succeeding for every
/// one of those seeds. Phase 2's bound of 10 comes from the binomial right
/// tail for 32 keys in 64 buckets summed over the buckets: a false failure
/// runs at most about 8.3e-11, roughly one run in twelve billion at worst —
/// a Bonferroni bound, since the per-bucket events are not disjoint — against
/// an observed maximum of 5 and a 99th percentile of 4 over 3000 simulated
/// seed pairs. If the seeding were dead the largest bucket would be 32, so
/// the margin before a broken seed could pass is 22 keys — measured, by
/// running both phases in one process.
///
/// Phase 1 also re-hashes the 32 keys it emits and checks they still land in
/// one bucket under its own seed, rather than trusting its own `count 32`
/// report — a filter that emitted 32 arbitrary keys would satisfy that
/// count without the set actually colliding, which would make phase 2's
/// comparison prove nothing.
///
/// What this does NOT reliably cover: the splitmix64 finalizer. Without it,
/// the six bucket-selecting bits depend only on `seed & 63` — 64 possible
/// layouts, not 2^64 — so dropping the finalizer is largely, but not
/// wholly, invisible to this test: enumerating all 4096 residue pairs
/// against these keys, the bound fails about one run in ten (416 of 4096),
/// and about 6.25% of pairs still print `largest bucket 32 of 32`, the same
/// value a dead seed produces — a failure here must not be read as a dead
/// seed without checking the finalizer separately.
/// `tests/runtime/hash_diffusion.nova` fails deterministically when the
/// finalizer is missing.
///
/// This builds and runs Nova binaries, so it joins the population the
/// `0xc0000005` flake draws from. That cost is stated rather than hidden.
#[test]
fn hashdos_precomputed_key_set_does_not_survive_a_new_process() {
    let dir = std::env::temp_dir().join(format!("nova-hashdos-resist-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("temp dir");

    let build_and_capture = |name: &str, src: &str| -> String {
        let file = dir.join(format!("{name}.nova"));
        std::fs::write(&file, src).expect("write nova source");
        let exe = dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
        nova()
            .arg("build")
            .arg(&file)
            .arg("-o")
            .arg(&exe)
            .assert()
            .success();
        let out = Command::new(&exe).assert().success();
        String::from_utf8_lossy(&out.get_output().stdout)
            .replace("\r\n", "\n")
            .trim()
            .to_string()
    };

    // Phase 1, in its own process.
    let found = build_and_capture("phase1", PHASE1_SRC);
    assert!(
        found.contains("found true"),
        "phase 1 must find 32 keys in one bucket within its budget; it printed:\n{found}"
    );
    assert!(
        found.contains("count 32"),
        "phase 1 must report exactly the set size it was asked for; it printed:\n{found}"
    );
    assert!(
        found.contains("concentration 32"),
        "phase 1's self-check must confirm the 32 keys it emitted actually share one \
         bucket under its own seed, not merely that it emitted 32 of them; it printed:\n{found}"
    );
    let indices: Vec<&str> = found
        .lines()
        .find_map(|l| l.strip_prefix("indices "))
        .expect("phase 1 prints an `indices` line")
        .split_whitespace()
        .collect();
    assert_eq!(
        indices.len(),
        32,
        "phase 1's index line must carry the whole set; it printed:\n{found}"
    );

    // Phase 2, in a SEPARATE process, therefore under a different seed.
    // A second real process supplies that second seed while both phases
    // still exercise the runtime's real hash builtin, rather than
    // reimplementing the algorithm in Nova with a chosen seed parameter —
    // that would pin a second copy of the algorithm and fail for the wrong
    // reason if the two ever diverged.
    let src = PHASE2_TEMPLATE.replace("__INDICES__", &indices.join(", "));
    let spread = build_and_capture("phase2", &src);
    assert!(
        spread.starts_with("keys 32 largest "),
        "phase 2 must report the set size and the largest bucket; it printed:\n{spread}"
    );
    let largest: usize = spread
        .rsplit(' ')
        .next()
        .and_then(|n| n.parse().ok())
        .expect("phase 2's last field is the largest bucket count");
    assert!(
        largest <= 10,
        "a set precomputed under another seed must not still collide: largest bucket {largest} \
         of 32 keys, bound 10. A dead seed yields 32. Phase 1 printed:\n{found}\n\
         Phase 2 printed:\n{spread}"
    );
}

/// Phase 1 of the `Int`-key equivalent: search `Int` keys for a set that
/// collides under THIS process's seed. The key IS the index, so nothing has to
/// be reconstructed from it the way the `String` search rebuilds `"k${i}"`.
///
/// Two passes rather than a bucket-of-lists, for the same reason the `String`
/// search gives: Nova's array construction has a repeat form and a list form
/// and no nested growable structure worth building here. The first pass stops
/// at the 32nd key in some bucket; the second collects that bucket's first 32
/// keys, which are exactly the keys the first pass counted.
const INT_PHASE1_SRC: &str = r#"const CAP: Int = 64
const WANT: Int = 32
const BUDGET: Int = 4000

fn main() {
    let mut counts = [0; CAP]
    let mut target = -1
    let mut i = 0
    while i < BUDGET {
        let b = (i).hash() & (CAP - 1)
        counts[b] = counts[b] + 1
        if counts[b] >= WANT { target = b; break }
        i = i + 1
    }
    if target < 0 {
        println("found false")
        return
    }
    let mut picked = [0; WANT]
    let mut out = ""
    let mut n = 0
    let mut j = 0
    while j < BUDGET {
        if ((j).hash() & (CAP - 1)) == target {
            picked[n] = j
            out = "${out}${j} "
            n = n + 1
            if n == WANT { break }
        }
        j = j + 1
    }
    // Self-check: bucket the emitted set with phase 2's own arithmetic. Under
    // this process's seed every picked key shares `target`, so this is the whole
    // set size; if it is not, the set being handed to phase 2 is not the set
    // phase 1 claims to have found.
    let mut own = [0; CAP]
    let mut m = 0
    while m < n {
        let k = picked[m]
        own[k.hash() & (CAP - 1)] = own[k.hash() & (CAP - 1)] + 1
        m = m + 1
    }
    let mut conc = 0
    let mut q = 0
    while q < CAP {
        if own[q] > conc { conc = own[q] }
        q = q + 1
    }
    println("found true")
    println("count ${n}")
    println("concentration ${conc}")
    println("keys ${out}")
}
"#;

/// Phase 2 of the `Int`-key equivalent: re-hash phase 1's set in a FRESH
/// process, therefore under a fresh seed. `__KEYS__` is replaced by the
/// comma-separated keys phase 1 printed.
const INT_PHASE2_TEMPLATE: &str = r#"const CAP: Int = 64

fn main() {
    let ks = [__KEYS__]
    let mut counts = [0; CAP]
    let mut i = 0
    while i < ks.len() {
        let k = ks[i]
        let b = k.hash() & (CAP - 1)
        counts[b] = counts[b] + 1
        i = i + 1
    }
    let mut largest = 0
    let mut j = 0
    while j < CAP {
        if counts[j] > largest { largest = counts[j] }
        j = j + 1
    }
    println("keys ${ks.len()} largest ${largest}")
}
"#;

/// An `Int` key set built to collide under one process's seed must NOT collide
/// in a fresh process. `hashdos_precomputed_key_set_does_not_survive_a_new_process`
/// asserts the same property for `String` keys through `nova_rt_str_hash`'s
/// seed; this one goes through `nova_rt_int_hash_seed`, which is a separate
/// draw feeding `std/core`'s `Int`, `Bool` and `Char` impls, so neither test
/// covers the other's path.
///
/// The bound and its derivation are the `String` test's: `Binomial(32, 1/64)`
/// for one bucket, summed over the 64 buckets, is `8.2686863021e-11` to eleven
/// significant figures — about one run in twelve billion. That sum is an UPPER
/// BOUND on the probability of a largest bucket above 10, not that probability:
/// the 64 per-bucket events are not disjoint, so summing them is Bonferroni, and
/// what the computation gives exactly is the bound rather than the quantity it
/// bounds. If the seeding were dead the largest bucket would be 32, so the
/// margin before a broken seed could pass is 22 keys.
///
/// That figure was wrong here until it was recomputed, and it was NOT a typo. It
/// read `8.2686863018e-11`, which is what `1 - (1-P)^64` rounds to at eleven
/// figures, where `P` is the single-bucket tail — the failure probability under
/// an INDEPENDENCE assumption, a different model from the sum this label
/// describes. To eleven figures, from an exact rational rendered with `Decimal`:
/// `P` is `1.2919822347e-12`, the independence form is `8.2686863018e-11`, and
/// the sum `64 * P` is `8.2686863021e-11`. Eleven is the precision the argument
/// needs and no more, because that is where the two models part — at ten
/// figures they agree.
///
/// So an exact figure carried the wrong derivation's name, which is also why
/// every consistency check passed rather than why one was skipped: `1/(64*P)` is
/// 12,093,819,543.57 and `1/(1-(1-P)^64)` is 12,093,819,544.07, and both round
/// to the 12,093,819,544 that shipped beside it. The reciprocal agreed because
/// it came from the same computation, so cross-checking the two figures could
/// never have caught this. What catches this class is recomputing the quantity
/// the LABEL names. The reciprocal is in words now for that reason: a second
/// exact figure derived from the first adds no check, only another thing to keep
/// in step.
///
/// An earlier version of this paragraph gave the cause as "each half of one
/// derivation was checked against the other rather than against a
/// recomputation". That has the mechanism backwards — both halves were correct,
/// for the same unlabelled model.
///
/// And the same defect had a THIRD instance, in this paragraph, until it was
/// recomputed. It displayed the three quantities at twenty-one figures under the
/// heading "Computed exactly with `fractions.Fraction`", but those digit strings
/// are what printing the exact values through a binary64 produces: they diverge
/// from the true expansions at the sixteenth and seventeenth figures. A block
/// labelled exact carried digits no exact computation yields. All three
/// instances have one shape — publishing more precision than the argument uses,
/// so that a figure and its label can drift apart unnoticed.
///
/// The search budget is derived rather than chosen to look generous, and it was
/// simulated for `Int` keys specifically rather than carried over. Over 400
/// seed pairs modelling `mix64(k ^ seed)`, a bucket reached 32 keys after a
/// median of 1320 candidates, 1468 at the 95th percentile and 1615 at the
/// worst, succeeding for every one of those seeds — so 4000 is about 2.5 times
/// the observed worst case. Phase 2's largest bucket over the same 400 pairs ran
/// 1 to 5, with a 99th percentile of 4, against the bound of 10.
///
/// Phase 1 also re-hashes the 32 keys it emits and checks they still land in one
/// bucket under its own seed, rather than trusting its own `count 32` report — a
/// filter that emitted 32 arbitrary keys would satisfy that count without the
/// set actually colliding, which would make phase 2's comparison prove nothing.
///
/// What this pins that the golden fixture cannot: `tests/runtime/hash.nova` runs
/// in one process and so sees one seed, and one seed is indistinguishable from a
/// seed that never varies. So no assertion in that fixture — neither the
/// seed-invariant lines nor the bounds — can detect a dead or constant seed;
/// only a second process can, which is what this test supplies. Measured, not
/// argued: under a runtime patched to return a fixed seed, this test failed at
/// `largest bucket 32 of 32` while the golden fixture passed unchanged.
/// It is also where the PRE-XOR shape earns its keep. Post-XOR
/// (`mix64(x) ^ seed`) leaves the low bits as
/// `(mix64(x) & mask) XOR (seed & mask)`, which permutes buckets without
/// separating any colliding pair, so a set found by phase 1 stays wholly
/// collided in phase 2 and the bound fails.
///
/// Rust's `format!` cannot build the phase-2 source: Nova's `${i}` interpolation
/// makes `format!` read `{i}` as a named capture and fail E0425, so this uses a
/// raw-string template and `str::replace`, as the `String` test does. The Nova
/// source is written from Rust rather than a shell heredoc, which has silently
/// eaten a backslash on this project.
///
/// This builds and runs Nova binaries, so it joins the population the
/// `0xc0000005` flake draws from. That cost is stated rather than hidden.
#[test]
fn hashdos_precomputed_int_key_set_does_not_survive_a_new_process() {
    let dir = std::env::temp_dir().join(format!("nova-hashdos-int-resist-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("temp dir");

    let build_and_capture = |name: &str, src: &str| -> String {
        let file = dir.join(format!("{name}.nova"));
        std::fs::write(&file, src).expect("write nova source");
        let exe = dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
        nova()
            .arg("build")
            .arg(&file)
            .arg("-o")
            .arg(&exe)
            .assert()
            .success();
        let out = Command::new(&exe).assert().success();
        String::from_utf8_lossy(&out.get_output().stdout)
            .replace("\r\n", "\n")
            .trim()
            .to_string()
    };

    // Phase 1, in its own process.
    let found = build_and_capture("int_phase1", INT_PHASE1_SRC);
    assert!(
        found.contains("found true"),
        "phase 1 must find 32 Int keys in one bucket within its budget; it printed:\n{found}"
    );
    assert!(
        found.contains("count 32"),
        "phase 1 must report exactly the set size it was asked for; it printed:\n{found}"
    );
    assert!(
        found.contains("concentration 32"),
        "phase 1's self-check must confirm the 32 keys it emitted actually share one \
         bucket under its own seed, not merely that it emitted 32 of them; it printed:\n{found}"
    );
    let keys: Vec<&str> = found
        .lines()
        .find_map(|l| l.strip_prefix("keys "))
        .expect("phase 1 prints a `keys` line")
        .split_whitespace()
        .collect();
    assert_eq!(
        keys.len(),
        32,
        "phase 1's key line must carry the whole set; it printed:\n{found}"
    );

    // Phase 2, in a SEPARATE process, therefore under a different seed. A
    // second real process supplies that second seed while both phases still
    // exercise `std/core`'s real `Hash for Int`, rather than reimplementing
    // `mix64` in Nova with a chosen seed parameter — that would pin a second
    // copy of the mixer and fail for the wrong reason if the two ever diverged.
    let src = INT_PHASE2_TEMPLATE.replace("__KEYS__", &keys.join(", "));
    let spread = build_and_capture("int_phase2", &src);
    assert!(
        spread.starts_with("keys 32 largest "),
        "phase 2 must report the set size and the largest bucket; it printed:\n{spread}"
    );
    let largest: usize = spread
        .rsplit(' ')
        .next()
        .and_then(|n| n.parse().ok())
        .expect("phase 2's last field is the largest bucket count");
    assert!(
        largest <= 10,
        "an Int key set precomputed under another seed must not still collide: largest \
         bucket {largest} of 32 keys, bound 10. A dead seed yields 32. Phase 1 printed:\n\
         {found}\nPhase 2 printed:\n{spread}"
    );
}

/// The offset table `http_parse_request` returns, pinned field by field from
/// the Nova side. See `tests/runtime/http_offsets.nova`'s own header for why
/// it is pinned from both sides and what mutation it exists to kill.
#[test]
fn http_offsets_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/http_offsets.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_offsets.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// A head split across two `parse_offsets` calls: partial on the first,
/// complete on the second. Also checks that two calls on the identical
/// complete buffer agree, which pins statelessness but is NOT a check that a
/// split parse matches the unsplit case -- see
/// `tests/runtime/http_partial.nova`'s own header for why design spec
/// section 8 now records that property as unfalsifiable under this parser's
/// design, and for the parser bug the split/complete check here is built to
/// catch.
#[test]
fn http_partial_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/http_partial.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_partial.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Two views of rejected or undecodable input: `parse_offsets`'s raw
/// negative status (asserting it is negative and the array has length 1),
/// and `parse_request_head`'s mapped `HttpErrorKind` for the subset of
/// kinds that view can actually reach. See
/// `tests/runtime/http_malformed.nova`'s own header for exactly which kinds
/// that subset is -- this fixture is what holds the Rust-side and Nova-side
/// numberings together for those, not for every kind either side defines.
#[test]
fn http_malformed_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/http_malformed.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_malformed.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `max_head_bytes` and `max_header_count`, each at its boundary and one past
/// it: the runtime's two hard walls (head bytes, header count), and a
/// caller's own tighter `Limits`. Does NOT cover `max_body_bytes` -- this
/// fixture calls `parse_offsets` and `parse_request_head`, and neither reads
/// a body; that limit's boundary and one-past-it cases live in
/// `http_keepalive_run` instead. See `tests/runtime/http_limits.nova`'s own
/// header for why the two head-limit enforcement points each need their own
/// coverage.
#[test]
fn http_limits_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/http_limits.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_limits.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Parses a request, builds a `Response`, and serialises it: the round trip
/// this module's request half and response half must agree on. Also checks
/// that `to_bytes` drops a header carrying an embedded CRLF rather than
/// letting it split the response (FIX 5 of the whole-branch review). See
/// `tests/runtime/http_serialise.nova`'s own header for why the golden checks
/// the wire's parts rather than one `.eq()` over the whole buffer.
#[test]
fn http_serialise_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/http_serialise.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_serialise.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// Keep-alive over one accepted connection: five requests, all parsed and
/// answered without a second `accept`. Both ends are Nova, in two tasks of
/// one process, the same shape `net_listener_accept_run` uses -- see
/// `tests/runtime/http_keepalive.nova`'s own header for why that means no
/// port file. Beyond the original two-request round trip, this is also
/// where `max_body_bytes` gets its boundary and one-past-it coverage (design
/// spec section 11 criterion 4) and where `read_request`'s body-read loop,
/// a real `Content-Length`, and an invalid `Content-Length` value are
/// exercised -- every other `std/http` fixture only ever declares
/// `Content-Length: 0`. That fixture's client awaits each reply before
/// sending the next request, so it never pipelines; see `read_request`'s doc
/// comment in `std/http/lib.nova` for the pipelined-request case this does
/// not cover.
#[test]
fn http_keepalive_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/http_keepalive.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_keepalive.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `std/http`'s `Server::dispatch` and `Response::json`, socket-free: exact
/// GET routes, a handler that reads its request, 404 for an unknown path and
/// for a non-GET method, and the JSON response's headers and bytes. Design:
/// docs/superpowers/specs/2026-10-04-examples-03-http-server-design.md §7.2.
#[test]
fn http_server_dispatch_run() {
    let expected =
        std::fs::read_to_string(repo_root().join("tests/runtime/http_server_dispatch.stdout"))
            .expect("expected-output fixture exists")
            .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/http_server_dispatch.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `std/process`'s `args()` under `nova run FILE -- ARGS`: index 0 is FILE as
/// written, and an argument with spaces and an empty one each arrive whole.
/// Run from the repository root so FILE is a fixed relative path. Design:
/// docs/superpowers/specs/2026-10-05-examples-04-todo-cli-design.md §7.3.
#[test]
fn process_args_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/process_args.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .current_dir(repo_root())
        .arg("run")
        .arg("tests/runtime/process_args.nova")
        .arg("--")
        .args(["one", "two words", ""])
        .assert()
        .success()
        .stdout(expected);
}

/// Without `--`, `nova run` behaves as it always has, and `args()` is just
/// FILE.
#[test]
fn process_args_without_a_separator_is_just_the_file() {
    nova()
        .current_dir(repo_root())
        .arg("run")
        .arg("tests/runtime/process_args.nova")
        .assert()
        .success()
        .stdout("count: 1\n[tests/runtime/process_args.nova]\n");
}

/// `exit(3)` under `nova run`: the `nova` process ends with status 3, and the
/// partial line written before it was flushed.
#[test]
fn process_exit_run() {
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/process_exit.nova"))
        .assert()
        .code(3)
        .stdout("partial");
}

/// `exit(3)` in a built executable, where Rust's own `main` never ran: the
/// status is 3 and the partial line is still flushed.
#[test]
fn process_exit_build_standalone() {
    let dir = std::env::temp_dir().join(format!("nova-build-tests-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("temp dir");
    let exe = dir.join(format!("process_exit{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(repo_root().join("tests/runtime/process_exit.nova"))
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    Command::new(&exe).assert().code(3).stdout("partial");
    let _ = std::fs::remove_file(&exe);
}

/// The benchmark's two halves still work together: the Nova server starts,
/// prints its port, and `nova-bench-http` drives keep-alive requests against
/// it with no errors.
///
/// **This asserts no throughput number**, so it cannot flake on timing. One
/// connection for one second is enough to prove the halves connect; the real
/// measurement is taken by hand, per `docs/benchmarks/README.md`.
///
/// It is a normal test rather than `#[ignore]`d on purpose: CI's Test job has
/// an advisory step that runs exactly the ignored tests, so a load test placed
/// there would run on every push inside a step whose failures are tolerated and
/// therefore unread.
///
/// Uses `nova run` rather than a built binary because this checks correctness,
/// not throughput -- JIT warmup is irrelevant here, and a separate build step
/// would only add moving parts. Task 3's procedure builds a native binary
/// instead, and `docs/benchmarks/README.md` says why.
///
/// **Also runs the generator in `--self-test` mode.** Nothing reached
/// `spawn_self_test_server` before this invocation was added:
/// `nova-bench-http`'s own `self_test_needs_no_addr_and_plain_mode_does`
/// parses the flag into a bool and stops there, and this test ran target mode
/// twice. Meanwhile `docs/benchmarks/README.md` calls that calibration
/// mandatory rather than advisory, and every ratio recorded in
/// `docs/benchmarks/` is computed against a self-test ceiling -- so the mode
/// could have rotted with a green suite. What this invocation pins is that
/// the mode runs end to end: its in-process fixed-response server starts,
/// answers, and the run completes with no errors. Like the target run it
/// asserts no throughput number. Confirmed by mutation rather than assumed --
/// making the self-test server accept a connection and then drop it without
/// answering fails this test on the `--self-test failed` assertion below.
/// `--self-test` needs no external server, which is the entire point of the
/// mode, so this adds no moving parts.
///
/// **Also runs the generator once more against a port nothing is listening
/// on, and asserts that run fails.** Measured directly during this
/// increment's Task 2 rather than reasoned: a `run_load` mutated to
/// fabricate a plausible `Report` without opening
/// any socket satisfies every assertion above it, since those only read the
/// generator's own self-reported `RESULT` line. This negative control is what
/// turns that mutation into a failure -- a generator actually driving
/// connections must see every one of them refused against a dead port, and
/// one that does not touch the network cannot tell a dead port from a live
/// server.
#[test]
fn bench_http_server_and_generator_agree() {
    use std::io::{BufRead, BufReader};
    use std::process::Stdio;

    // `assert_cmd::cargo::cargo_bin("nova-bench-http")` resolves a binary
    // belonging to a different crate, which is what makes the failure mode
    // below worth spelling out. If `nova-bench-http` has never been built,
    // `cargo_bin` panics on its own rather than handing back a bad path --
    // checked against the installed assert_cmd (2.2.1) source rather than
    // assumed: `legacy_cargo_bin` looks in the shared `target/debug`
    // directory and returns `None` when its own `.exists()` check fails (and
    // earlier, if it cannot resolve a target directory at all), so
    // `cargo_bin` never returns a path that isn't there. That panic
    // misdirects here, though. It reports `CARGO_BIN_EXE_nova-bench-http` as
    // unset and then lists the binary names it does have -- just "nova" --
    // because `missing_cargo_bin` takes that branch whenever any
    // `CARGO_BIN_EXE_` variable is set, which one always is for this
    // integration test. So it points at a variable when the real cause is
    // that `cargo test -p nova-cli` does not build other workspace members'
    // binaries the way `cargo test --workspace` does, and the fix is
    // `cargo build --locked --workspace` first.
    let generator = assert_cmd::cargo::cargo_bin("nova-bench-http");

    let mut server = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova"))
        .arg("run")
        .arg(repo_root().join("docs/benchmarks/server.nova"))
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn the benchmark server");

    // The port line is the first thing the server prints, so this read blocks
    // only until it arrives -- and if the program fails to compile, the stream
    // closes and `next()` yields `None`, which fails with a clear message
    // rather than hanging.
    let stdout = server.stdout.take().expect("stdout was piped");
    let first = BufReader::new(stdout)
        .lines()
        .next()
        .and_then(|l| l.ok())
        .unwrap_or_default();
    let port = first
        .rsplit(':')
        .next()
        .and_then(|p| p.trim().parse::<u16>().ok());

    let port = match port {
        Some(p) => p,
        None => {
            let _ = server.kill();
            panic!("server did not print a parseable port line; got {first:?}");
        }
    };

    let out = std::process::Command::new(generator)
        .arg("--addr")
        .arg(format!("127.0.0.1:{port}"))
        .args(["--connections", "1", "--duration", "1", "--warmup", "0"])
        .output()
        .expect("run nova-bench-http");

    let _ = server.kill();
    let _ = server.wait();

    let report = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        out.status.success(),
        "generator failed: {}\nstderr: {}",
        report,
        String::from_utf8_lossy(&out.stderr)
    );
    let result = report
        .lines()
        .find(|l| l.starts_with("RESULT "))
        .unwrap_or_else(|| panic!("no RESULT line in generator output: {report:?}"));
    assert!(
        result.contains(" errors=0 "),
        "generator reported errors: {result}"
    );
    let requests: u64 = result
        .split_whitespace()
        .find_map(|f| f.strip_prefix("requests="))
        .and_then(|v| v.parse().ok())
        .unwrap_or(0);
    assert!(requests >= 1, "no request completed: {result}");

    // `--self-test` -- see this test's own doc comment for why it is here.
    // No `--addr`: the mode binds its own in-process fixed-response server.
    // The assertions are the target run's, minus any throughput number.
    let selftest = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova-bench-http"))
        .arg("--self-test")
        .args(["--connections", "1", "--duration", "1", "--warmup", "0"])
        .output()
        .expect("run nova-bench-http --self-test");
    let selftest_report = String::from_utf8_lossy(&selftest.stdout).to_string();
    assert!(
        selftest.status.success(),
        "--self-test failed: {}\nstderr: {}",
        selftest_report,
        String::from_utf8_lossy(&selftest.stderr)
    );
    let selftest_result = selftest_report
        .lines()
        .find(|l| l.starts_with("RESULT "))
        .unwrap_or_else(|| {
            panic!("no RESULT line in --self-test output: {selftest_report:?}");
        });
    assert!(
        selftest_result.contains(" errors=0 "),
        "--self-test reported errors: {selftest_result}"
    );
    let selftest_requests: u64 = selftest_result
        .split_whitespace()
        .find_map(|f| f.strip_prefix("requests="))
        .and_then(|v| v.parse().ok())
        .unwrap_or(0);
    assert!(
        selftest_requests >= 1,
        "--self-test completed no request: {selftest_result}"
    );

    // Negative control -- see this test's own doc comment for why it exists.
    // A fresh listener is bound and dropped immediately for the sole purpose
    // of getting a port guaranteed to be refusing connections: dropping
    // closes it right away, and no lingering TIME_WAIT applies to a socket
    // that never accepted one. This has a narrow TOCTOU window -- another
    // bind anywhere on the system, including the other ephemeral
    // `TcpListener::bind("127.0.0.1:0")` sites elsewhere in this file, could
    // claim the freed port before `nova-bench-http` connects to it. Holding
    // the listener open instead would close that window but turn the target
    // into a STALLED peer rather than a dead one: the connect and the request
    // write would both succeed, and the generator would sit in `read` until
    // its ten-second READ timeout fired, costing this test that wait instead
    // of a fast failure -- worse on balance than the window it would close.
    // (Not the write timeout, and specifically because of the peer shape
    // this alternative would have: the worker writes one request and then
    // waits for its response, so against a peer that accepts and never
    // answers, exactly one 36-byte request is ever written. The connect and
    // that single write both succeed, and the wait lands on the READ
    // timeout. A peer that *answers without reading* is the different shape
    // that does reach the write timeout -- it keeps the worker writing until
    // the peer's own receive buffer fills -- and `nova-bench-http`'s comment
    // at `set_write_timeout` records that case.)
    let dead_port = {
        let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind an ephemeral port");
        l.local_addr().expect("read the bound port").port()
    };
    let dead = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova-bench-http"))
        .arg("--addr")
        .arg(format!("127.0.0.1:{dead_port}"))
        .args(["--connections", "1", "--duration", "1", "--warmup", "0"])
        .output()
        .expect("run nova-bench-http against a dead port");
    assert!(
        !dead.status.success(),
        "nova-bench-http reported success against a port nothing is listening on \
         (stdout: {}, stderr: {})",
        String::from_utf8_lossy(&dead.stdout),
        String::from_utf8_lossy(&dead.stderr)
    );
}

/// `std/crypto`'s digests and HMAC against known vectors, cross-checked
/// against Python's `hashlib`/`hmac`. Also pins the operation-selector
/// constants `std/crypto/lib.nova` duplicates from
/// `crates/nova-runtime/src/crypto.rs` -- `OP_SHA256`, `OP_SHA512`,
/// `OP_HMAC_SHA256` and `OP_HMAC_SHA256_VERIFY` -- each of which owns golden
/// lines in the fixture: the `sha256` lines, the `sha512` lines, the `hmac`
/// line and the four `verify` lines respectively. What a swap moves is not
/// always a digest: `OP_HMAC_SHA256` traded with `OP_HMAC_SHA256_VERIFY`
/// empties the `hmac` line and turns every `verify` answer `true`, measured
/// from each side of the boundary in turn. See
/// `tests/runtime/crypto_hashes.nova`'s own header for that mapping and how it
/// was derived, for the hex helper's route (`String::slice`, not `char_at`)
/// and for which claim this fixture is and is not making about the published
/// test vectors.
#[test]
fn crypto_hashes_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/crypto_hashes.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/crypto_hashes.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `std/crypto`'s entropy surface: no vector is asserted, only the
/// properties that hold whatever the draw is -- a length, an error kind at
/// each rejected boundary, the accepted length at the size cap itself, two
/// draws differing, and 200 bounded draws all landing in range. The `at cap
/// 65536` line is what stops `crates/nova-runtime/src/crypto.rs`'s `want >
/// MAX_RANDOM_BYTES` drifting to `>=`; the over-cap line alone does not. See
/// `tests/runtime/crypto_random.nova`'s own header for why the
/// differing-draws check is safe despite being probabilistic.
#[test]
fn crypto_random_run() {
    let expected = std::fs::read_to_string(repo_root().join("tests/runtime/crypto_random.stdout"))
        .expect("expected-output fixture exists")
        .replace("\r\n", "\n");
    nova()
        .arg("run")
        .arg(repo_root().join("tests/runtime/crypto_random.nova"))
        .assert()
        .success()
        .stdout(expected);
}

/// `examples/05-json-api` driven over a real socket: its three routes and the
/// error paths the assertions below name, each by status code and whole
/// response body.
///
/// **The exchanges below are a roster and not a closed world.** Arms of the
/// example's `handle` that nothing here drives include a `POST` to an unknown
/// path, a `POST` whose body is not UTF-8, is not JSON or is not an object,
/// and any method other than `GET` or `POST`. Which arms are undriven changes
/// as the example does, so the durable check is the one the example's own
/// comments hand over rather than this list: delete a response line from
/// `examples/05-json-api/src/main.nova` and re-run this test.
///
/// **No duration and no rate is asserted here.** It is a correctness test
/// that happens to need a server; the throughput question belongs to
/// `nova-bench-http` and `docs/benchmarks/`. Asserting no duration is not the
/// same as having no timing dependency, though: `exchange` installs a
/// ten-second read and write timeout below, and exceeding it turns that
/// exchange into a `(0, "read failed: ...")` outcome which then fails its
/// assertion. The bound is there to break a hang rather than to measure
/// anything -- a stalled peer must fail this test rather than park the suite
/// -- so a red here reads as a stall rather than as a slow machine.
/// `nova-bench-http`'s `IO_TIMEOUT` takes the same ten seconds for the same
/// reason and argues its margin from a measured round trip; no round trip has
/// been timed against this example, so the margin here is unmeasured rather
/// than proven.
///
/// **Bodies are compared whole; heads are not.** The example interpolates
/// its response bodies rather than building `Map`-backed `JsonValue`s
/// exactly so that key order is fixed by the source text, because `Map`
/// iteration is seeded per process. The response HEADERS are still
/// `Map`-ordered -- a hand run emitted `content-type` ahead of the
/// `content-length` that `json_response` inserts first -- so this test pulls
/// `Content-Length` out of the head case-insensitively and never compares
/// the head itself.
///
/// One connection per exchange, each response framed by `Content-Length`
/// rather than by end-of-stream: the example keeps a connection alive until
/// its own read fails, so a reader waiting for EOF would be waiting for a
/// close that only its own close can cause.
///
/// `GET /users/1` runs over a connection later than the `POST` that created
/// the user, so a different `serve` task answers it. That is what makes it a
/// check on the shared store rather than on one task's local state: `Store`
/// is passed by reference under ADR 0005 and `Store::create` writes through
/// a `mut self` receiver, with no lock, because ADR 0009 makes
/// single-threading a correctness requirement.
///
/// **`GET /users` runs twice, and the second run is the one that exercises
/// the list.** On an empty store `users_json`'s `while` never enters, so its
/// `Some(u)` arm never runs and the `[]` comes from joining an empty array.
/// The second `GET /users` goes last, after both `POST`s, and pins the
/// two-element array: the separator between the elements and the ascending
/// walk over ids. Confirmed by mutation rather than assumed. Since
/// 2026-10-02, `users_json` sizing its array one slot too large, or writing
/// one user short, fails this test, and the `listed` body is the only one
/// either mutant changes. Before that, deleting the old
/// `if !first { out = "${out}," }` failed the `listed` assertion. Nothing
/// else here can catch these, because every other body asserted is a single
/// object or an empty array, and a separator never appears in one.
///
/// **`GET /nope/1` is what pins the resource segment, and nothing else here
/// can.** `GET /nope` is one segment, so it misses the router's
/// `parts.len() == 3` test and never reaches the `parts[1] == "users"` test
/// beside it; an assertion set holding only that one is satisfied by a router
/// that checks the resource segment and by one that only counts segments.
/// The second is what this example served until the check was added: every
/// two-segment path whose tail parsed as an integer answered as a user fetch,
/// so `/foo/1` and `//1` both returned user 1. Confirmed by mutation rather
/// than assumed -- dropping `&& parts[1] == "users"` from the example turns
/// this exchange into `(200, {"id":1,...})` and fails this assertion alone.
/// It runs after the first `POST`, which is what makes the mutant's answer a
/// user rather than a 404 from an empty store.
///
/// Every I/O failure becomes a `(0, "...")` outcome instead of a panic, and
/// every outcome is collected before the child is killed, so a failing
/// assertion cannot leave a server process behind.
#[test]
fn json_api_example_serves_its_routes() {
    use std::io::{BufRead, BufReader, Read, Write};
    use std::process::Stdio;

    let mut server = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova"))
        .arg("run")
        .arg(repo_root().join("examples/05-json-api/src/main.nova"))
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn the json-api example");

    // The port line is the first thing the example prints, so this read
    // blocks only until it arrives -- and if the program fails to compile,
    // the stream closes and `next()` yields `None`, which fails with a clear
    // message rather than hanging.
    let stdout = server.stdout.take().expect("stdout was piped");
    let first = BufReader::new(stdout)
        .lines()
        .next()
        .and_then(|l| l.ok())
        .unwrap_or_default();
    let port = match first
        .rsplit(':')
        .next()
        .and_then(|p| p.trim().parse::<u16>().ok())
    {
        Some(p) => p,
        None => {
            let _ = server.kill();
            let _ = server.wait();
            panic!("the example did not print a parseable port line; got {first:?}");
        }
    };

    // `Content-Length` out of a complete head, case-insensitively. `None`
    // for an absent or malformed value rather than `0`, which would be
    // indistinguishable from a legitimately empty body.
    fn content_length(head: &str) -> Option<usize> {
        for line in head.split("\r\n") {
            // A line with no `:` is the status line or the blank terminator,
            // not a header -- skip it rather than stopping the scan.
            let Some((name, value)) = line.split_once(':') else {
                continue;
            };
            if name.trim().eq_ignore_ascii_case("content-length") {
                return value.trim().parse().ok();
            }
        }
        None
    }

    let exchange = |method: &str, path: &str, body: &str| -> (u16, String) {
        // Shaped like the `curl` invocations this example was driven with by
        // hand: no `content-length` at all on a bodyless request.
        let mut wire = if body.is_empty() {
            format!("{method} {path} HTTP/1.1\r\nhost: nova-json-api\r\n\r\n")
        } else {
            format!(
                "{method} {path} HTTP/1.1\r\nhost: nova-json-api\r\n\
                 content-type: application/json\r\ncontent-length: {}\r\n\r\n",
                body.len()
            )
        };
        wire.push_str(body);

        let mut sock = match std::net::TcpStream::connect(("127.0.0.1", port)) {
            Ok(s) => s,
            Err(e) => return (0, format!("connect failed: {e}")),
        };
        // A stalled peer must fail this test rather than hang the suite.
        let limit = Some(std::time::Duration::from_secs(10));
        if let Err(e) = sock.set_read_timeout(limit) {
            return (0, format!("set_read_timeout failed: {e}"));
        }
        if let Err(e) = sock.set_write_timeout(limit) {
            return (0, format!("set_write_timeout failed: {e}"));
        }
        if let Err(e) = sock.write_all(wire.as_bytes()) {
            return (0, format!("write failed: {e}"));
        }

        let mut buf: Vec<u8> = Vec::new();
        let mut chunk = [0u8; 4096];
        let total = loop {
            let framed = buf
                .windows(4)
                .position(|w| w == b"\r\n\r\n")
                .map(|i| i + 4)
                .and_then(|end| {
                    // The head is ASCII; a body need not be, which is why
                    // only the head is decoded here.
                    let head = std::str::from_utf8(&buf[..end]).ok()?;
                    Some(end + content_length(head)?)
                });
            match framed {
                Some(n) if buf.len() >= n => break n,
                _ => {}
            }
            match sock.read(&mut chunk) {
                Ok(0) => {
                    return (
                        0,
                        format!(
                            "peer closed mid-response after {} bytes: {:?}",
                            buf.len(),
                            String::from_utf8_lossy(&buf)
                        ),
                    );
                }
                Ok(n) => buf.extend_from_slice(&chunk[..n]),
                Err(e) => return (0, format!("read failed: {e}")),
            }
        };

        let head_end = buf
            .windows(4)
            .position(|w| w == b"\r\n\r\n")
            .map(|i| i + 4)
            .unwrap_or(0);
        let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
        let status = head
            .lines()
            .next()
            .and_then(|l| l.split_whitespace().nth(1))
            .and_then(|s| s.parse::<u16>().ok())
            .unwrap_or(0);
        (
            status,
            String::from_utf8_lossy(&buf[head_end..total]).to_string(),
        )
    };

    let empty = exchange("GET", "/users", "");
    let created = exchange(
        "POST",
        "/users",
        r#"{"name":"ada","email":"a@example.com"}"#,
    );
    let fetched = exchange("GET", "/users/1", "");
    let bad_id = exchange("GET", "/users/zz", "");
    let no_such = exchange("GET", "/users/99", "");
    let unknown = exchange("GET", "/nope", "");
    // Two segments, wrong resource. This runs after the `POST` above, so
    // user 1 exists and a router that only counted segments would answer it
    // with that user rather than a 404 -- see the doc comment.
    let wrong_prefix = exchange("GET", "/nope/1", "");
    // Beyond the routes above, and the reason the example reaches for
    // `stringify` instead of interpolating a name directly: a name carrying
    // a quote and a backslash must come back escaped rather than breaking
    // the document.
    let escaped = exchange(
        "POST",
        "/users",
        r#"{"name":"a\"b\\c","email":"q@example.com"}"#,
    );
    // Last, so every exchange above keeps the store state it was written
    // against. This is the only one that drives `users_json`'s loop body:
    // the `empty` exchange above skips it entirely.
    let listed = exchange("GET", "/users", "");

    let _ = server.kill();
    let _ = server.wait();

    fn seen(r: &(u16, String)) -> (u16, &str) {
        (r.0, r.1.as_str())
    }

    assert_eq!(seen(&empty), (200, "[]"), "GET /users on an empty store");
    assert_eq!(
        seen(&created),
        (201, r#"{"id":1,"name":"ada","email":"a@example.com"}"#),
        "POST /users"
    );
    assert_eq!(
        seen(&fetched),
        (200, r#"{"id":1,"name":"ada","email":"a@example.com"}"#),
        "GET /users/1 over a later connection"
    );
    assert_eq!(
        seen(&bad_id),
        (400, r#"{"error":"id must be an integer"}"#),
        "GET /users/zz"
    );
    assert_eq!(
        seen(&no_such),
        (404, r#"{"error":"no such user"}"#),
        "GET /users/99"
    );
    assert_eq!(
        seen(&unknown),
        (404, r#"{"error":"not found"}"#),
        "GET /nope"
    );
    assert_eq!(
        seen(&wrong_prefix),
        (404, r#"{"error":"not found"}"#),
        "GET /nope/1: two segments, wrong resource -- not GET /users/:id"
    );
    assert_eq!(
        seen(&escaped),
        (201, r#"{"id":2,"name":"a\"b\\c","email":"q@example.com"}"#),
        "POST /users with a quote and a backslash in the name"
    );
    assert_eq!(
        seen(&listed),
        (
            200,
            r#"[{"id":1,"name":"ada","email":"a@example.com"},{"id":2,"name":"a\"b\\c","email":"q@example.com"}]"#
        ),
        "GET /users with two users: the separator and the ascending id walk"
    );
}

// ---------------------------------------------------------------------------
// `examples/03-http-server`: the Phase 2 gate in `nova-spec/60-EXAMPLES.md` §3.
// Design: docs/superpowers/specs/2026-10-04-examples-03-http-server-design.md
// §7.3, and the plan's Review Focus.

/// The example binds the fixed port 3000 the gate names, so every test that
/// runs it holds this lock: libtest runs tests on parallel threads, and two
/// servers cannot both have the port.
static PORT_3000: std::sync::Mutex<()> = std::sync::Mutex::new(());

const HTTP03_ADDR: &str = "127.0.0.1:3000";

fn lock_port_3000() -> std::sync::MutexGuard<'static, ()> {
    PORT_3000
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

fn http03_addr() -> std::net::SocketAddr {
    HTTP03_ADDR.parse().expect("a valid socket address")
}

/// Fails the calling test unless nothing is listening on port 3000.
fn assert_port_3000_free() {
    use std::time::Duration;
    if let Ok(s) = std::net::TcpStream::connect_timeout(&http03_addr(), Duration::from_millis(500))
    {
        drop(s);
        panic!("something is already listening on {HTTP03_ADDR}; free port 3000 and re-run");
    }
    if let Err(e) = std::net::TcpListener::bind("0.0.0.0:3000") {
        panic!("cannot bind 0.0.0.0:3000 ({e}); free port 3000 and re-run");
    }
}

/// An exit status in a form that names both a signal death (Unix) and a
/// Windows status code in hex.
fn describe_status(s: &std::process::ExitStatus) -> String {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(sig) = s.signal() {
            return format!("killed by signal {sig}");
        }
    }
    match s.code() {
        Some(c) => format!("exit code {c} ({:#x})", c as u32),
        None => format!("{s:?}"),
    }
}

/// SIGTERM to the child. Hand-declared, so no dev-dependency and no
/// `Cargo.lock` change. Measured on all three CI runners by the 2026-10-04
/// spike (draft PR #95).
#[cfg(unix)]
fn send_termination_request(pid: u32) -> Result<(), String> {
    extern "C" {
        fn kill(pid: i32, sig: i32) -> i32;
    }
    let pid = i32::try_from(pid).map_err(|e| format!("pid {pid}: {e}"))?;
    if pid <= 0 {
        return Err(format!("refusing to signal pid {pid}"));
    }
    // SAFETY: `kill` takes two plain integers and touches no memory.
    let rc = unsafe { kill(pid, 15) };
    if rc == 0 {
        Ok(())
    } else {
        Err(format!(
            "kill(pid, SIGTERM) failed: {}",
            std::io::Error::last_os_error()
        ))
    }
}

/// CTRL_BREAK to the child's own console process group, whose id is the
/// child's pid because it was spawned with CREATE_NEW_PROCESS_GROUP. Never
/// group 0, which would reach every process on the console, cargo and this
/// test included. Hand-declared, as on Unix.
#[cfg(windows)]
fn send_termination_request(pid: u32) -> Result<(), String> {
    #[link(name = "kernel32")]
    extern "system" {
        fn GenerateConsoleCtrlEvent(ctrl_event: u32, process_group_id: u32) -> i32;
    }
    if pid == 0 {
        return Err("refusing to signal process group 0".to_string());
    }
    // SAFETY: `GenerateConsoleCtrlEvent` takes two plain integers.
    let rc = unsafe { GenerateConsoleCtrlEvent(1, pid) };
    if rc != 0 {
        Ok(())
    } else {
        Err(format!(
            "GenerateConsoleCtrlEvent(CTRL_BREAK, {pid}) failed: {}",
            std::io::Error::last_os_error()
        ))
    }
}

/// A running `nova run examples/03-http-server/src/main.nova`. Both of its
/// output streams are drained on threads for its whole life: a closed stdout
/// pipe aborts a later `println` (measured), and an undrained full one can
/// block. Dropping it kills a server that is still running, so a test that
/// panics part-way never leaves one on port 3000.
struct Http03Server {
    child: std::process::Child,
    stdout: Option<std::thread::JoinHandle<String>>,
    stderr: Option<std::thread::JoinHandle<String>>,
}

impl Http03Server {
    fn spawn() -> Self {
        Self::spawn_with_env(&[])
    }

    /// As [`Http03Server::spawn`], with `env` set in the child's environment.
    fn spawn_with_env(env: &[(&str, &str)]) -> Self {
        use std::io::Read;
        use std::process::Stdio;
        let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova"));
        cmd.arg("run")
            .arg(repo_root().join("examples/03-http-server/src/main.nova"))
            .envs(env.iter().copied())
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            // CREATE_NEW_PROCESS_GROUP: the child leads its own console
            // group, so a CTRL_BREAK aimed at it never reaches this test.
            cmd.creation_flags(0x0000_0200);
        }
        let mut child = cmd.spawn().expect("spawn nova run on the 03 example");
        let mut out = child.stdout.take().expect("stdout was piped");
        let mut err = child.stderr.take().expect("stderr was piped");
        let stdout = std::thread::spawn(move || {
            let mut s = String::new();
            let _ = out.read_to_string(&mut s);
            s
        });
        let stderr = std::thread::spawn(move || {
            let mut s = String::new();
            let _ = err.read_to_string(&mut s);
            s
        });
        Http03Server {
            child,
            stdout: Some(stdout),
            stderr: Some(stderr),
        }
    }

    fn pid(&self) -> u32 {
        self.child.id()
    }

    /// Waits until the port accepts a connection. `listen` installs the
    /// signal handler before `bind`, so from then on a signal is handled
    /// gracefully. The probe connection is dropped at once; the server reads
    /// its end of stream and closes it.
    fn wait_until_accepting(&mut self) {
        use std::time::{Duration, Instant};
        let deadline = Instant::now() + Duration::from_secs(120);
        loop {
            if let Ok(s) =
                std::net::TcpStream::connect_timeout(&http03_addr(), Duration::from_millis(500))
            {
                drop(s);
                return;
            }
            if let Ok(Some(status)) = self.child.try_wait() {
                let (out, err) = self.streams();
                panic!(
                    "the example exited before listening: {}; stdout={out:?} stderr={err:?}",
                    describe_status(&status)
                );
            }
            if Instant::now() >= deadline {
                self.kill_and_panic("the example never accepted on 127.0.0.1:3000 within 120 s");
            }
            std::thread::sleep(Duration::from_millis(100));
        }
    }

    /// Waits up to `limit` for the process to exit.
    fn wait_for_exit(&mut self, limit: std::time::Duration) -> Option<std::process::ExitStatus> {
        let deadline = std::time::Instant::now() + limit;
        loop {
            match self.child.try_wait().expect("try_wait") {
                Some(s) => return Some(s),
                None if std::time::Instant::now() >= deadline => return None,
                None => std::thread::sleep(std::time::Duration::from_millis(50)),
            }
        }
    }

    /// Both streams. Call only once the process has exited.
    fn streams(&mut self) -> (String, String) {
        let out = self
            .stdout
            .take()
            .map(|h| h.join().unwrap_or_default())
            .unwrap_or_default();
        let err = self
            .stderr
            .take()
            .map(|h| h.join().unwrap_or_default())
            .unwrap_or_default();
        (out, err)
    }

    fn kill_and_panic(&mut self, why: &str) -> ! {
        let _ = self.child.kill();
        let status = self.child.wait();
        let (out, err) = self.streams();
        panic!("{why}; force-killed: {status:?}; stdout={out:?} stderr={err:?}");
    }
}

impl Drop for Http03Server {
    fn drop(&mut self) {
        if matches!(self.child.try_wait(), Ok(None)) {
            let _ = self.child.kill();
            let _ = self.child.wait();
        }
    }
}

/// One client connection to the example. It reads responses framed by
/// `content-length`, and keeps any bytes past one response for the next.
struct Http03Conn {
    sock: std::net::TcpStream,
    pending: Vec<u8>,
}

/// One response: status, header values by lower-cased name, and body.
struct Http03Response {
    status: u16,
    headers: std::collections::HashMap<String, String>,
    body: String,
}

impl Http03Conn {
    fn open() -> Self {
        let sock = std::net::TcpStream::connect(HTTP03_ADDR).expect("connect to 127.0.0.1:3000");
        let limit = Some(std::time::Duration::from_secs(10));
        sock.set_read_timeout(limit).expect("set_read_timeout");
        sock.set_write_timeout(limit).expect("set_write_timeout");
        Http03Conn {
            sock,
            pending: Vec::new(),
        }
    }

    fn send(&mut self, bytes: &str) {
        use std::io::Write;
        self.sock
            .write_all(bytes.as_bytes())
            .expect("write to the example");
    }

    /// The next whole response, or a description of what arrived instead.
    fn response(&mut self) -> Result<Http03Response, String> {
        use std::io::Read;
        let mut chunk = [0u8; 4096];
        loop {
            if let Some(head_end) = self
                .pending
                .windows(4)
                .position(|w| w == b"\r\n\r\n")
                .map(|i| i + 4)
            {
                let head = String::from_utf8_lossy(&self.pending[..head_end]).to_string();
                let mut lines = head.split("\r\n");
                let status = lines
                    .next()
                    .and_then(|l| l.split_whitespace().nth(1))
                    .and_then(|s| s.parse::<u16>().ok())
                    .ok_or_else(|| format!("no status line in {head:?}"))?;
                let mut headers = std::collections::HashMap::new();
                for line in lines {
                    if let Some((name, value)) = line.split_once(':') {
                        headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
                    }
                }
                let len: usize = headers
                    .get("content-length")
                    .and_then(|v| v.parse().ok())
                    .ok_or_else(|| format!("no content-length in {head:?}"))?;
                if self.pending.len() >= head_end + len {
                    let body = String::from_utf8_lossy(&self.pending[head_end..head_end + len])
                        .to_string();
                    self.pending.drain(..head_end + len);
                    return Ok(Http03Response {
                        status,
                        headers,
                        body,
                    });
                }
            }
            match self.sock.read(&mut chunk) {
                Ok(0) => {
                    return Err(format!(
                        "peer closed mid-response; had {:?}",
                        String::from_utf8_lossy(&self.pending)
                    ))
                }
                Ok(n) => self.pending.extend_from_slice(&chunk[..n]),
                Err(e) => {
                    return Err(format!(
                        "read failed: {e}; had {:?}",
                        String::from_utf8_lossy(&self.pending)
                    ))
                }
            }
        }
    }

    /// `Ok` once the server has closed this connection: a read returns end of
    /// stream, or a reset, with nothing else pending.
    fn closed_by_server(&mut self) -> Result<(), String> {
        use std::io::Read;
        if !self.pending.is_empty() {
            return Err(format!(
                "unexpected bytes: {:?}",
                String::from_utf8_lossy(&self.pending)
            ));
        }
        let mut chunk = [0u8; 64];
        match self.sock.read(&mut chunk) {
            Ok(0) => Ok(()),
            Ok(n) => Err(format!(
                "expected end of stream, got {:?}",
                String::from_utf8_lossy(&chunk[..n])
            )),
            Err(e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted
                ) =>
            {
                Ok(())
            }
            Err(e) => Err(format!("expected end of stream, got error {e}")),
        }
    }
}

/// The next response on `conn`, or the test fails with the server's streams.
fn http03_response(server: &mut Http03Server, conn: &mut Http03Conn, what: &str) -> Http03Response {
    match conn.response() {
        Ok(r) => r,
        Err(e) => server.kill_and_panic(&format!("{what}: {e}")),
    }
}

/// Waits until a fresh connection to the example is refused, which proves
/// `listen` saw the shutdown flag and closed its listener. A refusal takes
/// about 2 s on Windows (measured), so each attempt allows 3 s.
fn wait_until_refused() -> Result<(), String> {
    use std::time::{Duration, Instant};
    let deadline = Instant::now() + Duration::from_secs(15);
    loop {
        match std::net::TcpStream::connect_timeout(&http03_addr(), Duration::from_secs(3)) {
            Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => return Ok(()),
            Ok(s) => drop(s),
            Err(_) => {}
        }
        if Instant::now() >= deadline {
            return Err("the listener was still accepting 15 s after the signal".to_string());
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// The gate: both routes; a body on a keep-alive connection; pipelining; a
/// malformed request; a request that straddles the signal; idle connections
/// closed after it; then exit 0.
#[test]
fn http_server_example_serves_and_exits_cleanly() {
    use std::time::Duration;
    let _port = lock_port_3000();
    assert_port_3000_free();
    let mut server = Http03Server::spawn();
    server.wait_until_accepting();

    // Routes, on one keep-alive connection K.
    let mut k = Http03Conn::open();
    k.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n");
    let hello = http03_response(&mut server, &mut k, "GET /");
    assert_eq!(hello.status, 200);
    assert_eq!(hello.body, "Hello from Nova!");
    k.send("GET /health HTTP/1.1\r\nhost: x\r\n\r\n");
    let health = http03_response(&mut server, &mut k, "GET /health");
    assert_eq!(health.status, 200);
    assert_eq!(
        health.headers.get("content-type").map(String::as_str),
        Some("application/json")
    );
    assert_eq!(
        health.headers.get("content-length").map(String::as_str),
        Some("15")
    );
    assert_eq!(health.body, r#"{"status":"ok"}"#);

    // A body is consumed exactly, so the connection stays usable (Review Focus 3).
    k.send("POST / HTTP/1.1\r\nhost: x\r\ncontent-length: 3\r\n\r\nabc");
    let post = http03_response(&mut server, &mut k, "POST / with a body");
    assert_eq!(post.status, 404, "only GET routes ship");
    k.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n");
    let again = http03_response(&mut server, &mut k, "GET / after a body");
    assert_eq!(again.body, "Hello from Nova!");
    // K now stays open and idle across the signal.

    // Pipelining: two requests in one write, answered in order.
    let mut p = Http03Conn::open();
    p.send("GET / HTTP/1.1\r\nhost: x\r\n\r\nGET /health HTTP/1.1\r\nhost: x\r\n\r\n");
    let first = http03_response(&mut server, &mut p, "pipelined GET /");
    let second = http03_response(&mut server, &mut p, "pipelined GET /health");
    assert_eq!(first.body, "Hello from Nova!");
    assert_eq!(second.body, r#"{"status":"ok"}"#);

    // A malformed request closes its connection with no response (Review Focus 4).
    let mut m = Http03Conn::open();
    m.send("this is not http\r\n\r\n");
    if let Err(e) = m.closed_by_server() {
        server.kill_and_panic(&format!("malformed request: {e}"));
    }

    // In flight: half a head, a pause past one tick so the server holds it,
    // the signal, proof the server saw it, and only then the rest.
    let mut f = Http03Conn::open();
    f.send("GET / HTTP/1.1\r\nho");
    std::thread::sleep(Duration::from_millis(300));
    if let Err(e) = send_termination_request(server.pid()) {
        server.kill_and_panic(&format!("could not deliver the signal: {e}"));
    }
    if let Err(e) = wait_until_refused() {
        server.kill_and_panic(&e);
    }
    f.send("st: x\r\n\r\n");
    let in_flight = http03_response(&mut server, &mut f, "the request straddling the signal");
    assert_eq!(in_flight.status, 200);
    assert_eq!(in_flight.body, "Hello from Nova!");
    if let Err(e) = f.closed_by_server() {
        server.kill_and_panic(&format!("after the in-flight answer: {e}"));
    }

    // Idle connections were closed after the signal.
    if let Err(e) = k.closed_by_server() {
        server.kill_and_panic(&format!("idle keep-alive K: {e}"));
    }
    if let Err(e) = p.closed_by_server() {
        server.kill_and_panic(&format!("idle pipelining P: {e}"));
    }

    let status = match server.wait_for_exit(Duration::from_secs(10)) {
        Some(s) => s,
        None => server.kill_and_panic("the example did not exit within 10 s of finishing"),
    };
    let (out, err) = server.streams();
    assert_eq!(
        status.code(),
        Some(0),
        "{}; stdout={out:?} stderr={err:?}",
        describe_status(&status)
    );
    assert!(err.contains("listening on :3000"), "stderr: {err:?}");
}

/// A second signal while a request is still in flight takes the default
/// action at once, well before that request's 10 s deadline.
#[test]
fn http_server_example_second_signal_forces_exit() {
    use std::time::Duration;
    let _port = lock_port_3000();
    assert_port_3000_free();
    let mut server = Http03Server::spawn();
    server.wait_until_accepting();

    let mut stalled = Http03Conn::open();
    stalled.send("GET / HTTP/1.1\r\nho");
    std::thread::sleep(Duration::from_millis(300));
    if let Err(e) = send_termination_request(server.pid()) {
        server.kill_and_panic(&format!("could not deliver the first signal: {e}"));
    }
    // Unix merges a second SIGTERM sent while the first is pending, so wait
    // for proof the first was handled before sending the second.
    if let Err(e) = wait_until_refused() {
        server.kill_and_panic(&e);
    }
    if let Err(e) = send_termination_request(server.pid()) {
        server.kill_and_panic(&format!("could not deliver the second signal: {e}"));
    }
    let status = match server.wait_for_exit(Duration::from_secs(5)) {
        Some(s) => s,
        None => server.kill_and_panic("a second signal did not end the process within 5 s"),
    };
    let (out, err) = server.streams();
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        assert_eq!(
            status.signal(),
            Some(15),
            "{}; stdout={out:?} stderr={err:?}",
            describe_status(&status)
        );
    }
    #[cfg(windows)]
    {
        assert_eq!(
            status.code().map(|c| c as u32),
            Some(0xC000_013A),
            "{}; stdout={out:?} stderr={err:?}",
            describe_status(&status)
        );
    }
    drop(stalled);
}

/// A request that stalls mid-head across the signal is held until its 10 s
/// deadline and then dropped, so the drain always finishes and the process
/// still exits 0 (Review Focus 1).
#[test]
fn http_server_example_drops_a_stalled_request_at_its_deadline() {
    use std::time::{Duration, Instant};
    let _port = lock_port_3000();
    assert_port_3000_free();
    let mut server = Http03Server::spawn();
    server.wait_until_accepting();

    let mut stalled = Http03Conn::open();
    stalled.send("GET / HTTP/1.1\r\nho");
    std::thread::sleep(Duration::from_millis(300));
    let signalled = Instant::now();
    if let Err(e) = send_termination_request(server.pid()) {
        server.kill_and_panic(&format!("could not deliver the signal: {e}"));
    }
    let status = match server.wait_for_exit(Duration::from_secs(20)) {
        Some(s) => s,
        None => server.kill_and_panic("the stalled request held the process past 20 s"),
    };
    let took = signalled.elapsed();
    let (out, err) = server.streams();
    assert_eq!(
        status.code(),
        Some(0),
        "{}; stdout={out:?} stderr={err:?}",
        describe_status(&status)
    );
    assert!(
        took >= Duration::from_secs(8),
        "exited {took:?} after the signal: the stalled request was not held to its deadline"
    );
    if let Err(e) = stalled.closed_by_server() {
        panic!("the stalled connection was not closed by the server: {e}");
    }
}

/// A client that keeps pipelining across the signal cannot hold the drain
/// open. Every write below completes one request and starts the next, so the
/// server's buffer is never empty after an answer; a request taken up after
/// the stop must already be whole, so the server stops reading and closes
/// this connection although the client is still sending. Found by the
/// whole-branch review.
#[test]
fn http_server_example_bounds_the_drain_for_a_pipelining_client() {
    use std::io::Write;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use std::time::{Duration, Instant};
    let _port = lock_port_3000();
    assert_port_3000_free();
    let mut server = Http03Server::spawn();
    server.wait_until_accepting();

    let mut conn = Http03Conn::open();
    let mut feed = conn.sock.try_clone().expect("clone the client socket");
    let stop = Arc::new(AtomicBool::new(false));
    let stop_feeding = Arc::clone(&stop);
    let feeder = std::thread::spawn(move || {
        let _ = feed.write_all(b"GET / HTTP/1.1\r\nho");
        while !stop_feeding.load(Ordering::SeqCst) {
            if feed
                .write_all(b"st: x\r\n\r\nGET / HTTP/1.1\r\nho")
                .is_err()
            {
                return;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    });

    // The stream is flowing before the signal.
    for i in 0..3 {
        let r = http03_response(&mut server, &mut conn, &format!("pipelined response {i}"));
        assert_eq!(r.body, "Hello from Nova!");
    }
    if let Err(e) = send_termination_request(server.pid()) {
        stop.store(true, Ordering::SeqCst);
        server.kill_and_panic(&format!("could not deliver the signal: {e}"));
    }
    if let Err(e) = wait_until_refused() {
        stop.store(true, Ordering::SeqCst);
        server.kill_and_panic(&e);
    }
    // Answers to requests already taken up may still arrive; then the server
    // must close the connection.
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        if Instant::now() >= deadline {
            stop.store(true, Ordering::SeqCst);
            server.kill_and_panic("a pipelining client was still being served 5 s after the stop");
        }
        match conn.response() {
            Ok(r) => assert_eq!(r.body, "Hello from Nova!"),
            Err(_) => break,
        }
    }
    stop.store(true, Ordering::SeqCst);
    let _ = feeder.join();
    let status = match server.wait_for_exit(Duration::from_secs(10)) {
        Some(s) => s,
        None => server.kill_and_panic("the example did not exit after the pipelining connection"),
    };
    let (out, err) = server.streams();
    assert_eq!(
        status.code(),
        Some(0),
        "{}; stdout={out:?} stderr={err:?}",
        describe_status(&status)
    );
}

/// With port 3000 taken, the example fails at once with a nonzero exit and
/// the generic unwrap message, rather than hanging (design §6; Review Focus 5).
#[test]
fn http_server_example_fails_fast_when_the_port_is_taken() {
    use std::time::Duration;
    let _port = lock_port_3000();
    assert_port_3000_free();
    let _holder = std::net::TcpListener::bind("0.0.0.0:3000").expect("hold port 3000");
    let mut server = Http03Server::spawn();
    let status = match server.wait_for_exit(Duration::from_secs(120)) {
        Some(s) => s,
        None => server.kill_and_panic("the example did not exit with port 3000 already taken"),
    };
    let (out, err) = server.streams();
    assert!(
        !status.success(),
        "it must fail: {}; stdout={out:?} stderr={err:?}",
        describe_status(&status)
    );
    assert!(
        err.contains("called `unwrap` on an `Err` value"),
        "stderr: {err:?}"
    );
}

/// Stops the example with a termination request and returns the live-object
/// count of every collection it logged. The server must have been started
/// with `NOVA_GC_DEBUG=1`, and must exit 0: a crash under collection is a
/// failure here, not a pass.
fn http03_stop_for_live_counts(server: &mut Http03Server) -> Vec<u64> {
    use std::time::Duration;
    if let Err(e) = send_termination_request(server.pid()) {
        server.kill_and_panic(&format!("could not deliver the signal: {e}"));
    }
    let status = match server.wait_for_exit(Duration::from_secs(10)) {
        Some(s) => s,
        None => server.kill_and_panic("the example did not exit within 10 s of the signal"),
    };
    let (out, err) = server.streams();
    assert_eq!(
        status.code(),
        Some(0),
        "{}; stdout={out:?} stderr={err:?}",
        describe_status(&status)
    );
    gc_live_object_counts(&err)
}

/// Fails unless every collection across `requests` kept fewer than `bound`
/// objects live, and at least 10 collections ran, so the bound was checked
/// across the whole run rather than only at its start. The bound is checked
/// first: a leak grows the heap, which raises the next collection's
/// threshold, so a leaking run also collects less often, and checking the
/// count first would report the leak as too few collections (measured: a
/// leaking 3,000-connection run collected 4 times, reaching 110,906 live
/// objects).
fn assert_live_set_bounded(live: &[u64], requests: usize, bound: u64) {
    let max = live.iter().copied().max().unwrap_or(0);
    assert!(
        max < bound,
        "the live set must stay bounded: a collection reported {max} live objects, \
         the bound is {bound} (all {} collections: {live:?})",
        live.len()
    );
    assert!(
        live.len() >= 10,
        "expected at least 10 collections over {requests} requests, saw {}: {live:?}",
        live.len()
    );
}

/// Phase 2's "server-side apps work", measured on the collector: 3,000
/// requests, each on a connection of its own, leave a bounded live set. Every
/// connection is a task the server spawns and the executor releases when it
/// finishes, so a root that outlived its task would leave at least one more
/// object live per connection. The design measured 38-109 live objects on
/// Windows and on Linux
/// (docs/superpowers/specs/2026-10-05-gc-unix-stack-bounds-design.md §2.4);
/// the bound is about 10x that, and a leak of one object per connection
/// crosses it after about 1,000 connections.
#[test]
fn http_server_example_keeps_a_bounded_live_set() {
    const REQUESTS: usize = 3_000;
    let _port = lock_port_3000();
    assert_port_3000_free();
    let mut server = Http03Server::spawn_with_env(&[("NOVA_GC_DEBUG", "1")]);
    server.wait_until_accepting();
    for i in 0..REQUESTS {
        let mut conn = Http03Conn::open();
        conn.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n");
        let r = http03_response(&mut server, &mut conn, &format!("request {i}"));
        assert_eq!(r.status, 200, "request {i}");
    }
    let live = http03_stop_for_live_counts(&mut server);
    assert_live_set_bounded(&live, REQUESTS, 1_000);
}

/// The same property with eight clients at once, 375 connections each: more
/// tasks are alive at a time, so the live set sits higher, but it must still
/// stay flat. Measured on Linux while planning this test: 61-544 live objects
/// across 22 collections, flat
/// (docs/superpowers/plans/2026-10-05-gc-unix-stack-bounds.md, Review Focus
/// 1). A leak of one object per connection would add 3,000.
#[test]
fn http_server_example_keeps_a_bounded_live_set_under_concurrent_clients() {
    const CLIENTS: usize = 8;
    const PER_CLIENT: usize = 375;
    let _port = lock_port_3000();
    assert_port_3000_free();
    let mut server = Http03Server::spawn_with_env(&[("NOVA_GC_DEBUG", "1")]);
    server.wait_until_accepting();
    let clients: Vec<_> = (0..CLIENTS)
        .map(|c| {
            std::thread::spawn(move || -> Result<(), String> {
                for i in 0..PER_CLIENT {
                    let mut conn = Http03Conn::open();
                    conn.send("GET / HTTP/1.1\r\nhost: x\r\n\r\n");
                    let r = conn
                        .response()
                        .map_err(|e| format!("client {c}, request {i}: {e}"))?;
                    if r.status != 200 {
                        return Err(format!("client {c}, request {i}: status {}", r.status));
                    }
                }
                Ok(())
            })
        })
        .collect();
    for client in clients {
        let outcome = client
            .join()
            .unwrap_or_else(|_| Err("a client thread panicked".to_string()));
        if let Err(e) = outcome {
            server.kill_and_panic(&e);
        }
    }
    let live = http03_stop_for_live_counts(&mut server);
    assert_live_set_bounded(&live, CLIENTS * PER_CLIENT, 2_000);
}

/// A server that never calls `Server::listen` installs no handler, so a
/// termination request still ends it by the default action (design §7.4;
/// Review Focus 2). `docs/benchmarks/server.nova` is such a server. This is
/// the 2026-10-04 spike's measurement (draft PR #95), kept. It passes before
/// this branch exists, by design: it pins behaviour that must not change.
#[test]
fn a_server_that_never_calls_listen_keeps_the_default_signal_action() {
    use std::io::{BufRead, BufReader, Read};
    use std::process::Stdio;
    use std::time::{Duration, Instant};

    let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("nova"));
    cmd.arg("run")
        .arg(repo_root().join("docs/benchmarks/server.nova"))
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(0x0000_0200);
    }
    let mut child = cmd
        .spawn()
        .expect("spawn nova run docs/benchmarks/server.nova");
    let stdout = child.stdout.take().expect("stdout was piped");
    let (tx, rx) = std::sync::mpsc::channel::<String>();
    let out_thread = std::thread::spawn(move || {
        let mut lines = BufReader::new(stdout).lines().map_while(Result::ok);
        if let Some(first) = lines.next() {
            let _ = tx.send(first);
        }
        lines.collect::<Vec<_>>().join("\n")
    });
    let mut stderr = child.stderr.take().expect("stderr was piped");
    let err_thread = std::thread::spawn(move || {
        let mut s = String::new();
        let _ = stderr.read_to_string(&mut s);
        s
    });

    let first = rx
        .recv_timeout(Duration::from_secs(120))
        .unwrap_or_default();
    if !first.contains("listening on") {
        let _ = child.kill();
        let status = child.wait();
        let err = err_thread.join().unwrap_or_default();
        panic!("no ready line; got {first:?}; status {status:?}; stderr {err:?}");
    }
    // Let the server reach its parked accept before the request arrives.
    std::thread::sleep(Duration::from_millis(500));
    if let Err(e) = send_termination_request(child.id()) {
        let _ = child.kill();
        let _ = child.wait();
        panic!("could not deliver the request: {e}");
    }
    let deadline = Instant::now() + Duration::from_secs(10);
    let status = loop {
        if let Some(s) = child.try_wait().expect("try_wait") {
            break s;
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let s = child.wait();
            panic!("the request did not end the server within 10 s; force-killed: {s:?}");
        }
        std::thread::sleep(Duration::from_millis(50));
    };
    let out = out_thread.join().unwrap_or_default();
    let err = err_thread.join().unwrap_or_default();
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        assert_eq!(
            status.signal(),
            Some(15),
            "{}; stdout={out:?} stderr={err:?}",
            describe_status(&status)
        );
    }
    #[cfg(windows)]
    {
        assert_eq!(
            status.code().map(|c| c as u32),
            Some(0xC000_013A),
            "{}; stdout={out:?} stderr={err:?}",
            describe_status(&status)
        );
    }
}

// ---------------------------------------------------------------------------
// `examples/04-todo-cli`: the Phase 2 gate in `nova-spec/60-EXAMPLES.md` §4.
// Design: docs/superpowers/specs/2026-10-05-examples-04-todo-cli-design.md
// §7.4, and the plan's Review Focus.

/// A fresh, empty directory for one 04 test. `todos.json` lives in the
/// working directory, so no two tests may share one. Each tag is unique to
/// its test, so removing a stale one races with no sibling.
fn todo_workdir(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("nova-todo-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("todo work dir");
    dir
}

/// `nova run examples/04-todo-cli/src/main.nova -- ARGS`, in `dir`.
fn todo_run(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
    nova()
        .current_dir(dir)
        .arg("run")
        .arg(repo_root().join("examples/04-todo-cli/src/main.nova"))
        .arg("--")
        .args(args)
        .output()
        .expect("run nova")
}

/// `examples/04-todo-cli` built into `bin`.
fn todo_build(bin: &std::path::Path) -> std::path::PathBuf {
    let exe = bin.join(format!("todo{}", std::env::consts::EXE_SUFFIX));
    nova()
        .arg("build")
        .arg(repo_root().join("examples/04-todo-cli/src/main.nova"))
        .arg("-o")
        .arg(&exe)
        .assert()
        .success();
    exe
}

/// The built `exe`, run in `dir` with real argv.
fn todo_exe(exe: &std::path::Path, dir: &std::path::Path, args: &[&str]) -> std::process::Output {
    std::process::Command::new(exe)
        .current_dir(dir)
        .args(args)
        .output()
        .expect("run the built todo")
}

fn stdout_of(out: &std::process::Output) -> String {
    String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n")
}

fn stderr_of(out: &std::process::Output) -> String {
    String::from_utf8_lossy(&out.stderr).replace("\r\n", "\n")
}

/// The gate's cycle, add → list → done → list, through `run`: every step's
/// output, then the file. `add buy milk` is two arguments and `add "walk
/// dog"` is one; both must store a two-word title.
fn todo_cycle(dir: &std::path::Path, run: &dyn Fn(&[&str]) -> std::process::Output) {
    let step = |args: &[&str], want: &str| {
        let out = run(args);
        assert!(
            out.status.success(),
            "{args:?}: {:?}; stderr={}",
            out.status,
            stderr_of(&out)
        );
        assert_eq!(stdout_of(&out), want, "{args:?}");
    };
    step(&["add", "buy", "milk"], "added: 1\n");
    step(&["add", "walk dog"], "added: 2\n");
    step(&["list"], "[ ] 1: buy milk\n[ ] 2: walk dog\n");
    step(&["done", "1"], "");
    step(&["list"], "[x] 1: buy milk\n[ ] 2: walk dog\n");
    let file = std::fs::read_to_string(dir.join("todos.json")).expect("todos.json written");
    assert_eq!(
        file,
        r#"[{"id":1,"title":"buy milk","done":true},{"id":2,"title":"walk dog","done":false}]"#
    );
}

/// The gate under `nova run`.
#[test]
fn todo_cli_cycle_under_nova_run() {
    let dir = todo_workdir("run-cycle");
    todo_cycle(&dir, &|args| todo_run(&dir, args));
}

/// The gate as a built executable, whose arguments come from the OS argv:
/// the measurement of docs/adr/0023's decision 3 on each CI operating system.
#[test]
fn todo_cli_cycle_as_a_built_executable() {
    let bin = todo_workdir("built-bin");
    let exe = todo_build(&bin);
    let dir = todo_workdir("built-cycle");
    todo_cycle(&dir, &|args| todo_exe(&exe, &dir, args));
}

/// A Thai title survives the arguments, `todos.json` and `list` (Review
/// Focus 1).
fn todo_thai(dir: &std::path::Path, run: &dyn Fn(&[&str]) -> std::process::Output) {
    let title = "ซื้อนม";
    let added = run(&["add", title]);
    assert!(added.status.success(), "add: {}", stderr_of(&added));
    assert_eq!(stdout_of(&run(&["list"])), format!("[ ] 1: {title}\n"));
    let file = std::fs::read_to_string(dir.join("todos.json")).expect("todos.json written");
    assert_eq!(
        file,
        format!("[{{\"id\":1,\"title\":\"{title}\",\"done\":false}}]")
    );
}

#[test]
fn todo_cli_keeps_a_thai_title_under_nova_run() {
    let dir = todo_workdir("thai-run");
    todo_thai(&dir, &|args| todo_run(&dir, args));
}

#[test]
fn todo_cli_keeps_a_thai_title_as_a_built_executable() {
    let bin = todo_workdir("thai-bin");
    let exe = todo_build(&bin);
    let dir = todo_workdir("thai-built");
    todo_thai(&dir, &|args| todo_exe(&exe, &dir, args));
}

/// No command, or an unknown one: the usage line on stderr, exit 1, and no
/// file written.
#[test]
fn todo_cli_without_a_command_prints_usage_and_exits_1() {
    let dir = todo_workdir("usage");
    for args in [&[][..], &["frobnicate"][..]] {
        let out = todo_run(&dir, args);
        assert_eq!(out.status.code(), Some(1), "{args:?}");
        assert_eq!(
            stderr_of(&out),
            "usage: todo {add <title> | list | done <id>}\n",
            "{args:?}"
        );
        assert!(out.stdout.is_empty(), "{args:?}");
    }
    assert!(!dir.join("todos.json").exists());
}

/// A `todos.json` that is not JSON, or not a list of todos, is refused by
/// every command and never written (Review Focus 3).
#[test]
fn todo_cli_refuses_a_corrupt_todos_json_and_leaves_it_alone() {
    let dir = todo_workdir("corrupt");
    let cases: [(&str, &[&str]); 4] = [
        ("{not json", &["list"]),
        ("{not json", &["add", "x"]),
        ("{not json", &["done", "1"]),
        (r#"[{"id":1}]"#, &["list"]),
    ];
    for (content, args) in cases {
        std::fs::write(dir.join("todos.json"), content).expect("write the corrupt file");
        let out = todo_run(&dir, args);
        assert_eq!(out.status.code(), Some(1), "{content:?} {args:?}");
        let err = stderr_of(&out);
        assert!(
            err.starts_with("todo: cannot use todos.json: "),
            "{content:?} {args:?}: {err:?}"
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("todos.json")).expect("still there"),
            content,
            "{content:?} {args:?} must leave the file alone"
        );
    }
}

/// `done` with an id no todo has, or one that is not a number, changes
/// nothing and prints nothing.
#[test]
fn todo_cli_done_with_an_unknown_id_changes_nothing() {
    let dir = todo_workdir("unknown-id");
    assert!(todo_run(&dir, &["add", "a"]).status.success());
    let before = std::fs::read(dir.join("todos.json")).expect("written");
    for id in ["99", "x", ""] {
        let out = todo_run(&dir, &["done", id]);
        assert!(out.status.success(), "{id:?}: {}", stderr_of(&out));
        assert!(out.stdout.is_empty(), "{id:?}");
        assert_eq!(
            std::fs::read(dir.join("todos.json")).expect("still there"),
            before,
            "{id:?}"
        );
    }
}

/// Spec 3.4b §3.3: `nova check` prints a fix's title as a help line, in
/// place of the note it replaces.
#[test]
fn check_prints_a_fix_as_a_help_line() {
    let dir = std::env::temp_dir().join("nova-check-help-mutable");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("temp dir");
    let main = dir.join("main.nova");
    std::fs::write(
        &main,
        "fn main() {\n    let x = 1\n    x = 2\n    println(\"${x}\")\n}\n",
    )
    .expect("write");
    // Uncoloured, so `= help:` is one run of text (termcolor's Auto colours
    // a pipe too).
    let assert = nova()
        .env("NO_COLOR", "1")
        .arg("check")
        .arg(&main)
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("= help: make `x` mutable"),
        "stderr: {stderr}"
    );
    assert!(
        !stderr.contains("declare it as"),
        "the fix replaces the note: {stderr}"
    );
}

/// Spec 3.4b §4.4: the resolver's fix, placed in another file.
#[test]
fn check_prints_make_public_as_a_help_line() {
    let dir = std::env::temp_dir().join("nova-check-help-public");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("temp dir");
    std::fs::write(dir.join("lib.nova"), "fn hidden() -> Int {\n    1\n}\n").expect("write lib");
    let main = dir.join("app.nova");
    std::fs::write(
        &main,
        "import lib::{hidden}\n\nfn main() {\n    println(\"${hidden()}\")\n}\n",
    )
    .expect("write main");
    // Uncoloured, so `= help:` is one run of text (termcolor's Auto colours
    // a pipe too).
    let assert = nova()
        .env("NO_COLOR", "1")
        .arg("check")
        .arg(&main)
        .assert()
        .failure();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("= help: make `hidden` public in `lib`"),
        "stderr: {stderr}"
    );
}

/// `examples/05-geometry` (spec
/// `docs/superpowers/specs/2026-10-11-phase-3-5a-the-documentation-site-design.md`
/// §13): a program and the path library beside it.
#[test]
fn example_05_geometry_runs() {
    let home = std::env::temp_dir().join("nova-run-05-geometry-home");
    let _ = std::fs::remove_dir_all(&home);
    nova()
        .current_dir(repo_root().join("examples/05-geometry"))
        .env("NOVA_HOME", &home)
        .arg("run")
        .assert()
        .success()
        .stdout(
            "area 3.141592653589793, perimeter 6.283185307179586\n\
             area 6, perimeter 10\n\
             total area 9.141592653589793\n",
        );
}