brink-compiler 0.0.17

Compiler for inkle's ink narrative scripting language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
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
#![allow(
    clippy::unwrap_used,
    clippy::panic,
    clippy::print_stderr,
    clippy::wildcard_enum_match_arm,
    clippy::match_same_arms
)]

use std::collections::HashMap;
use std::path::Path;

use brink_runtime::{DotNetRng, Step, Story};

/// Helper: compile from an in-memory file system (`HashMap` of path to source).
fn compile_mem(
    entry: &str,
    files: &HashMap<&str, &str>,
) -> Result<brink_format::StoryData, brink_compiler::CompileError> {
    brink_compiler::compile(entry, |path| {
        files.get(path).map(|s| (*s).to_string()).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("file not found: {path}"),
            )
        })
    })
    .map(|output| output.data)
}

// ── Single file ─────────────────────────────────────────────────────

#[test]
fn compile_minimal_story() {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", "Hello, world!\n")]);

    let story = compile_mem("main.ink", &files).unwrap();
    // The driver ran without errors (parsed, lowered, analyzed, codegen).
    assert!(
        !story.containers.is_empty(),
        "expected non-empty containers"
    );
}

#[test]
fn compile_story_with_knots() {
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "\
Hello!
-> greet

== greet ==
Welcome to the story.
-> END
",
    )]);

    let story = compile_mem("main.ink", &files).unwrap();
    assert!(
        !story.containers.is_empty(),
        "expected non-empty containers"
    );
}

// ── INCLUDE discovery ───────────────────────────────────────────────

#[test]
fn compile_follows_includes() {
    let files: HashMap<&str, &str> = HashMap::from([
        ("main.ink", "INCLUDE helpers.ink\nHello!\n-> greet\n"),
        ("helpers.ink", "== greet ==\nWelcome.\n-> END\n"),
    ]);

    let story = compile_mem("main.ink", &files).unwrap();
    assert!(
        !story.containers.is_empty(),
        "expected non-empty containers"
    );
}

#[test]
fn compile_nested_includes() {
    let files: HashMap<&str, &str> = HashMap::from([
        ("main.ink", "INCLUDE a.ink\nMain content.\n"),
        ("a.ink", "INCLUDE b.ink\n"),
        ("b.ink", "VAR x = 5\n== knot_b ==\nHello from b.\n-> END\n"),
    ]);

    let story = compile_mem("main.ink", &files).unwrap();
    assert!(
        !story.containers.is_empty(),
        "expected non-empty containers"
    );
}

#[test]
fn compile_circular_includes_detected() {
    // Each file includes the other — should be detected as a circular dependency.
    let files: HashMap<&str, &str> = HashMap::from([
        ("a.ink", "INCLUDE b.ink\nContent A.\n"),
        ("b.ink", "INCLUDE a.ink\nContent B.\n"),
    ]);

    let err = compile_mem("a.ink", &files).unwrap_err();
    assert!(
        matches!(err, brink_compiler::CompileError::CircularInclude(_)),
        "expected CircularInclude variant, got: {err}"
    );
}

// ── Relative path resolution ────────────────────────────────────────

#[test]
fn compile_resolves_relative_include_paths() {
    let files: HashMap<&str, &str> = HashMap::from([
        ("src/main.ink", "INCLUDE utils/helpers.ink\nHello!\n"),
        ("src/utils/helpers.ink", "== greet ==\nHi.\n-> END\n"),
    ]);

    let story = compile_mem("src/main.ink", &files).unwrap();
    assert!(
        !story.containers.is_empty(),
        "expected non-empty containers"
    );
}

// ── Error cases ─────────────────────────────────────────────────────

#[test]
fn compile_missing_entry_file() {
    let files: HashMap<&str, &str> = HashMap::new();

    let err = compile_mem("nonexistent.ink", &files).unwrap_err();
    assert!(
        matches!(err, brink_compiler::CompileError::Io(_)),
        "expected I/O error for missing entry file, got: {err}"
    );
}

#[test]
fn compile_missing_included_file() {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", "INCLUDE missing.ink\nHello!\n")]);

    let err = compile_mem("main.ink", &files).unwrap_err();
    assert!(
        matches!(err, brink_compiler::CompileError::Io(_)),
        "expected I/O error for missing included file, got: {err}"
    );
}

/// A bare `INCLUDE` with no path lowers to an empty `FILE_PATH` node and the
/// parser's E037 ("expected file path") diagnostic. Discovery must not
/// attempt to read the empty path (which would surface a raw `Io` error and
/// swallow the diagnostic before it reaches the user) — see #708.
#[test]
fn compile_bare_include_reports_e037_not_io_error() {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", "INCLUDE\nHello!\n")]);

    let err = compile_mem("main.ink", &files).unwrap_err();
    assert!(
        matches!(err, brink_compiler::CompileError::Diagnostics(_)),
        "expected a Diagnostics(E037) compile error, got: {err}"
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E037"),
        "expected E037 (expected file path) among diagnostics, got: {codes:?}"
    );
}

// ── Native (.brink) discovery (B0.10b, #1288) ───────────────────────

/// A `.brink` entry with no `brink.toml` anywhere above it (the
/// single-file-project ruling: root = the entry's own directory) compiles
/// via `compile_path`, proving `prepare_driver`'s native branch dispatches
/// and its entry-key resolution (`native_source_root` + `relative_key`)
/// lines up with the key `discover_native` registered the entry under.
#[test]
fn compile_path_native_single_file_no_brink_toml() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-single-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output = result.expect("single-file native project should compile");
    assert!(
        !output.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

/// A `.brink` entry nested under a subdirectory, still with no `brink.toml`,
/// so the root is the entry's *own* directory (not an ancestor) — exercises
/// `native_source_root`'s fallback with a non-trivial (non-".") entry path,
/// and a sibling file in the same directory that discovery must find
/// without breaking the entry's own compile.
#[test]
fn compile_path_native_multi_file_no_brink_toml() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-multi-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("story")).unwrap();
    std::fs::write(
        dir.join("story/main.brink"),
        "flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("story/other.brink"),
        "flow other() {\n  Hi. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("story/main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output = result.expect("multi-file native project should compile");
    assert!(
        !output.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

/// A lambda in a real `.brink` project, compiled through the production
/// entry point and **run** (issues #1685 and #1709).
///
/// This assertion used to point the other way. Through #1685 a lambda
/// lowered to HIR and then stopped at a targeted `E052` codegen fence
/// (`lir::lower::expr::lower_lambda_fence`), because an anonymous body had
/// no runtime representation; this test pinned that fence green, which is
/// precisely why nothing signalled that the fn-value verb layer (#1679)
/// could not actually be handed a lambda. #1709 lifts the lambda into a
/// synthesized function value, so the fence is gone and the user-visible
/// fact to pin is the opposite one: the lambda compiles, is *called*, and
/// its result reaches the transcript.
#[test]
fn compile_path_native_lambda_lifts_to_a_callable_function_value() {
    let output = compile_and_run_native(
        "lambda-lift",
        "fn tally(n: int): int {\n  let add = |x| x + 1;\n  return add(n);\n}\n\n\
         flow main() {\n  Tally: {tally(41)} -> END\n}\n",
    );
    assert!(
        output.contains("Tally: 42"),
        "the lambda must be lifted to a real function value and invoked, got: {output:?}"
    );
}

/// The by-value capture half of lambda lifting (RULED 2026-07-19, issue
/// #1709): a lambda's read of an enclosing local is snapshotted into the
/// closure environment **at the point the lambda value is made**, so a
/// later write to that local cannot be seen through the already-created
/// value. `bump` is created while `step` is `1`, `step` then becomes `100`,
/// and the call still adds `1`.
#[test]
fn compile_path_native_lambda_captures_by_value_at_creation() {
    let output = compile_and_run_native(
        "lambda-capture",
        "fn shifted(): int {\n  let step = 1;\n  let bump = |x| x + step;\n  \
         step = 100;\n  return bump(5);\n}\n\n\
         flow main() {\n  Shifted: {shifted()} -> END\n}\n",
    );
    assert!(
        output.contains("Shifted: 6"),
        "a capture is a creation-site snapshot, not a live read, got: {output:?}"
    );
}

/// Two lifting edges the tier1-native golden case does not reach (#1709).
///
/// `tailless` — a braced body whose block ends in a **statement**: "last
/// expression is the value" has no last expression, so the value comes from
/// the explicit `return` inside the block, which (per the 2026-07-19
/// ruling) leaves the *lambda*, not the enclosing function. Lifting must
/// therefore not append a synthetic terminal `Return` here; if it returned
/// from the wrong frame, `tailless` would never reach `f(41)`.
///
/// `nested` — **transitive** capture: `inner` reads `outer`, a local of the
/// frame two levels out. `outer` is not free in `inner`'s own enclosing
/// frame by accident — it has to be captured by `make` *and* re-captured by
/// `inner` for the read to resolve, which is exactly what the free-name
/// walk's nested-lambda arm is for.
#[test]
fn compile_path_native_lambda_tailless_body_and_transitive_capture() {
    let output = compile_and_run_native(
        "lambda-edges",
        "fn tailless() {\n  let f = |x| { return x + 1; };\n  return f(41);\n}\n\n\
         fn nested() {\n  let outer = 10;\n  \
         let make = |y| { let inner = |z| z + outer; inner(y) };\n  return make(5);\n}\n\n\
         flow main() {\n  Tailless: {tailless()}\n  Nested: {nested()} -> END\n}\n",
    );
    assert!(
        output.contains("Tailless: 42"),
        "an explicit `return` must leave the lambda, not the enclosing fn, got: {output:?}"
    );
    assert!(
        output.contains("Nested: 15"),
        "a nested lambda's read of a two-levels-out local must capture transitively, \
         got: {output:?}"
    );
}

/// A lambda handed straight to the pure trio (`docs/stdlib-spec.md` §4,
/// issue #1679) — the interaction #1709 exists to unblock. `#fn(target)`
/// over a named function was the only fn-value spelling that reached these
/// ops before lifting landed.
#[test]
fn compile_path_native_lambda_is_a_legal_verb_callback() {
    let output = compile_and_run_native(
        "lambda-verb-callback",
        "fn doubled() {\n  return map([1, 2, 3], |x| x * 2);\n}\n\n\
         flow main() {\n  Doubled: {doubled()} -> END\n}\n",
    );
    assert!(
        output.contains("Doubled: [2, 4, 6]"),
        "a lambda literal must be a legal `map` callback, got: {output:?}"
    );
}

/// A lambda reading its own `let` name — recursion — is a compile-time
/// refusal (`E158`), not a compile-clean runtime fault (issue #1709
/// review). `f`'s initializer is scanned for captures *before* `let f = …`
/// finishes binding `f`, so `f` has no temp slot yet in the enclosing frame
/// even though the analyzer resolves it as a real local; falling through
/// would let call lowering target `f`'s own `let`-declaration id as though
/// it were a callable function — a miscompile that previously only
/// surfaced as `RuntimeError::UnresolvedDefinition` when `f` called itself.
#[test]
fn compile_path_native_lambda_self_reference_is_e158() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-lambda-self-ref-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "fn a() {\n  let f = |x| {\n    if x <= 0 { return 0; }\n    \
         return f(x - 1) + 1;\n  };\n  return f(3);\n}\n\n\
         flow main() {\n  Out: {a()} -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let err = result.expect_err(
        "a lambda reading its own not-yet-bound `let` name (recursion) must refuse to \
         compile, not silently target the wrong container and fault at runtime",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E158"),
        "expected E158 (unliftable lambda capture) among diagnostics, got: {codes:?}"
    );
}

// ── File-scope VAR/CONST lambda literal decl defaults (issue #1774) ────

/// A native `var`/`const` may hold a lambda literal as its declaration
/// default (RULED 2026-08-01, `docs/decision-log.md` #1774) — the E083 gate
/// this used to hit is lifted, and the lambda is lowered through the same
/// lambda-lifting machinery (#1709) as a local lambda, just with an empty
/// enclosing frame (no locals to capture at file scope). Reachability: the
/// production `compile_path` entry point.
///
/// Deliberately asserts *compilation*, not invocation from `flow main()` —
/// see `compile_path_native_lambda_valued_global_call_site_resolves` below,
/// which does invoke the fn value from `flow main()` and pins the separate
/// call-site-resolution fix from issue #2083.
#[test]
fn compile_path_native_const_lambda_literal_decl_default_compiles() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-lambda-decl-default-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "const twice = |x| x * 2\n\nflow main() {\n  Hi. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output = result.expect("a file-scope const lambda literal must compile (E083 lifted)");
    let global = output
        .data
        .variables
        .iter()
        .find(|v| output.data.name_table[v.name.0 as usize] == "twice")
        .expect("global `twice` must be present in the compiled StoryData");
    assert!(
        !global.mutable,
        "a `const` global stays immutable regardless of its default's kind"
    );
    let brink_format::Value::FnRef(target) = global.default_value else {
        panic!(
            "a file-scope lambda has no enclosing frame to capture from, so it \
             must fold to a bare FnRef (no bound environment), got {:?}",
            global.default_value
        );
    };
    // Review finding on #1774: mirrors the `brink-ir`-level assertion in
    // `lambda_literal_declaration_default.rs` against the actually-compiled
    // `StoryData` — `assemble_program`'s `root_children.extend(prelude
    // .lifted...)` is the one hunk that makes this feature more than a
    // type-check relaxation, so this walks `output.data.containers` (not
    // just the global's own `default_value`) to prove the `FnRef` target
    // resolves to a real, compiled container with `twice`'s one `x` param.
    let lifted = output
        .data
        .containers
        .iter()
        .find(|c| c.id == target)
        .unwrap_or_else(|| {
            panic!(
                "no compiled container has id {target:?} — the FnRef target \
                 does not resolve to a real container in StoryData"
            )
        });
    assert_eq!(
        lifted.param_count, 1,
        "expected `twice`'s one `x` param, got param_count {}",
        lifted.param_count
    );
    assert_eq!(
        lifted.params.len(),
        1,
        "expected `twice`'s one `x` ParamMeta entry, got {} entries",
        lifted.params.len()
    );
    assert_eq!(
        output.data.name_table[lifted.params[0].name.0 as usize], "x",
        "expected the lifted container's param to be named `x`"
    );
}

/// The `var` half of the same ruling.
#[test]
fn compile_path_native_var_lambda_literal_decl_default_compiles() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-lambda-decl-default-var-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "var addOne = |x| x + 1\n\nflow main() {\n  Hi. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output = result.expect("a file-scope var lambda literal must compile (E083 lifted)");
    let global = output
        .data
        .variables
        .iter()
        .find(|v| output.data.name_table[v.name.0 as usize] == "addOne")
        .expect("global `addOne` must be present in the compiled StoryData");
    assert!(global.mutable, "a `var` global stays mutable");
    assert!(matches!(
        global.default_value,
        brink_format::Value::FnRef(_)
    ));
}

/// **Issue #2083, RESOLVED.** The issue's own report speculated the gap was
/// in `brink-db`'s FG-3 incremental `resolve_query`/`resolutions_index_query`
/// machinery, and pointed at this crate's sibling
/// `lambda_literal_decl_default_reads_other_globals_without_capturing_them`
/// (`brink-ir`) as proof the identical shape "compiles and resolves cleanly"
/// through the simpler whole-project `brink_analyzer::analyze` +
/// `lower_to_program_with_type_mode` path. Re-investigation (RCA) found that
/// claim does not hold: that sibling test never asserts on
/// `brink_analyzer::analyze`'s own resolution diagnostics at all — it only
/// checks the shape of the *declaring* global's lowered default value
/// (`ConstValue::FnRef`), never whether the flow body's *call site* actually
/// resolved. A direct, `brink-db`-free call to `brink_analyzer::resolve`/
/// `analyze()` on the identical source reproduces the same `E025` — proving
/// the bug was never in `brink-db`'s incremental layer at all, but in
/// `brink-analyzer::resolve::resolve_function` itself: its call-site
/// "try variables" lookup searched only `SymbolKind::Variable`, never
/// `SymbolKind::Constant` — so a `var`-bound fn value's call site always
/// resolved (confirmed: `var twice = double` + `{twice(21)}` was already
/// clean before this fix) while the identically-shaped `const` form never
/// could. `resolve_variable`'s own bare-*read* lookup (`{twice}`, no call)
/// already searched `[Variable, Constant]` together — this was a one-sided
/// omission in the call-site arm alone. Fixed by adding `SymbolKind::Constant`
/// to that lookup's kind list, at the `brink-analyzer` layer (not `brink-db`
/// — the bug never depended on the db's incremental machinery, so both the
/// db-direct and whole-project roads share this one fix by construction).
#[test]
fn compile_path_native_lambda_valued_global_call_site_resolves() {
    let output = compile_and_run_native(
        "lambda-decl-default-call-site",
        "const twice = |x| x * 2\n\nflow main() {\n  Result: {twice(21)} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 42"),
        "calling a fn-valued CONST global from flow main should work now that \
         issue #2083 is fixed, got: {output:?}"
    );
}

/// The bare-name sibling of the test above (#1862's shipped feature, no
/// lambda literal involved) — issue #2083's own repro used this exact shape.
/// Pinned separately since the bare-name and lambda-literal forms lower
/// through different HIR/LIR construction paths even though both share the
/// one resolver fix.
#[test]
fn compile_path_native_bare_name_fn_valued_const_global_call_site_resolves() {
    let output = compile_and_run_native(
        "bare-name-const-call-site",
        "fn double(n: int): int {\n  return n * 2;\n}\n\nconst twice = double\n\n\
         flow main() {\n  Result: {twice(21)} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 42"),
        "calling a bare-name fn-valued CONST global from flow main should \
         work now that issue #2083 is fixed, got: {output:?}"
    );
}

/// The `var` sibling of the test above: `var twice = double` + `{twice(21)}`
/// already resolved before #2083's fix (the call-site arm searched
/// `SymbolKind::Variable`) — pinned end-to-end here so that "var already
/// worked" stays a tested claim rather than a remembered one.
#[test]
fn compile_path_native_bare_name_fn_valued_var_global_call_site_resolves() {
    let output = compile_and_run_native(
        "bare-name-var-call-site",
        "fn double(n: int): int {\n  return n * 2;\n}\n\nvar twice = double\n\n\
         flow main() {\n  Result: {twice(21)} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 42"),
        "calling a bare-name fn-valued VAR global from flow main should \
         keep working, got: {output:?}"
    );
}

/// Call-vs-read parity (issue #2083's review follow-up, fixed by the
/// locals-first reorder in `brink-analyzer::resolve::resolve_function`):
/// with BOTH a fn-valued global `const twice` and a same-named local
/// `let twice` in scope, the call site must invoke the LOCAL — exactly as a
/// bare read of the name resolves the local (`lookup_variable` step 1).
/// The runtime half already behaved (LIR `lower_call` consults `temp_slot`
/// first), so this end-to-end run pins the aligned end state; the analyzer
/// half of the divergence (resolution target + `infer_call` signature) is
/// pinned red/green by `crates/internal/brink-analyzer/tests/
/// issue_2083_call_site_local_shadows_global.rs`.
#[test]
fn compile_path_native_call_site_local_shadows_same_named_const_global() {
    let output = compile_and_run_native(
        "call-site-local-shadows-const",
        "fn double(n: int): int {\n  return n * 2;\n}\n\n\
         fn triple(n: int): int {\n  return n * 3;\n}\n\n\
         const twice = double\n\n\
         flow main() {\n  ~ let twice = triple\n  Result: {twice(21)} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 63"),
        "the local `let twice = triple` must shadow the global \
         `const twice = double` at the call site (63, not 42), got: {output:?}"
    );
}

/// The `var` sibling of the shadowing test above — the same call-site
/// inversion existed for `Variable`-kind globals, deliberately also fixed
/// by the locals-first reorder.
#[test]
fn compile_path_native_call_site_local_shadows_same_named_var_global() {
    let output = compile_and_run_native(
        "call-site-local-shadows-var",
        "fn double(n: int): int {\n  return n * 2;\n}\n\n\
         fn triple(n: int): int {\n  return n * 3;\n}\n\n\
         var twice = double\n\n\
         flow main() {\n  ~ let twice = triple\n  Result: {twice(21)} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 63"),
        "the local `let twice = triple` must shadow the global \
         `var twice = double` at the call site (63, not 42), got: {output:?}"
    );
}

/// Review finding on #1774: the PR body and the comment posted on issue
/// #1774 both claimed this test existed (`compile_path_native_const_lambda_
/// decl_default_self_recursion_works`, "#[ignore]d with a doc explaining the
/// separate, pre-existing gap they hit") — it did not; only the call-site
/// test above was ever added. This is that missing test, added rather than
/// just correcting the claim, since the gap it documents is real and was
/// already verified by hand: a global `const`-bound lambda referencing its
/// own name recursively (`fact` calling `fact` inside its own body) does
/// **not** yet work — `brink-analyzer` reports `E025` ("unresolved variable
/// reference") at *both* occurrences of the recursive call (the const's own
/// name, mid-initializer, is not visible to its own body's resolution — a
/// single-pass ordering nuance). Orthogonal to both this issue's `E083` gate
/// and #2083's incremental-resolution gap (that one is about calling a
/// fn-valued global from *outside* its own declaration; this one is about a
/// fn-valued global calling *itself*, *inside* its own declaration) —
/// narrower than and adjacent to #2083's territory rather than a clean
/// independent bug, so not filed separately (see `docs/t1c-spec.md` §2b).
#[test]
#[ignore = "pre-existing resolver limitation: a global const-bound lambda cannot reference its own name recursively (E025) — not introduced or fixed by #1774, narrower than and adjacent to #2083, not filed separately"]
fn compile_path_native_const_lambda_decl_default_self_recursion_works() {
    let output = compile_and_run_native(
        "lambda-decl-default-self-recursion",
        "const fact = |n| {\n  if n <= 1 { return 1; }\n  return n * fact(n - 1);\n}\n\n\
         flow main() {\n  Result: {fact(5)} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 120"),
        "a global const-bound lambda should be able to call itself \
         recursively once the resolver limitation is fixed, got: {output:?}"
    );
}

/// Review finding on #1764, UPDATED by #1774 (RULED 2026-08-01): a
/// lambda-valued `VAR`/`CONST` default used to be a hard compile error
/// (`E083`) independently of #1764's seven analyzer-pass fixes — this test
/// originally pinned that "the day a lambda default legally folds is the
/// day this test goes red", predicting exactly the day #1774 landed. It is
/// updated here rather than left to bit-rot into a false assertion: the
/// `VAR` now compiles cleanly (E083 lifted), and the inner `E106` warning
/// (a bad map-literal key inside the lambda's own body) still fires
/// alongside — proving #1764's per-pass fixes (analyzing a lambda's body
/// the same way any other body is analyzed) were never dead code, they were
/// just one layer ahead of a program that could reach them from a decl
/// default. This is a concrete "yes" to the issue's "does #1764 become
/// expressible" question, for the map-key-warning pass specifically.
#[test]
fn compile_path_native_lambda_valued_var_default_compiles_with_map_keys_warning_alongside() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-lambda-var-default-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "var f = ||: int {\n  let m = Map { 3.5: 1 };\n  0\n}\n\n\
         flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output = result.expect(
        "a lambda-valued VAR default now compiles (E083 lifted, RULED 2026-08-01, issue #1774)",
    );
    let codes: Vec<&str> = output.warnings.iter().map(|d| d.code.as_str()).collect();
    assert!(
        codes.contains(&"E106"),
        "expected E106 (bad map key inside the lambda's own body) to still fire \
         as a warning now that the outer VAR compiles, got: {codes:?}"
    );
}

/// Issue #2096 (superseding this test's own former pin of a defensive
/// `E144`): `brink_analyzer::ufcs::resolve` used to drive its
/// `UfcsVisitor` with plain `visit::visit`, which never reaches a `VAR`/
/// `CONST` initializer — so a UFCS-shaped call written directly inside a
/// decl-default lambda's own body was never visited by the pass at all, and
/// fell through to LIR lowering's own defensive `E144` refusal (the
/// `push_ufcs_lowering_refusal` fallback — a caller-never-ran-analysis
/// guard, not the real answer). `ufcs::resolve` now drives the same visitor
/// with `visit::visit_with_decl_initializers`, so this call site is
/// visited like any other.
///
/// **This exact fixture's receiver (`g`, no type annotation) still does not
/// compile** — but for the *real*, D3-ruled reason (`ufcs.rs`'s own module
/// doc): with no annotation and nothing else constraining `g`'s type, the
/// receiver's type genuinely is not known at the resolution point, and D3
/// says that demands an annotation (`E142`) rather than a guess between
/// field-access and free-function. The important thing this test now
/// guards: the call is genuinely *analyzed* (the diagnostic names the real
/// cause, "annotate the receiver," not a structural "never visited"
/// refusal) — see
/// `compile_path_native_ufcs_call_in_lambda_decl_default_resolves_and_runs`
/// below for the positive twin, where annotating the receiver lets the same
/// shape resolve and run end-to-end.
#[test]
fn compile_path_native_ufcs_call_in_lambda_decl_default_is_e142_unannotated_receiver() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-ufcs-lambda-decl-default-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "struct Guest {\n  name: string\n}\n\n\
         fn greet(g, loudness) {\n  return loudness;\n}\n\n\
         const callGreet = |g| g.greet(3)\n\n\
         flow main() {\n  Hi. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let err = result.expect_err(
        "an unannotated UFCS receiver inside a decl-default lambda body must still \
         refuse to compile (D3: the type is genuinely undecidable here) — but now with \
         the real diagnostic naming that cause, not a structural never-visited refusal",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E142"),
        "expected E142 (D3: annotate the receiver) among diagnostics, got: {codes:?}"
    );
    assert!(
        !codes.contains(&"E144"),
        "must not fall through to the old defensive never-visited refusal any more, \
         got: {codes:?}"
    );
}

/// The positive twin of the test above (issue #2096's own "option 1: the
/// call resolves instead of hard-erroring" ask, proven by actually running
/// the story — not just by inspecting the verdict table). Annotating the
/// lambda param's own type (`|g: Guest|`, unlike `greet`'s own untyped
/// params — this pass only needs the *receiver's* type, per D3) gives
/// `ufcs::resolve` everything it needs: `Guest` declares no `greet` field
/// (D1 loses), so it falls to D4 — `greet` is a free function in ordinary
/// lexical scope, resolved and desugared to `greet(g, 3)`.
///
/// Composition with issue #2083 (fn-valued const call sites resolve;
/// locals-first at call sites, landed just before this issue was picked
/// up): `callGreet` is itself a fn-valued `CONST` called from `flow main`
/// exactly the way `compile_path_native_lambda_valued_global_call_site_resolves`
/// (above) already pins for a plain (non-UFCS) lambda body — this test is
/// that same call shape, with a UFCS-shaped call now inside the lambda body
/// too, proving the two fixes compose rather than only working in
/// isolation.
#[test]
fn compile_path_native_ufcs_call_in_lambda_decl_default_resolves_and_runs() {
    let output = compile_and_run_native(
        "ufcs-lambda-decl-default-resolves",
        "struct Guest {\n  hp: int\n}\n\n\
         fn greet(g, loudness) {\n  return loudness;\n}\n\n\
         const callGreet = |g: Guest| g.greet(3)\n\n\
         flow main() {\n  Result: {callGreet(Guest { hp: 1 })} -> END\n}\n",
    );
    assert!(
        output.contains("Result: 3"),
        "the UFCS call inside the decl-default lambda body must actually run and \
         produce `greet`'s own return value (loudness=3), not just compile, got: {output:?}"
    );
}

/// Compile a native `.brink` entry from disk with `Dialect::Brink` explicitly
/// requested — mirrors `seq_verbs.rs`'s own `compile_native` helper.
/// `comparator_contract`'s E119 gate is `dialect == Brink`-only, with no
/// `is_native` fallback the way `map_keys`'s gate has (`lib.rs`: `if
/// opts.dialect == Dialect::Brink && needs_effects`), so it must be
/// requested explicitly even though the source is already native-surface —
/// the same "brink-dialect analysis over native-surface source" combination
/// issue #1887 is about.
fn compile_native_brink_dialect(
    dir_suffix: &str,
    source: &str,
) -> Result<brink_compiler::CompileOutput, brink_compiler::CompileError> {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-comparator-contract-{dir_suffix}-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("main.brink"), source).unwrap();
    let options = brink_compiler::AnalysisOptions {
        dialect: brink_compiler::Dialect::Brink,
        ..brink_compiler::AnalysisOptions::default()
    };
    let result = brink_compiler::compile_path_with_options(&dir.join("main.brink"), options);
    std::fs::remove_dir_all(&dir).ok();
    result
}

/// Issue #2085 (the `comparator_contract.rs` half of #1774's
/// re-verification remainder): `comparator_contract::collect_sites` used to
/// start only from `root_content` + knot/stitch bodies — the same
/// unvisited-decl-initializer gap `ufcs.rs` has (see
/// `compile_path_native_ufcs_call_in_lambda_decl_default_is_e144` above),
/// confirmed live here rather than assumed. `spy` writes the global `seen`,
/// so a pure-callback quartet call (`map`) naming it as a decl-default
/// lambda's own callback must still be refused by E119 — not silently
/// pass because the analyzer never visited the initializer at all.
///
/// **Reproduced first (rule 20a):** with `collect_sites`'s two new
/// `hir.variables`/`hir.constants` loops removed, this compiled clean with
/// zero warnings/errors — confirmed both via a direct `brink-analyzer`-level
/// repro before writing the fix, and by reverting the production hunk and
/// re-running this exact test (red without the fix, green with it).
#[test]
fn compile_path_native_comparator_contract_call_in_lambda_decl_default_is_e119() {
    let source = "var seen = 0\n\n\
         fn spy(n) {\n  seen = seen + n;\n  return n;\n}\n\n\
         const doIt = || map([1, 2], spy)\n\n\
         flow main() {\n  Hi. -> END\n}\n";

    let err = compile_native_brink_dialect("lambda-decl-default", source).expect_err(
        "an impure named callback of a pure-callback verb, called inside a decl-default \
         lambda's own body, must be refused by E119 — not compile clean because the \
         analyzer never visited the initializer",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E119"),
        "expected E119 among diagnostics, got: {codes:?}"
    );
}

/// The companion positive twin: a *pure* named callback inside a
/// decl-default lambda body must still compile clean — the fix must not
/// over-trigger on every callback reachable from an initializer, only on
/// ones whose row provably exceeds pure·silent (mirrors
/// `native_bare_name_pure_callback_passes` in `seq_verbs.rs`, this time
/// reached from `collect_sites`'s new initializer loops rather than a
/// flow body).
#[test]
fn compile_path_native_comparator_contract_pure_call_in_lambda_decl_default_compiles() {
    let source = "fn double(n) {\n  return n * 2;\n}\n\n\
         const doIt = || map([1, 2], double)\n\n\
         flow main() {\n  Hi. -> END\n}\n";

    compile_native_brink_dialect("lambda-decl-default-pure", source).expect(
        "a pure named callback inside a decl-default lambda body must compile clean \
         (E119 is exceedance-only, not a blanket refusal of the new initializer reach)",
    );
}

/// Issue #1769 (`comparator_contract::collect_sites` never walked file-level
/// `VAR`/`CONST` initializers at all — independent of lambdas): the SAME
/// `collect_sites` fix that closes #2085's lambda-body gap closes this one
/// too, since both are the identical missing walk. A direct (non-lambda)
/// `sort_by` misuse written straight in a `VAR` initializer must be refused
/// by E119.
#[test]
fn compile_path_native_comparator_contract_call_directly_in_var_initializer_is_e119() {
    let source = "var seen = 0\n\n\
         fn spy(x, y) {\n  seen = seen + 1;\n  return x - y;\n}\n\n\
         var sorted = sort_by([2, 1], spy)\n\n\
         flow main() {\n  Hi. -> END\n}\n";

    let err = compile_native_brink_dialect("var-initializer-direct", source).expect_err(
        "an impure named comparator called directly in a VAR initializer (no lambda \
         involved) must be refused by E119 — issue #1769's own gap",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E119"),
        "expected E119 among diagnostics, got: {codes:?}"
    );
}

// ── Issue #2085, item 1: `compile_path`-level coverage for the four
// passes #1764/#2084 spot-checked as "already hand-recurses over
// `hir.variables`/`hir.constants`, should already be structurally
// reachable, but has no dedicated regression test yet" — `contains_domain`,
// `conversions`, `range_refinement`, `structs` (`map_keys` already has its
// analog: `compile_path_native_lambda_valued_var_default_compiles_with_
// map_keys_warning_alongside` above). No production fix accompanies these
// three (`contains_domain`/`conversions`/`structs`) — they confirm existing
// behavior, mirroring the map_keys test's own shape.

/// `contains_domain`'s E152 (a float needle against an int-keyed map,
/// provably always false) fires from inside a decl-default lambda's own
/// body — its initializer hand-recursion (`for var in &hir.variables` /
/// `for c in &hir.constants` in `contains_domain::check`) already reaches
/// `Expr::Lambda`'s body via `check_expr`'s own lambda-descent arm (the
/// #1764 unit test `an_always_false_contains_in_a_lambda_statement_of_a_
/// var_initializer_is_e152` proves this at the analyzer layer; this pins
/// it through the production `compile_path` pipeline instead).
#[test]
fn compile_path_native_contains_domain_call_in_lambda_decl_default_is_e152() {
    let source = "const doIt = || {\n  let hit = contains(Map { 1: \"a\" }, 3.5);\n  0\n}\n\n\
         flow main() {\n  Hi. -> END\n}\n";

    let result = compile_native_brink_dialect("contains-domain-lambda-decl-default", source);
    let out = result.expect(
        "a decl-default lambda body's contains() misuse compiles clean (E152 is a warning), \
         with E152 firing alongside it",
    );
    let codes: Vec<&str> = out.warnings.iter().map(|d| d.code.as_str()).collect();
    assert!(
        codes.contains(&"E152"),
        "expected E152 among warnings, got: {codes:?}"
    );
}

/// `conversions`'s E078 (`int()` rejecting a map argument) fires from
/// inside a decl-default lambda's own body — mirrors the #1764 unit test
/// `a_bad_conversion_in_a_lambda_statement_of_a_var_initializer_is_e078`,
/// this time through `compile_path`.
#[test]
fn compile_path_native_conversions_call_in_lambda_decl_default_is_e078() {
    let source = "const doIt = || {\n  let x = int(Map { 1: 2 });\n  0\n}\n\n\
         flow main() {\n  Hi. -> END\n}\n";

    let err = compile_native_brink_dialect("conversions-lambda-decl-default", source).expect_err(
        "a bad int() conversion inside a decl-default lambda body must be refused by E078",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E078"),
        "expected E078 among diagnostics, got: {codes:?}"
    );
}

/// `structs`'s E071 (a struct-literal field disagreeing with its declared
/// type) fires from inside a decl-default lambda's own body — `structs::
/// check`'s own initializer loop (`for var in &hir.variables` / `for c in
/// &hir.constants`, calling `check_expr` — which, like its five siblings,
/// already descends `Expr::Lambda`) reaches it structurally; this pins
/// that reach through `compile_path`.
#[test]
fn compile_path_native_structs_literal_in_lambda_decl_default_is_e071() {
    let source = "struct Point {\n  x: float\n}\n\n\
         const doIt = || Point { x: \"hi\" }\n\n\
         flow main() {\n  Hi. -> END\n}\n";

    let err = compile_native_brink_dialect("structs-lambda-decl-default", source).expect_err(
        "a struct literal with a field type mismatch inside a decl-default lambda body \
         must be refused by E071",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E071"),
        "expected E071 among diagnostics, got: {codes:?}"
    );
}

/// `range_refinement` (NS-A5, E117) is one of #1774's own-documented
/// "currently-documented-vacuous" checks with respect to a decl-default
/// LAMBDA specifically — not because its own initializer hand-recursion is
/// broken, but because of surface disjointness: a range literal (`a..b`)
/// parses only on the ink/brink dialect surface (`brink-syntax`), and a
/// lambda literal (`|x| …`) parses only on the native surface
/// (`brink-syntax-native`, `hir::lower_native`) — confirmed directly: a
/// bare `int(0..0)` inside a native `.brink` decl-default lambda body fails
/// to *parse* at all (`E037`/`E129`, not E117), because native has no `..`
/// range-literal grammar. The two surfaces are mutually exclusive, so no
/// fixture can ever put a range literal inside a lambda body — this is the
/// same finding `comparator_contract.rs`'s own module comment records for
/// `Expr::FnLiteral`/`Expr::Lambda`.
///
/// The honest equivalent this test pins instead: `range_refinement`'s own
/// initializer hand-recursion (`for c in &hir.constants` /
/// `for var in &hir.variables`, twice over in `range_refinement::check`)
/// reaches a **plain, non-lambda** top-level `VAR` initializer on the one
/// surface ranges actually exist on (ink/brink dialect) — through
/// `compile_path`'s in-memory sibling `compile_with_options`, since
/// `range_refinement` has no native-surface reach to give `compile_path`
/// (the on-disk native entry point) anything to exercise here.
#[test]
fn compile_ink_brink_range_refinement_direct_var_initializer_is_e117() {
    // The empty range literal must sit in the `VAR`'s own initializer
    // expression — `range_refinement::check`'s `visit::visit(hir, &mut v)`
    // call already walks an ordinary `~ bad = int(0..0)` assignment inside
    // a flow body (that's the block-tree, not an initializer), so a
    // fixture that put the call there instead would pass with the
    // initializer hand-recursion loops deleted, proving nothing about them.
    let files: std::collections::HashMap<&str, &str> =
        std::collections::HashMap::from([("main.ink", "VAR bad = int(0..0)\n-> END\n")]);
    let options = brink_compiler::AnalysisOptions {
        dialect: brink_compiler::Dialect::Brink,
        ..brink_compiler::AnalysisOptions::default()
    };
    let result = brink_compiler::compile_with_options(
        "main.ink",
        |p| {
            files.get(p).map(|s| (*s).to_string()).ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::NotFound, format!("not found: {p}"))
            })
        },
        options,
    );
    let err = result.expect_err(
        "a provably-empty range literal in a plain VAR initializer must be refused by E117",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E117"),
        "expected E117 among diagnostics, got: {codes:?}"
    );
}

/// A `target/` subdirectory sitting next to a valid `.brink` entry, holding
/// a file that is not valid brink source at all: native discovery must
/// never walk into `target/` in the first place (issue #1381), so the
/// unparseable file is never enumerated and never kills an otherwise-valid
/// compile. Fails on `main` (before the `target/`/`.git/`/`node_modules/`
/// pruning landed) and passes on this branch.
#[test]
fn compile_path_native_ignores_unparseable_file_under_target() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-target-junk-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("target")).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();
    std::fs::write(dir.join("target/junk.brink"), "{{{ not brink source at all").unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output = result.expect(
        "an unparseable .brink file under target/ must not be discovered, so the entry still compiles",
    );
    assert!(
        !output.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

/// A `.brink` entry under a directory whose ancestor has a `brink.toml`:
/// the source root walks up to it (not the entry's own directory), and
/// discovery must still find + read the entry correctly through that root.
#[test]
fn compile_path_native_walks_up_to_brink_toml() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-walkup-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("story")).unwrap();
    std::fs::write(dir.join("brink.toml"), "[project]\ndialect = \"brink\"\n").unwrap();
    std::fs::write(
        dir.join("story/main.brink"),
        "flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path(&dir.join("story/main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let output =
        result.expect("native project with an ancestor brink.toml should compile via walk-up");
    assert!(
        !output.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

// ── B0.9 native strict-only enforcement (issue #1342) ────────────────
//
// Native is strict-only by design (decision-log 2026-07-19 "Typing posture
// ruled"): a `.brink` compile with an explicit `types = gradual` knob is a
// hard error (`E137`), never silently accepted. A bare `.brink` compile
// with no explicit `types` (the two tests above, `AnalysisOptions::default()`)
// is unaffected — the gate only fires on an explicit `gradual` choice, see
// `brink_analyzer::native_strict_only_error`'s doc.

/// `types = gradual` explicitly requested for a native entry is refused
/// with `E137`, not silently compiled.
#[test]
fn compile_path_native_with_explicit_gradual_types_is_e137() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-gradual-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();

    let options = brink_compiler::AnalysisOptions {
        types: Some(brink_compiler::TypePolicy::Gradual),
        ..Default::default()
    };
    let result = brink_compiler::compile_path_with_options(&dir.join("main.brink"), options);
    std::fs::remove_dir_all(&dir).ok();

    let err = result.expect_err("a gradual-knob .brink compile must be a hard error");
    assert!(
        matches!(err, brink_compiler::CompileError::Diagnostics(_)),
        "expected a Diagnostics(E137) compile error, got: {err}"
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E137"),
        "expected E137 (native strict-only) among diagnostics, got: {codes:?}"
    );
}

/// `types = strict` explicitly requested for a native entry compiles
/// cleanly — the paired positive case for the gate above.
///
/// No `dialect` setting at all (issue #1348): `dialect` is an ink-only axis
/// (docs/t1b-surface-spec.md §1), orthogonal to native's `Language`
/// classification, so a native compile must never need one — the ink-only
/// `E064` config error (`types = strict` + `dialect != brink`) must not fire
/// against a `.brink` entry even at `dialect`'s `StrictInk` default.
#[test]
fn compile_path_native_with_explicit_strict_types_compiles() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-strict-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "flow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();

    let options = brink_compiler::AnalysisOptions {
        types: Some(brink_compiler::TypePolicy::Strict),
        ..Default::default()
    };
    let result = brink_compiler::compile_path_with_options(&dir.join("main.brink"), options);
    std::fs::remove_dir_all(&dir).ok();

    // `E064` is a hard error (`DiagnosticCode::severity`) — if the ink-only
    // dialect gate had fired, this `expect` would panic showing it, exactly
    // the regression `compile_path_native_with_explicit_gradual_types_is_e137`
    // above proves the *sibling* `E137` gate the same way.
    let output = result.expect("types = strict native compile should succeed with no dialect set");
    assert!(
        !output.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

/// The T1b dialect gate itself (`dialect_gate::check`, `E051`) must not fire
/// against native source either (issue #1348) — not just its `E064` config
/// error. `STRUCT` declarations are ordinary native syntax (native's own
/// `struct` keyword lowers to the same `HirFile::structs` the gate walks —
/// `docs/t1b-surface-spec.md` §1 flags a `STRUCT` decl as brink-extension
/// syntax under ink's `StrictInk` default), so a native file declaring one
/// must compile cleanly under fully-default `AnalysisOptions` — no `dialect`,
/// no `types` — exactly the posture a bare `.brink` compile with no
/// `brink.toml` has today.
#[test]
fn compile_path_native_struct_decl_under_default_options_has_no_dialect_gate_e051() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-struct-dialect-gate-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "struct Item {\n  name: string,\n  weight: int\n}\n\nflow main() {\n  Hello. -> END\n}\n",
    )
    .unwrap();

    let result = brink_compiler::compile_path_with_options(
        &dir.join("main.brink"),
        brink_compiler::AnalysisOptions::default(),
    );
    std::fs::remove_dir_all(&dir).ok();

    let output = result
        .expect("a native STRUCT declaration must never trip the ink-only dialect gate (E051)");
    assert!(
        !output.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

// ── B1 `or`-coalescing (`docs/stdlib-spec.md` §1.6a, issue #1460),
// short-circuited per issue #1471's ruling ───────────────────────────
//
// Full pipeline: native lexer (`KW_OR`) → native parser (`Prec::Coalesce`)
// → native HIR lowering (`InfixOp::Coalesce`) → analyzer typing
// (`infer::ty::coalesce`, recorded per step by `brink_analyzer::
// coalesce_types` and threaded to lowering by `brink-db`'s
// `coalesce_types_query`) → LIR (`lir::ExprKind::Coalesce`, a real branch) →
// codegen (`Opcode::CoalesceSome`) → runtime VM
// (`value_ops::coalesce_unwrap_some`) → `Story` output. Compiles and *runs*
// the program (not just a diagnostics-clean compile) so the opcode is
// proven reachable end to end, not merely wired at the type level.

/// Compile a native `.brink` entry from disk and run it to completion,
/// returning the concatenated output text. Mirrors `compile_and_run`
/// above, but for a native (not `.ink`) entry — `compile_and_run` is
/// `.ink`-only (`compile_mem` hardcodes the `.ink` extension), so this is
/// its own small helper rather than a parameterization of that one.
fn compile_and_run_native(dir_suffix: &str, source: &str) -> String {
    try_compile_and_run_native(dir_suffix, source)
        .unwrap_or_else(|err| panic!("fixture must run cleanly, got a runtime fault: {err:?}"))
}

/// [`compile_and_run_native`] without the "must run cleanly" assumption —
/// the fixture still has to *compile* cleanly, but a turn-terminating
/// runtime fault is handed back instead of panicking, so a test can assert
/// on one (the `CoalesceShape::RuntimeCheck` posture).
fn try_compile_and_run_native(
    dir_suffix: &str,
    source: &str,
) -> Result<String, brink_runtime::RuntimeError> {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-b1-{dir_suffix}-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("main.brink"), source).unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();
    // B1 coalescing fixture must compile cleanly.
    let data = result.unwrap().data;

    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let lines = story.continue_maximally()?;
    let mut output = String::new();
    for line in &lines {
        output.push_str(line.text());
    }
    Ok(output)
}

/// The collapse form (`Option[T] or T -> T`): `some(v)` unwraps to `v`,
/// `none` falls through to the (already-`T`-typed) fallback unchanged.
#[test]
fn native_or_coalescing_collapse_form_unwraps_some_and_falls_back_on_none() {
    let output = compile_and_run_native(
        "collapse",
        "flow main() {\n  Some case: {some(5) or 99}\n  None case: {none or 99} -> END\n}\n",
    );
    assert!(
        output.contains("Some case: 5"),
        "expected the unwrapped `some(5)`, got: {output:?}"
    );
    assert!(
        output.contains("None case: 99"),
        "expected the `none` fallback, got: {output:?}"
    );
}

/// The two-Option form chained (`a or b or default`): `none or none` keeps
/// optionality (stays `none`), so the chain falls all the way through to
/// the final non-Option fallback. A **smoke test only** — review finding on
/// PR #1469/#1460: coalescing is semantically associative (`unify` is
/// commutative/associative on agreeing types), so `{none or none or 7}`
/// prints `7` under *either* grouping — this test cannot detect an
/// associativity regression (e.g. right-associative parsing) on its own.
/// `brink-syntax-native`'s own
/// `parser::tests::expression::prec_coalesce_chain_is_left_associative`
/// proves left-associativity at the parse-tree level, where a wrong
/// grouping is actually observable.
#[test]
fn native_or_coalescing_chain_falls_through_to_final_fallback() {
    let output = compile_and_run_native(
        "chain",
        "flow main() {\n  Chained: {none or none or 7} -> END\n}\n",
    );
    assert!(
        output.contains("Chained: 7"),
        "expected the chain to fall through both `none`s to the final fallback, got: {output:?}"
    );
}

/// Coalescing **short-circuits**: `rhs` is never evaluated when `lhs` is
/// `some` — RULED, issue #1471, flipping the eager pin PR #1469/#1460
/// landed and flagged as unruled (see `brink_ir::InfixOp::Coalesce`/
/// `brink_format::Opcode::CoalesceSome`'s own docs), matching the
/// short-circuiting `??`/`?:` conventions this operator's precedence
/// placement was modeled on. `bump()` mutates the global `counter` and is
/// only ever reached through the coalescing `rhs` — if evaluation were
/// still eager, `bump()` would run regardless of `lhs` and `counter` would
/// end up `1`; short-circuiting means a `some(_)` `lhs` skips `bump()`
/// entirely, so `counter` stays `0`.
const OR_COALESCING_SHORT_CIRCUIT_SRC: &str = "var counter = 0\n\
     fn bump() {\n  counter = counter + 1;\n  return 99;\n}\n\
     flow main() {\n  Value: {some(5) or bump()}\n  Counter: {counter} -> END\n}\n";

#[test]
fn native_or_coalescing_short_circuits_rhs_on_some_lhs() {
    let output = compile_and_run_native("shortcircuit", OR_COALESCING_SHORT_CIRCUIT_SRC);
    assert!(
        output.contains("Value: 5"),
        "the collapse form must still unwrap `some(5)`, got: {output:?}"
    );
    assert!(
        output.contains("Counter: 0"),
        "expected `bump()` to never run since `lhs` is `some(_)` \
         (short-circuit), got: {output:?}"
    );
}

/// The other half of the short-circuit proof: `rhs` must still run —
/// exactly once — when `lhs` actually is `none`. Short-circuiting only
/// means the evaluation is *conditional*, not that `rhs` is permanently
/// dead code.
#[test]
fn native_or_coalescing_still_evaluates_rhs_when_lhs_is_none() {
    let output = compile_and_run_native(
        "shortcircuit-none",
        "var counter = 0\n\
         fn bump() {\n  counter = counter + 1;\n  return 99;\n}\n\
         flow main() {\n  Value: {none or bump()}\n  Counter: {counter} -> END\n}\n",
    );
    assert!(
        output.contains("Value: 99"),
        "the `none` lhs must fall through to `bump()`'s return value, got: {output:?}"
    );
    assert!(
        output.contains("Counter: 1"),
        "expected `bump()` to have run exactly once for a `none` lhs, got: {output:?}"
    );
}

/// A leading `some(_)` in a coalesce **chain** must still preserve
/// optionality through the intermediate step so the chain can continue —
/// short-circuiting changes *when* `rhs` runs, not the collapse-vs-preserve
/// typing rule (`(Option[T],T)->T` vs `(Option[T],Option[T])->Option[U]`).
/// `some(5) or none` is the inner step (parses left-associatively): a wrong
/// collapse decision there would hand the outer step a plain `Int` where it
/// requires an `Option`, faulting instead of printing `5`.
#[test]
fn native_or_coalescing_chain_preserves_optionality_through_intermediate_some() {
    let output = compile_and_run_native(
        "chain-preserve",
        "flow main() {\n  Chained: {some(5) or none or 99} -> END\n}\n",
    );
    assert!(
        output.contains("Chained: 5"),
        "expected the leading `some(5)` to win, unwrapped only at the final \
         non-Option fallback, got: {output:?}"
    );
}

/// The BLOCKING review finding on PR #1479, now a passing test (issue
/// #1492's ruling, re-driven here): an `Option`-returning **call** as the
/// intermediate fallback. `maybe()` lowers to `lir::ExprKind::Call`, whose
/// `Option`-ness lives in the callee's inferred return type — invisible to
/// any syntactic shape-sniff at lowering time, which is exactly why the
/// deleted `rhs_is_option_shaped` heuristic collapsed the inner step and
/// made the outer `CoalesceSome` fault on a plain `Int`. Lowering now reads
/// the analyzer's recorded `CoalesceShape::PreserveOption` for that step
/// instead, so the leading `some(5)` survives to the end.
///
/// (`brink-analyzer`'s `coalesce_types.rs` pins the *verdict* for this exact
/// chain; this pins the program it actually produces.)
/// Shared with `native_or_coalescing_and_as_binding_strict_findings_match_baseline`
/// below — a single source of truth so a change here cannot silently drift
/// out of sync with what the strict sweep actually compiles.
const OR_COALESCING_CHAIN_WITH_CALL_SRC: &str = "fn maybe() {\n  return none;\n}\n\
     flow main() {\n  Chained: {some(5) or maybe() or 99} -> END\n}\n";

#[test]
fn native_or_coalescing_chain_with_intermediate_call_yields_the_leading_some() {
    let output = compile_and_run_native("chain-call", OR_COALESCING_CHAIN_WITH_CALL_SRC);
    assert!(
        output.contains("Chained: 5"),
        "expected the leading `some(5)` to win through an Option-returning \
         call fallback, got: {output:?}"
    );
}

/// A `VisitCount`/`DivertTarget`/`TURNS_SINCE` reference reachable only
/// through a coalesce operand must still register on the counting walk
/// (`lir::lower::collect_counting_refs_expr`) — a BLOCKING silent-data-drop
/// finding on PR #1479: the new `lir::ExprKind::Coalesce` variant fell into the
/// walker's `_ => {}` catch-all, so the referenced container's
/// `CountingFlags::VISITS` was never set and its visit count read back `0`
/// instead of the true count. No diagnostic, no fault — just a wrong
/// number, which is exactly the class of bug this repo's rules call a bug
/// until proven otherwise.
#[test]
fn native_or_coalescing_rhs_visit_count_reference_is_tracked() {
    let output = compile_and_run_native(
        "visit-count",
        "flow main() {\n  -> other\n}\n\
         flow other() {\n  V: {none or other} -> END\n}\n",
    );
    assert!(
        output.contains("V: 1"),
        "expected `other`'s visit count to be tracked through the coalesce \
         operand, got: {output:?}"
    );
}

/// The `CoalesceShape::RuntimeCheck` posture, still intact (RULED, issue
/// #1492, documented on `brink_format::Opcode::CoalesceSome`): with an
/// unpinned left-hand type — an untyped parameter under the native default
/// `types = gradual` — the analyzer commits to no shape, and **the runtime
/// check is the operator's semantics**. A plain (non-`Option`) value
/// reaching the step is a turn-terminating `TypeError`, not a silent
/// coalesce and not a compile error.
/// Shared with `native_or_coalescing_and_as_binding_strict_findings_match_baseline`
/// below — a single source of truth so a change here cannot silently drift
/// out of sync with what the strict sweep actually compiles.
const OR_COALESCING_UNPINNED_LHS_FAULT_SRC: &str = "fn pick(x) {\n  return x or 99;\n}\n\
     flow main() {\n  Value: {pick(1)} -> END\n}\n";

#[test]
fn native_or_coalescing_unpinned_lhs_faults_on_a_plain_value() {
    let err =
        try_compile_and_run_native("runtime-check-fault", OR_COALESCING_UNPINNED_LHS_FAULT_SRC)
            .expect_err("a plain `Int` left-hand side must fault at runtime");
    assert!(
        matches!(&err, brink_runtime::RuntimeError::TypeError(msg)
            if msg.contains("or-coalescing requires an Option left-hand side")),
        "expected the or-coalescing TypeError, got: {err:?}"
    );
}

/// The other arm of the same unpinned step, so the test above cannot pass
/// by the operator being broken outright: an actual `Option` flowing into
/// an unpinned `lhs` coalesces normally (and still short-circuits — the
/// runtime check gates the *value*, not the branch).
#[test]
fn native_or_coalescing_unpinned_lhs_coalesces_an_option() {
    let output = compile_and_run_native(
        "runtime-check-ok",
        "fn pick(x) {\n  return x or 99;\n}\n\
         flow main() {\n  Some: {pick(some(5))}\n  None: {pick(none)} -> END\n}\n",
    );
    assert!(
        output.contains("Some: 5"),
        "an unpinned `lhs` holding `some(5)` must unwrap, got: {output:?}"
    );
    assert!(
        output.contains("None: 99"),
        "an unpinned `lhs` holding `none` must fall through, got: {output:?}"
    );
}

/// The same call-shaped fallback un-chained, and falling through: a `none`
/// `lhs` hands the whole step over to `maybe()`'s own `Option`, which the
/// trailing plain fallback then collapses.
///
/// This is **fall-through-only** coverage, not a verdict pin: the inner
/// step's `lhs` is the literal `none`, so it always takes the fallback
/// branch, and codegen only emits `MakeSome` on the *unwrap* (`some(v)`)
/// branch (`brink_codegen_inkb::expr`'s `Coalesce` arm) — never on
/// fall-through. That means this fixture prints `Chained: 7` identically
/// whether the inner step's recorded shape is `PreserveOption` or the
/// `RuntimeCheck` default, so it does not pin
/// `brink_ir::lir::CoalesceShape` here. The test above
/// (`native_or_coalescing_chain_with_intermediate_call_yields_the_leading_some`)
/// is the one that actually exercises `MakeSome`, because its `lhs` is a
/// real `some(5)` at runtime and takes the unwrap branch.
#[test]
fn native_or_coalescing_falls_through_to_an_option_returning_call() {
    let output = compile_and_run_native(
        "call-fallthrough",
        "fn maybe() {\n  return some(7);\n}\n\
         flow main() {\n  Chained: {none or maybe() or 99} -> END\n}\n",
    );
    assert!(
        output.contains("Chained: 7"),
        "expected `maybe()`'s `some(7)` to win, unwrapped at the final \
         non-Option fallback, got: {output:?}"
    );
}

// ── B1b the `as` binding (`docs/decision-log.md` 2026-07-26, issue
//    #1475) ────────────────────────────────────────────────────────────
//
// Full pipeline, in both ruled condition positions: native parser
// (`AS_BINDING`) → native HIR lowering (`IfStmt`/`WhileStmt`/
// `CondBranch::binding`) → analyzer typing (`Option[T]` → `T`) → LIR
// (`lir::ExprKind::OptionBind`) → codegen (`Opcode::OptionBind`) → runtime VM
// → `Story` output. Each fixture *runs*, so the opcode is proven reachable
// end to end rather than merely wired at the type level.

/// The statement form: `if EXPR as NAME { … }` binds the unwrapped payload
/// (not the `Option`) inside the success arm, and the `else` arm is
/// reached when the condition is `none`.
#[test]
fn native_as_binding_statement_form_binds_payload_and_falls_to_else() {
    let output = compile_and_run_native(
        "as-if",
        "fn present() {\n  if some(41) as n {\n    return n + 1;\n  }\n  return 0;\n}\n\
         fn absent() {\n  if none as n {\n    return n;\n  }\n  return -7;\n}\n\
         flow main() {\n  Present: {present()}\n  Absent: {absent()} -> END\n}\n",
    );
    assert!(
        output.contains("Present: 42"),
        "expected `n` to be the UNWRAPPED 41 (42 after +1), got: {output:?}"
    );
    assert!(
        output.contains("Absent: -7"),
        "expected the `none` condition to skip the arm entirely, got: {output:?}"
    );
}

/// The `while` form rebinds each iteration (the ruling's explicit rider):
/// `next_ticket()` yields `some(2)`, `some(1)`, `some(0)`, then `none`, so
/// a per-iteration rebinding sums to 3 — a first-iteration snapshot would
/// sum to 6 (2+2+2) and a non-terminating binding would never stop.
const AS_BINDING_WHILE_REBIND_SRC: &str = "var counter = 3\n\
     fn next_ticket() {\n\
     \x20 if counter > 0 {\n\
     \x20   counter = counter - 1;\n\
     \x20   return some(counter);\n\
     \x20 }\n\
     \x20 return none;\n}\n\
     fn drain() {\n\
     \x20 let sum = 0;\n\
     \x20 while next_ticket() as t {\n\
     \x20   sum = sum + t;\n\
     \x20 }\n\
     \x20 return sum;\n}\n\
     flow main() {\n  Sum: {drain()} -> END\n}\n";

#[test]
fn native_as_binding_while_form_rebinds_each_iteration() {
    let output = compile_and_run_native("as-while", AS_BINDING_WHILE_REBIND_SRC);
    assert!(
        output.contains("Sum: 3"),
        "expected 2+1+0 = 3 from per-iteration rebinding, got: {output:?}"
    );
}

/// The template form `{if EXPR as NAME: … else: …}` — the same construct in
/// brink's other condition position, riding the already-ruled `{if}`
/// spelling. The bound name is readable from an interpolation inside the
/// success arm; the `else` arm runs on `none`.
#[test]
fn native_as_binding_template_form_binds_inside_the_success_arm() {
    let output = compile_and_run_native(
        "as-template",
        "flow main() {\n\
         \x20 Leader: {if some(9) as l: number {l} else: nobody}\n\
         \x20 Empty: {if none as l: number {l} else: nobody} -> END\n}\n",
    );
    assert!(
        output.contains("Leader: number 9"),
        "expected the template arm to see the unwrapped 9, got: {output:?}"
    );
    assert!(
        output.contains("Empty: nobody"),
        "expected the `else` arm on `none`, got: {output:?}"
    );
}

/// The binding is scoped **strictly to the success arm** — observable by
/// shadowing: an outer `n` is invisible inside the arm (the binding wins)
/// and intact after it (the binding is gone). A leaked binding would make
/// the function return `1`; a binding that never took effect would print
/// `100` from inside the arm.
#[test]
fn native_as_binding_scope_ends_at_the_arm() {
    let output = compile_and_run_native(
        "as-scope",
        "fn probe() {\n\
         \x20 let n = 100;\n\
         \x20 let inner = 0;\n\
         \x20 if some(1) as n {\n\
         \x20   inner = n;\n\
         \x20 }\n\
         \x20 return inner * 1000 + n;\n}\n\
         flow main() {\n  Probe: {probe()} -> END\n}\n",
    );
    assert!(
        output.contains("Probe: 1100"),
        "expected inner = 1 (the binding) and n = 100 (the outer local, \
         restored after the arm), got: {output:?}"
    );
}

// ── Choice-guard `as` binding (issue #1508, decision log 2026-07-26
//    "Choice-guard `as` un-deferred") ─────────────────────────────────
//
// Full pipeline, riding the *same* `OptionBind` + frame-slot machinery the
// B1b tests above already prove: native parser (`AS_BINDING` inside
// `CHOICE_GUARD`) → native HIR lowering (`hir::Choice::binding`) → LIR
// (`lir::ExprKind::OptionBind`, scoped across condition *and* the choice's own
// body — `lir::lower::mod::lower_choice_with_child`) → codegen
// (`Opcode::OptionBind` inside the guard's condition eval) → runtime VM
// (the write lands in the same frame `BeginChoice`'s `fork_thread`
// snapshots into the pending choice) → `Story::choose` restores that
// frame, so the picked body's `{n}` reads the captured value. No new
// wire-format field exists or is needed: `OptionBind` and the thread-fork
// snapshot both predate this feature (issue #1475) and already generalize
// to a choice guard's binding without modification — verified by tracing
// `vm.rs::handle_begin_choice`/`fork_thread` and `flow_instance.rs::choose`
// end to end while implementing this, not assumed.

/// Compile a native `.brink` entry from disk and link it, without
/// draining any choices — mirrors `try_compile_and_run_native`, but hands
/// back the linked `(Program, line_tables)` so a test can build a `Story`,
/// inspect/select choices, mutate globals between presentation and pick,
/// and — for the snapshot test — reattach a second `Story` to the same
/// `Arc<Program>` after detaching the first.
fn compile_native_linked(
    dir_suffix: &str,
    source: &str,
) -> (
    std::sync::Arc<brink_runtime::Program>,
    Vec<Vec<brink_format::LineEntry>>,
) {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-choice-as-{dir_suffix}-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("main.brink"), source).unwrap();

    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();
    let data = result
        .unwrap_or_else(|err| panic!("choice-guard `as` fixture must compile cleanly: {err:?}"))
        .data;

    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    (std::sync::Arc::new(program), line_tables)
}

/// [`compile_native_linked`] wrapped straight into a fresh `Story`.
fn compile_native_to_story(dir_suffix: &str, source: &str) -> Story<DotNetRng> {
    let (program, line_tables) = compile_native_linked(dir_suffix, source);
    Story::<DotNetRng>::new(program, line_tables)
}

const CHOICE_GUARD_AS_SRC: &str = "var stash: Option<int> = none\n\
     flow main() {\n\
     \x20 ~ stash = some(41)\n\
     \x20 {?\n\
     \x20   * {if stash as n} [pick it] {\n\
     \x20     You have {n}.\n\
     \x20     -> DONE\n\
     \x20   }\n\
     \x20 }\n}\n";

/// The guard's `as` binding both gates the choice (`stash` is `some`, so
/// it's presented) and captures `n = 41` **at presentation time** — a
/// same-name global mutation between the choice appearing and being
/// picked must not leak into the already-captured value. Regression for
/// exactly the misread the maintainer caught in the 2026-07-26 "COW
/// no-aliasing invariant" ruling: reference semantics would show `999`
/// here, not the captured `41`.
#[test]
fn native_choice_guard_as_binds_and_captures_at_presentation() {
    let mut story = compile_native_to_story("guard-capture", CHOICE_GUARD_AS_SRC);
    // Host-facing `variable`/`set_variable` refuse an undeclared-module
    // global by default (M-2b visibility enforcement) — a pre-existing,
    // unrelated posture this test's mutation step needs to see past, the
    // same documented dev-tooling escape hatch `visibility.rs`'s own
    // `dev_override_allows_private_access` test uses. Flagged as scope
    // overflow (issue comment) rather than fixed here: out of #1508's
    // fence.
    story.set_visibility_enforcement(false);

    let lines = story.continue_maximally().expect("continue to the choice");
    let Some(Step::Choices(choices)) = lines.last() else {
        panic!("expected the guard-gated choice to be presented, got: {lines:?}");
    };
    assert_eq!(choices.len(), 1, "expected exactly one choice: {choices:?}");
    assert_eq!(choices[0].text, "pick it");

    // Mutate the source *after* presentation, *before* picking — capture-
    // at-presentation must make this invisible to the picked body.
    let mutated = story.set_variable(
        "stash",
        brink_format::Value::some(brink_format::Value::Int(999)),
    );
    assert!(mutated, "`stash` must be a real declared global");

    story.choose(0).expect("choose the only choice");
    let lines = story.continue_maximally().expect("continue after choosing");
    let output: String = lines.iter().map(Step::text).collect();
    assert!(
        output.contains("You have 41."),
        "expected the captured (pre-mutation) value 41, got: {output:?}"
    );
    assert!(
        !output.contains("999"),
        "the post-presentation mutation to 999 must never reach the picked \
         body — capture-at-presentation, by-value COW: {output:?}"
    );
}

/// The captured value survives a `StorySnapshot` round trip (the in-memory
/// detach/reattach `Story::into_snapshot`/`from_snapshot` uses for locale
/// hot-swapping) — issue #1508's "save round-trip" requirement. This is an
/// ordinary `Clone` under the hood (`FlowInstance`/`Flow`/`PendingChoice`/
/// `Thread` all derive `Clone`, no serde ceremony), the same "just clones"
/// shape `ClosureValue`'s env row already relies on — proving it here
/// pins that no extra wire-level plumbing is needed for the captured
/// value to ride along.
#[test]
fn native_choice_guard_as_captured_value_survives_a_story_snapshot_round_trip() {
    let (program, line_tables) = compile_native_linked("guard-snapshot", CHOICE_GUARD_AS_SRC);
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::clone(&program), line_tables);

    let lines = story.continue_maximally().expect("continue to the choice");
    assert!(
        matches!(lines.last(), Some(Step::Choices(cs)) if cs.len() == 1),
        "expected the guard-gated choice to be presented: {lines:?}"
    );

    // Detach and reattach to the SAME `Arc<Program>` — the snapshot
    // carries the pending choice (and its captured `n = 41`) across, same
    // as a locale hot-swap would.
    let (snapshot, line_tables) = story.into_snapshot();
    let mut story = Story::<DotNetRng>::from_snapshot(program, snapshot, line_tables);

    story.choose(0).expect("choose the only choice");
    let lines = story.continue_maximally().expect("continue after choosing");
    let output: String = lines.iter().map(Step::text).collect();
    assert!(
        output.contains("You have 41."),
        "expected the captured value to survive the snapshot round trip, got: {output:?}"
    );
}

/// A `none` guard hides the choice entirely — the fallback (`else`) is
/// what actually shows, and the bound name is never read (nothing to
/// unwrap).
#[test]
fn native_choice_guard_as_false_condition_hides_the_choice() {
    let source = "flow main() {\n\
         \x20 {?\n\
         \x20   * {if none as n} [pick it] {\n\
         \x20     You have {n}.\n\
         \x20     -> DONE\n\
         \x20   }\n\
         \x20   else {\n\
         \x20     Nothing to grab.\n\
         \x20     -> DONE\n\
         \x20   }\n\
         \x20 }\n}\n";
    let mut story = compile_native_to_story("guard-false", source);
    let lines = story
        .continue_maximally()
        .expect("continue past the hidden choice");
    let output: String = lines.iter().map(Step::text).collect();
    assert!(
        output.contains("Nothing to grab."),
        "expected the fallback to run since the guard is `none`, got: {output:?}"
    );
    assert!(
        !output.contains("pick it") && !output.contains("You have"),
        "the guarded choice must never appear when its condition is `none`, \
         got: {output:?}"
    );
}

/// Review finding (post-#1508 land): `{n}` in the choice's OWN
/// `start_content` (the text before the `[…]` bracket) must resolve
/// through the guard's binding, not just `{n}` inside the braced body.
/// `lower_choice_with_child` used to lower `start_content`/
/// `bracket_content`/`inner_content` *before* `ctx.push_block_scope()`, so
/// the block scope only ever covered the condition + braced body — a
/// `{n}` read here fell through `lower_path`'s `SymbolKind::Temp`
/// fallback (`GetGlobal(DefaultHasher(name))` for a nonexistent global)
/// and faulted with `UnresolvedGlobal` on the very first
/// `continue_maximally()`, before the choice ever presented. Verified to
/// fail this way with the `push_block_scope` reordering reverted.
///
/// This only pins the compile-time resolution the finding's fix
/// addresses (a real temp slot instead of a phantom global — no fault).
/// It deliberately does not assert `{n}`'s displayed *value* here:
/// `brink-codegen-inkb::container::emit_choice`'s pre-existing, choice-
/// generic bytecode order evaluates a choice's display text *before* its
/// condition (`// Push order: display first, condition second` — a
/// choice-guard-unrelated convention this PR's diff never touches), so a
/// guard's `OptionBind` write hasn't happened yet when this particular
/// display string is composed. The captured value reaching the picked
/// body (the feature's actual "capture-at-presentation" contract) is
/// proven by `native_choice_guard_as_binds_and_captures_at_presentation`
/// and the inner-content test below, both of which read `{n}` from
/// contexts that run after the guard condition.
#[test]
fn native_choice_guard_as_start_content_reads_the_binding() {
    let source = "var stash: Option<int> = none\n\
         flow main() {\n\
         \x20 ~ stash = some(41)\n\
         \x20 {?\n\
         \x20   * {if stash as n} You have {n}. [pick it] {\n\
         \x20     -> DONE\n\
         \x20   }\n\
         \x20 }\n}\n";
    let mut story = compile_native_to_story("guard-start-content", source);
    story.set_visibility_enforcement(false);

    let lines = story
        .continue_maximally()
        .expect("start-content `{n}` read must resolve through the guard binding, not fault");
    let Some(Step::Choices(choices)) = lines.last() else {
        panic!("expected the guard-gated choice to be presented, got: {lines:?}");
    };
    assert_eq!(choices.len(), 1, "expected exactly one choice: {choices:?}");
}

/// Same defect, `inner_content` (the text after the `[…]` bracket) instead
/// of `start_content`. This half of the split composes into the *output*
/// content emitted after the choice is picked (`ChoiceOutput`), so —
/// before the fix — presentation succeeded but the fault surfaced on the
/// *next* `continue_maximally()` call, after picking.
#[test]
fn native_choice_guard_as_inner_content_reads_the_binding() {
    let source = "var stash: Option<int> = none\n\
         flow main() {\n\
         \x20 ~ stash = some(41)\n\
         \x20 {?\n\
         \x20   * {if stash as n} [pick it] You have {n}. {\n\
         \x20     -> DONE\n\
         \x20   }\n\
         \x20 }\n}\n";
    let mut story = compile_native_to_story("guard-inner-content", source);
    story.set_visibility_enforcement(false);

    let lines = story.continue_maximally().expect("continue to the choice");
    assert!(
        matches!(lines.last(), Some(Step::Choices(cs)) if cs.len() == 1),
        "expected the guard-gated choice to be presented: {lines:?}"
    );

    story.choose(0).expect("choose the only choice");
    let lines = story.continue_maximally().expect(
        "inner-content `{n}` read must resolve through the guard binding after picking, not fault",
    );
    let output: String = lines.iter().map(Step::text).collect();
    assert!(
        output.contains("You have 41."),
        "expected the choice's own inner-content to read the captured binding, got: {output:?}"
    );
}

/// Review finding (same root cause as the two above): a *second*, sibling
/// choice binding the same name as an earlier choice must not trip a
/// spurious E082 ("block-scoped temp referenced after its block has
/// closed"). `ctx.block_scoped_temp_names` records a binding's name
/// permanently the first time it's declared; with the content lowered
/// before `push_block_scope`, the second choice's own `{n}` read missed
/// its own (freshly reopened) scope and fell through to the same
/// `SymbolKind::Temp` fallback, which then misfired E082 — even though
/// there is no `~ { … }` block anywhere in the source. Fixed by the same
/// reordering: each choice's `push_block_scope`/binding declare now
/// happens before that choice's own content is lowered, so its own `{n}`
/// resolves through its own (current) scope instead of the fallback.
#[test]
fn native_choice_guard_as_two_choices_binding_the_same_name_both_compile_clean() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-choice-as-shared-name-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "var stash: Option<int> = none\n\
         flow main() {\n\
         \x20 ~ stash = some(41)\n\
         \x20 {?\n\
         \x20   * {if stash as n} A [a] {\n\
         \x20     -> DONE\n\
         \x20   }\n\
         \x20   * {if stash as n} B {n} [b] {\n\
         \x20     -> DONE\n\
         \x20   }\n\
         \x20 }\n}\n",
    )
    .unwrap();
    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();
    // E082 is `Severity::Error` (not `Warning`), so the pre-fix misfire
    // surfaces as a hard `CompileError`, not a warning on an `Ok` output —
    // any error here (E082 or otherwise) means this must-compile-clean
    // fixture regressed.
    result.unwrap_or_else(|err| {
        panic!(
            "a second choice binding the same guard name must compile clean — \
             no `~ {{ … }}` block exists in this source, so E082 must never \
             fire: {err:?}"
        )
    });
}

// ── Native bare-name fn values (issue #1862) ────────────────────────
//
// The end-to-end proof that a bare name *is* a fn value lives in the
// `tests/tier1-native/fn-value-bare-name/` golden case. The three tests
// below cover the edges that case cannot express: the ink side of the
// gate, the `ref`-param refusal, and a plain (non-`.brink`) reading of the
// same shape.

/// The gate's ink half: in **ink** a bare function-knot name in expression
/// position is still the knot's **visit count**, not a fn value —
/// `#fn(f)` remains ink's only fn-value spelling. Dropping the
/// `LowerCtx::native` guard in `lir::lower::expr::lower_path` would turn
/// this `0` into a function value and print something else entirely.
#[test]
fn ink_bare_function_name_is_still_a_visit_count() {
    let source = "Count: {f}\n\
                  -> END\n\n\
                  === function f ===\n\
                  ~ return 1\n";
    let output = compile_and_run(source, &[]);
    assert!(
        output.contains("Count: 0"),
        "an ink bare function-knot name must stay a visit count (0, never entered), \
         got: {output:?}"
    );
}

/// A native bare-name reference binds **zero** arguments — the `#fn(f, a)`
/// binding form has no native spelling — so a target with a `ref`
/// parameter can never satisfy "all ref params bind at creation" and is
/// `E080` at the reference site (`fn_values::check_native_bare_refs`).
/// Before this check existed the reference compiled clean.
#[test]
fn native_bare_name_fn_value_with_a_ref_param_is_e080() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-fnvalue-ref-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "fn heal(ref amount) {\n\
         \x20 amount = amount + 1;\n}\n\
         fn used() {\n\
         \x20 let f = heal;\n\
         \x20 return 0;\n}\n\
         flow main() {\n  Used: {used()} -> END\n}\n",
    )
    .unwrap();
    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let err = result.expect_err("a ref-param target may not be referenced by bare name");
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E080"),
        "expected E080 at the bare-name reference, got: {codes:?}"
    );
}

/// Same obligation, but the bare-name reference sits in **declaration-
/// initializer** position (`var f = heal`) rather than inside a function
/// body. `check_native_bare_refs` only walks the block tree
/// (`hir::visit::visit`), which never descends into a file-level `VAR`/
/// `CONST` initializer — so before this test's fix, a `ref`-param target
/// referenced only this way compiled clean with no E080 at all, even
/// though the reviewer's own doc comment on `check_native_bare_refs`
/// asserts the obligation as an absolute ("a target with any ref parameter
/// can never be referenced by bare name").
#[test]
fn native_bare_name_fn_value_in_decl_initializer_with_a_ref_param_is_e080() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-fnvalue-decl-ref-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "fn heal(ref amount) {\n\
         \x20 amount = amount + 1;\n}\n\
         var f = heal\n\
         flow main() {\n  Used: {0} -> END\n}\n",
    )
    .unwrap();
    let result = brink_compiler::compile_path(&dir.join("main.brink"));
    std::fs::remove_dir_all(&dir).ok();

    let err = result.expect_err("a ref-param target may not be referenced by bare name");
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E080"),
        "expected E080 at the decl-initializer bare-name reference, got: {codes:?}"
    );
}

/// The same shape without any `ref` parameter compiles and runs — the
/// guard above must not fire on an ordinary by-value target.
#[test]
fn native_bare_name_fn_value_without_ref_params_compiles_and_runs() {
    let output = compile_and_run_native(
        "fnvalue-plain",
        "fn double(x) {\n\
         \x20 return x * 2;\n}\n\
         fn apply(g, v) {\n\
         \x20 return g(v);\n}\n\
         flow main() {\n  Applied: {apply(double, 21)} -> END\n}\n",
    );
    assert!(
        output.contains("Applied: 42"),
        "expected the bare name to reach `apply` as a callable fn value, got: {output:?}"
    );
}

// ── Native bare-name fn-value typing (issue #1876) ──────────────────
//
// #1862 landed the lowering; the reference still inferred as `Ty::Unknown`,
// so the type checker could not catch the very typo hazard the 2026-08-01
// ruling accepted an unsigilled spelling *because* it catches. These two
// tests are the compile-time halves of that claim — the type now exists
// (so a real mismatch is a diagnostic) and it is the *right* type (so a
// legitimate callback is not a false positive). The runtime half stays in
// the `tests/tier1-native/fn-value-bare-name/` golden case.

/// Compile one `.brink` source under the strict typed posture a real
/// native project runs in — `dialect = "brink"` in `brink.toml`, whose
/// `types` default is [`TypePolicy::Strict`] (`resolve_type_policy`) and
/// which is what makes `strict::check`'s inference-driven codes (`E063`
/// among them) fire at all.
fn compile_native_strict(
    dir_suffix: &str,
    source: &str,
) -> Result<brink_compiler::CompileOutput, brink_compiler::CompileError> {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-1876-{dir_suffix}-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("main.brink"), source).unwrap();
    let result = brink_compiler::compile_path_with_options(
        &dir.join("main.brink"),
        brink_compiler::AnalysisOptions {
            dialect: brink_compiler::Dialect::Brink,
            types: Some(brink_compiler::TypePolicy::Strict),
            ..brink_compiler::AnalysisOptions::default()
        },
    );
    std::fs::remove_dir_all(&dir).ok();
    result
}

/// The typo hazard, caught statically: `total(double)` passes a fn value
/// where the callee declares `int`. Before #1876 the argument typed
/// `Unknown`, `DirectCallArgMismatch` skipped it as unresolved, and this
/// fixture compiled clean — the obligation fell all the way to a runtime
/// fault, even though the 2026-08-01 ruling accepted the unsigilled
/// spelling *on the grounds* that the type checker catches this.
#[test]
fn native_bare_name_fn_value_passed_where_an_int_is_expected_is_e063() {
    let err = compile_native_strict(
        "mismatch",
        "fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         fn total(n: int): int {\n\
         \x20 return n + 1;\n}\n\
         flow main() {\n  Bad: {total(double)} -> END\n}\n",
    )
    .expect_err("passing a bare-name fn value where an `int` is declared must fail compilation");
    // Assert the exact code vector, not `contains` — this fixture is
    // deliberately clean of every other strict diagnostic so E063 alone
    // must be what fails compilation (matches the precedent in
    // `tm3_strict_policy.rs`'s `strict_direct_call_arg_mismatch_blocks_
    // compilation_with_e063`). `contains` alone would also stay green if
    // the code came from the annotation-vs-inference mismatch path
    // instead of `strict::check_direct_call_args` — pin the message too,
    // so a diagnostic-source swap that happens to also be E063 still
    // fails this test.
    let brink_compiler::CompileError::Diagnostics(diags) = &err else {
        panic!("expected a Diagnostics compile error, got: {err:?}");
    };
    assert_eq!(
        diags.iter().map(|d| d.code).collect::<Vec<_>>(),
        vec![brink_ir::DiagnosticCode::E063],
        "expected E063 alone, got: {diags:?}"
    );
    assert_eq!(
        diags[0].message,
        "argument 1 of call to `total` has type `fn(int): int` but its known type expects `int`",
        "expected the `check_direct_call_args` message shape, got: {:?}",
        diags[0].message
    );
}

/// The other direction — no false positive, under the *same* strict
/// posture. The same bare name handed to a parameter *declared*
/// `fn(int): int` is assignable (annotation rows are the unknown top
/// element and `assignable` is row-insensitive, issue #1680), so the
/// fixture compiles and runs. A rule that typed the reference as anything
/// but the target's own signature would break every legitimate callback.
#[test]
fn native_bare_name_fn_value_satisfies_a_declared_fn_parameter() {
    let data = compile_native_strict(
        "annotated-param",
        "fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         fn apply(g: fn(int): int, v: int): int {\n\
         \x20 return g(v);\n}\n\
         flow main() {\n  Applied: {apply(double, 21)} -> END\n}\n",
    )
    .unwrap_or_else(|err| {
        panic!(
            "a bare name must satisfy a declared `fn(int): int` parameter: {:?}",
            diagnostic_codes(&err)
        )
    })
    .data;
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let output: String = story
        .continue_maximally()
        .unwrap()
        .iter()
        .map(Step::text)
        .collect();
    assert!(
        output.contains("Applied: 42"),
        "the fn value must still reach `apply` and be callable there, got: {output:?}"
    );
}

// ── Native bare-name fn value in declaration-initializer position
//    (issue #1895) ────────────────────────────────────────────────────
//
// #1876 typed the *expression* position only. Lowering has always minted
// the fn value at a declaration initializer too
// (`lir::lower::decls::fold_path_ref` → `ConstValue::FnRef`), and
// `fn_values::check_native_bare_refs` already walks decl initializers for
// E080 — so the typing side was the odd one out, leaving the global at
// `Ty::Unknown` and turning a later call through it into `E065` on
// perfectly valid code.

/// The false positive itself: a file-level `var f = double` under
/// `types = strict`, called as `f(3)`. With `signature::declared_fn_type`
/// blind to the native bare-name spelling, `Sig::value_ty` is `None`, the
/// global never lands in `collect_globals`, `ty_of_def` answers
/// `Ty::Unknown`, and `check_value_call` classifies the call as
/// `UnknownCallee` → E065 on correct code.
#[test]
fn native_bare_name_fn_value_decl_initializer_call_is_not_e065() {
    let data = compile_native_strict(
        "decl-init-call",
        "fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         var f = double\n\
         flow main() {\n  Doubled: {f(3)} -> END\n}\n",
    )
    .unwrap_or_else(|err| {
        panic!(
            "calling a global initialized to a native bare-name fn value must compile: {:?}",
            diagnostic_codes(&err)
        )
    })
    .data;
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let output: String = story
        .continue_maximally()
        .unwrap()
        .iter()
        .map(Step::text)
        .collect();
    assert!(
        output.contains("Doubled: 6"),
        "the global must still hold a callable fn value at runtime, got: {output:?}"
    );
}

/// The other half of "the type exists": it is the *right* type, so a real
/// mismatch through the same global is still caught. Typing the
/// initializer as anything but `double`'s own signature would make this
/// fixture compile clean again.
#[test]
fn native_bare_name_fn_value_decl_initializer_type_is_the_targets_signature() {
    let err = compile_native_strict(
        "decl-init-mismatch",
        "fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         fn total(n: int): int {\n\
         \x20 return n + 1;\n}\n\
         var f = double\n\
         flow main() {\n  Bad: {total(f)} -> END\n}\n",
    )
    .expect_err("passing the fn-valued global where an `int` is declared must fail compilation");
    let brink_compiler::CompileError::Diagnostics(diags) = &err else {
        panic!("expected a Diagnostics compile error, got: {err:?}");
    };
    assert_eq!(
        diags.iter().map(|d| d.code).collect::<Vec<_>>(),
        vec![brink_ir::DiagnosticCode::E063],
        "expected E063 alone, got: {diags:?}"
    );
    assert_eq!(
        diags[0].message,
        "argument 1 of call to `total` has type `fn(int): int` but its known type expects `int`",
        "expected the `check_direct_call_args` message shape, got: {:?}",
        diags[0].message
    );
}

/// A same-named global shadows the function, exactly as it does at
/// runtime: `lir::lower::decls::fold_path_ref` resolves the initializer
/// through the real resolution map, which reaches a `const double` before
/// it reaches `fn double` and folds the constant's value. The typing side
/// has no resolution map — it is declaration-derived — so it declines
/// rather than guessing the fn interpretation. Without that decline
/// `alias` would type `fn(int): int` and this fixture would fail with a
/// bogus E063 on the `total(alias)` call.
#[test]
fn native_bare_name_shadowed_by_a_same_named_global_is_not_typed_as_a_fn_value() {
    let data = compile_native_strict(
        "decl-init-shadowed",
        "fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         fn total(n: int): int {\n\
         \x20 return n + 1;\n}\n\
         const double = 5\n\
         var alias = double\n\
         flow main() {\n  Val: {total(alias)} -> END\n}\n",
    )
    .unwrap_or_else(|err| {
        panic!(
            "a bare name shadowed by a same-named global is a constant read, not a fn value: {:?}",
            diagnostic_codes(&err)
        )
    })
    .data;
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let output: String = story
        .continue_maximally()
        .unwrap()
        .iter()
        .map(Step::text)
        .collect();
    assert!(
        output.contains("Val: 6"),
        "the shadowed bare name must fold to the constant's value, got: {output:?}"
    );
}

/// The `ListItem` sibling of the test above: a bare name shadowed by a list
/// item, in the *same* file. `ListItem`s are indexed under their qualified
/// `List.Item` name (never the bare item name), so the direct
/// `index.by_name.get(target_name)` lookup in `declared_fn_type`'s shadow
/// guard can never see them — closing this gap needs the same bare-name
/// suffix scan `lookup_variable` itself uses (`lookup_list_item_bare`),
/// consulted ahead of the knot lookup exactly as `lookup_variable`'s own
/// priority order does. Without it, `alias` was typed `fn(int): int` from
/// the knot `double` while lowering actually bound it to the list item
/// `Palette.double` — a same-file disagreement with no cross-module
/// privacy gate (`E087`) to mask it, unlike the cross-file case
/// (`native_cross_file_global_shadow_of_a_fn_value_reference_fails_to_compile`
/// below). Revert the `lookup_list_item_bare` call in
/// `crates/internal/brink-analyzer/src/signature.rs`'s `declared_fn_type`
/// and this fails with a bogus `E063` alone (verified per house rule 20a).
#[test]
fn native_bare_name_shadowed_by_a_same_named_list_item_is_not_typed_as_a_fn_value() {
    let data = compile_native_strict(
        "decl-init-shadowed-by-list-item",
        "flags Palette = double, other\n\
         fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         fn total(n: int): int {\n\
         \x20 return n + 1;\n}\n\
         var alias = double\n\
         flow main() {\n  Val: {total(alias)} -> END\n}\n",
    )
    .unwrap_or_else(|err| {
        panic!(
            "a bare name shadowed by a same-named list item is a list-item read, not a fn value: {:?}",
            diagnostic_codes(&err)
        )
    })
    .data;
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let output: String = story
        .continue_maximally()
        .unwrap()
        .iter()
        .map(Step::text)
        .collect();
    assert!(
        output.contains("Val:"),
        "the shadowed bare name must fold to the list item's value, got: {output:?}"
    );
}

/// The ink surface is untouched: `VAR f = double` in `.ink` has never been
/// a fn value (a bare knot name there is a visit count), so the new arm
/// must stay off unless the declaring file is native. Kept as a guard on
/// the `hir.native` conjunct — dropping it would silently give every ink
/// `VAR` initialized to a function knot's name a `Ty::Fn`.
///
/// Must actually be able to fail, so this compiles through
/// `compile_path_with_options` with `dialect = Brink` + `types = Strict`
/// (not `compile_and_run`'s bare `compile_mem`, which never turns strict
/// typing on and so could never observe a false `E063` here — house rule
/// 20a). `native` gates on which frontend parsed the file
/// (`crate::driver::prepare_driver` dispatches on the entry's `.brink`
/// extension), not on the `dialect` policy, so a *typed* function knot
/// under the T1b brink-extension syntax (`=== function f(x: int): int
/// ===`) is still parsed by the ink frontend here (`main.ink`) and stays
/// `native == false`. `g` must therefore stay `Ty::Unknown` and
/// `total(g)` must compile clean even under strict. With the `native`
/// conjunct stubbed out this fails with exactly `["E063"]` — `g` would
/// type as `fn(int): int` and mismatch `total`'s `int` parameter.
#[test]
fn ink_var_initialized_to_a_function_name_is_not_typed_as_a_fn_value() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-ink-1895-decl-init-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("main.ink");
    std::fs::write(
        &path,
        "VAR g = f\n\
         === function f(x: int): int ===\n\
         ~ return x\n\n\
         === function total(n: int): int ===\n\
         ~ return n + 1\n\n\
         === main ===\n\
         ~ total(g)\n\
         -> DONE\n",
    )
    .unwrap();
    let result = brink_compiler::compile_path_with_options(
        &path,
        brink_compiler::AnalysisOptions {
            dialect: brink_compiler::Dialect::Brink,
            types: Some(brink_compiler::TypePolicy::Strict),
            ..brink_compiler::AnalysisOptions::default()
        },
    );
    std::fs::remove_dir_all(&dir).ok();
    result.unwrap_or_else(|err| {
        panic!(
            "an ink bare function-knot name must stay Unknown and compile \
             clean under strict typing, got: {:?}",
            diagnostic_codes(&err)
        )
    });
}

// ── Strict-typing sweep of gradual-only native fixtures (issue #1916)
//    ───────────────────────────────────────────────────────────────────
//
// `native_or_coalescing_*` and `native_as_binding_*` above compile
// exclusively through `compile_and_run_native`, which uses
// `brink_compiler::compile_path` — default `AnalysisOptions`
// (`types = None`, resolving to `Gradual` for `Dialect::StrictInk`). The
// strict type checker (`strict::check`) never runs on those two families,
// even though a real `.brink` project with `dialect = "brink"` in its
// `brink.toml` gets `Strict` by default. The gap does NOT extend to the
// `native_bare_name_fn_value_*` family immediately above: those tests
// already compile under `compile_native_strict` (issue #1876), so strict
// coverage for bare-name fn values already exists.
//
// This sweep compiles two fixtures — reusing their exact sources via the
// `OR_COALESCING_CHAIN_WITH_CALL_SRC` / `OR_COALESCING_UNPINNED_LHS_FAULT_SRC`
// constants above, so a change to either fixture cannot silently drift out
// of sync with what this sweep actually compiles — and records the
// resulting `strict::check` findings as a baseline. Both were chosen
// because they are empirically confirmed to produce NEW findings rows, not
// zero-yield duplicates: every fixture tried below that returned no
// findings, or that duplicates coverage already established elsewhere, was
// left out, specifically —
//   * `native_or_coalescing_collapse_form_unwraps_some_and_falls_back_on_none`,
//     `native_or_coalescing_chain_falls_through_to_final_fallback`, the
//     short-circuit pair (`native_or_coalescing_short_circuits_rhs_on_some_
//     lhs` / `..._still_evaluates_rhs_when_lhs_is_none`), and
//     `native_as_binding_while_form_rebinds_each_iteration` all compile with
//     ZERO strict findings (confirmed by running each through
//     `compile_native_strict` and inspecting `CompileOutput::warnings`) —
//     sweeping them adds no coverage.
//   * `native_as_binding_statement_form_binds_payload_and_falls_to_else`
//     and `native_bare_name_fn_value_without_ref_params_compiles_and_runs`
//     are byte-identical to (respectively a strict superset of)
//     `tests/tier1-native/as-binding/story.brink` and
//     `tests/tier1-native/fn-value-bare-name/story.brink`, both already
//     swept by `tests/driver_native_strict.rs`'s baseline — re-sweeping
//     them here would add zero net new rows.
//
// This is a **partial** sweep (2 of the 22 `native_*` fixtures in this
// file) — see issue #1916 for the tracked remainder covering the other
// `native_or_coalescing_*` and `native_as_binding_*` fixtures.

/// Collect strict-pass findings (E063/E065/E066 diagnostics) from a compile
/// result.
fn strict_findings(
    fixture_name: &str,
    result: Result<brink_compiler::CompileOutput, brink_compiler::CompileError>,
) -> Vec<(String, String, String)> {
    let mut findings = Vec::new();
    let diagnostics = match result {
        Ok(output) => output.warnings,
        Err(brink_compiler::CompileError::Diagnostics(ds)) => ds,
        Err(e) => panic!("{fixture_name}: unexpected compile failure: {e}"),
    };
    for d in diagnostics {
        if matches!(
            d.code,
            brink_ir::DiagnosticCode::E063
                | brink_ir::DiagnosticCode::E065
                | brink_ir::DiagnosticCode::E066
        ) {
            findings.push((
                fixture_name.to_string(),
                d.code.as_str().to_string(),
                d.message,
            ));
        }
    }
    findings
}

/// Baseline of strict findings for the two swept fixtures, recorded from an
/// actual `compile_native_strict` run (not hand-derived).
///
/// `or-coalescing-chain-call`: `maybe()`'s return type is unannotated, so it
/// escapes strict inference as Unknown.
///
/// `or-coalescing-unpinned-lhs-fault`: `pick`'s parameter `x` and return
/// type are both unannotated (`strict::check` reports the return type;
/// `x`'s own Unknown-ness surfaces indirectly as the argument-type mismatch
/// on the call site, since the runtime-check posture the analyzer commits
/// to for an unpinned `lhs` still requires a *known* `Option` argument
/// under strict `check_direct_call_args`).
const BASELINE: &[(&str, &str, &str)] = &[
    (
        "or-coalescing-chain-call",
        "E065",
        "`maybe`'s return type escapes strict inference as Unknown — annotate or restructure",
    ),
    (
        "or-coalescing-unpinned-lhs-fault",
        "E063",
        "argument 1 of call to `pick` has type `int` but its known type expects `Option<int>`",
    ),
    (
        "or-coalescing-unpinned-lhs-fault",
        "E065",
        "`pick`'s return type escapes strict inference as Unknown — annotate or restructure",
    ),
];

/// Gate: the swept driver.rs fixtures' findings under strict typing must
/// match the recorded baseline.
#[test]
fn native_or_coalescing_strict_findings_match_baseline() {
    let mut actual = Vec::new();

    let result = compile_native_strict("or-coalesce-chain-call", OR_COALESCING_CHAIN_WITH_CALL_SRC);
    actual.extend(strict_findings("or-coalescing-chain-call", result));

    let result = compile_native_strict(
        "or-coalesce-unpinned-lhs-fault",
        OR_COALESCING_UNPINNED_LHS_FAULT_SRC,
    );
    actual.extend(strict_findings("or-coalescing-unpinned-lhs-fault", result));

    actual.sort();
    let expected: Vec<(String, String, String)> = BASELINE
        .iter()
        .map(|(f, c, m)| ((*f).to_string(), (*c).to_string(), (*m).to_string()))
        .collect();

    assert_eq!(
        actual, expected,
        "swept driver.rs native fixtures' strict findings drifted from baseline.\n\
         Do NOT edit the fixtures to make this pass — triage each finding and either \
         fix the checker or update BASELINE with a classification and tracking issue."
    );
}

/// Guard against the sweep going vacuous if strict options are misconfigured.
#[test]
fn the_sweep_actually_runs_under_strict() {
    let result = compile_native_strict(
        "guard-check",
        "fn f(x) { return x; }\nflow main() { -> END }\n",
    );
    let findings = strict_findings("guard", result);
    // At minimum, an unannotated parameter `x` should escape as Unknown
    // under strict mode. If we get nothing, the strict pass is not running.
    assert!(
        !findings.is_empty(),
        "the strict pass produced no findings at all — it is almost certainly \
         not running (issue #1916's original bug)"
    );
}

// ── compile_path (disk-based) ───────────────────────────────────────

#[test]
fn compile_path_reads_from_disk() {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/tier1/basics/I001-minimal-story/story.ink");

    let story = brink_compiler::compile_path(&path).unwrap();
    assert!(
        !story.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

#[test]
fn compile_path_nested_includes_from_disk() {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/tier3/misc/I025-nested-includes/story.ink");

    let story = brink_compiler::compile_path(&path).unwrap();
    assert!(
        !story.data.containers.is_empty(),
        "expected non-empty containers"
    );
}

// ── Compile + run (end-to-end) ─────────────────────────────────────

/// Compile from in-memory source, link, and run with given choice inputs.
fn compile_and_run(source: &str, inputs: &[usize]) -> String {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let mut output = String::new();
    let mut input_idx = 0;

    loop {
        let lines = story.continue_maximally().unwrap();
        let last = lines.last().unwrap();
        match last {
            Step::Line(_) | Step::Done | Step::End | Step::Suspended => {
                for line in &lines {
                    output.push_str(line.text());
                }
                break;
            }
            Step::Choices(choices) => {
                for line in &lines {
                    output.push_str(line.text());
                }
                let idx = if input_idx < inputs.len() {
                    let c = inputs[input_idx];
                    input_idx += 1;
                    c
                } else {
                    0
                };
                assert!(
                    idx < choices.len(),
                    "choice index {idx} out of range (only {} choices available)",
                    choices.len()
                );
                story.choose(idx).unwrap();
            }
        }
    }

    output
}

/// After a tunnel call returns, choices in the same container must be
/// yielded to the player. Regression: execution fell through to the
/// gather's `end` opcode, terminating the story before choices could
/// be presented.
#[test]
fn choices_after_tunnel_call_are_yielded() {
    let source = "\
-> main

=== function is_alive ===
~ return true

=== check ===
{ is_alive():
    ->->
}
-> END

=== main ===
Before choices.
-> check ->
*   [Option A]
    Chose A.
*   [Option B]
    Chose B.
- -> END
";
    let result = compile_and_run(source, &[0]);
    assert!(
        result.contains("Chose A"),
        "expected 'Chose A' after tunnel return, got: {result:?}"
    );
}

/// Choices after a tunnel call with arguments must be yielded.
/// Same regression as above but with parameter passing.
#[test]
fn choices_after_tunnel_call_with_args_are_yielded() {
    let source = "\
VAR hp = 2

-> main

=== function is_alive ===
~ return hp > 0

=== get_hit(x) ===
~ hp = hp - x
{ is_alive():
    ->->
}
-> END

=== main ===
Start.
-> get_hit(1) ->
*   [Fight]
    You fight.
*   [Flee]
    You flee.
- -> END
";
    let result = compile_and_run(source, &[0]);
    assert!(
        result.contains("You fight"),
        "expected 'You fight' after tunnel return, got: {result:?}"
    );
}

/// Nested choices with tunnel calls: outer choice leads to tunnel call,
/// tunnel returns, then inner choices must be presented. Mimics I003's
/// structure where the first choice leads to a stitch with a tunnel call
/// followed by sub-choices.
#[test]
fn nested_choices_after_tunnel_in_stitch() {
    let source = "\
VAR hp = 2

-> main

=== function is_alive ===
~ return hp > 0

=== get_hit(x) ===
~ hp = hp - x
{ is_alive():
    ->->
}
-> END

=== main ===
Choose:
*   [Yes]
    You chose yes.
    -> END
*   [No]
    You chose no.
    -> get_hit(1) ->
    **  [Fight]
        You fight.
    **  [Flee]
        You flee.
    - -> END
";
    let result = compile_and_run(source, &[1, 0]);
    assert!(
        result.contains("You fight"),
        "expected inner choice after tunnel return, got: {result:?}"
    );
}

// ── List display names ───────────────────────────────────────────────

/// List items should display without their origin prefix.
/// e.g. `{myList}` should output "a, b" not "myList.a, myList.b".
#[test]
fn list_items_display_without_origin_prefix() {
    let source = "\
LIST colors = (red), green, (blue)
{colors}
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "red, blue\n");
}

/// Multi-list display: items from different lists show unqualified names.
#[test]
fn multi_list_display_without_origin_prefix() {
    let source = "\
LIST a = (x), y
LIST b = (p), q
{a + b}
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "x, p\n");
}

// ── External function fallback ───────────────────────────────────────

/// EXTERNAL declaration with ink fallback function should use the fallback
/// when no external binding is provided.
#[test]
fn external_function_uses_ink_fallback() {
    let source = "\
EXTERNAL greet()

The value is {greet()}.
-> END

=== function greet() ===
~ return \"hello\"
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "The value is hello.\n");
}

/// EXTERNAL with arguments should pass args to the ink fallback.
#[test]
fn external_function_fallback_with_args() {
    let source = "\
EXTERNAL add(x, y)

The value is {add(3, 4)}.
-> END

=== function add(x, y) ===
~ return x + y
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "The value is 7.\n");
}

// ── Include file ordering ────────────────────────────────────────────

/// Content from included files should appear before the including file's
/// content, matching ink's INCLUDE-as-paste semantics.
#[test]
fn include_content_appears_before_main() {
    let files: HashMap<&str, &str> = HashMap::from([
        ("main.ink", "INCLUDE a.ink\nINCLUDE b.ink\nThis is main.\n"),
        ("a.ink", "This is A.\n"),
        ("b.ink", "This is B.\n"),
    ]);
    let data = compile_mem("main.ink", &files).unwrap();
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let lines = story.continue_maximally().unwrap();
    let result: String = lines.iter().map(Step::text).collect();
    assert_eq!(
        result, "This is A.\nThis is B.\nThis is main.\n",
        "included file content must appear before main file content"
    );
}

// ── Divert to standalone labeled gather ──────────────────────────────

/// Diverting to a labeled gather within a knot (e.g. `-> knot.gather`)
/// must work. The gather needs its own container to be a divert target.
#[test]
fn divert_to_standalone_labeled_gather() {
    let source = "\
-> knot
=== knot ===
-> knot.gather
- (gather) g
-> DONE
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "g\n");
}

// ── Pattern 1: Divert/tunnel parameters not pushed onto stack ────────

/// Variable divert with parameter: `->x (5)` where x holds a divert target.
/// The argument must be pushed onto the value stack before the call.
#[test]
fn divert_target_with_parameter() {
    let source = "\
VAR x = ->place
->x (5)
== place (a) ==
{a}
-> DONE
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "5\n");
}

/// Tunnel onwards with argument: `->-> b (5 + 3)` must evaluate the
/// expression and pass the result to the target knot.
#[test]
fn tunnel_onwards_with_arg() {
    let source = "\
-> a ->
=== a ===
->-> b (5 + 3)
=== b (x) ===
{x}
-> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "8\n");
}

/// Tunnel onwards with parameter inside a default choice:
/// `* ->-> elsewhere (8)` — the default choice auto-fires and passes the arg.
#[test]
fn tunnel_onwards_with_param_default_choice() {
    let source = "\
-> tunnel ->
== tunnel ==
* ->-> elsewhere (8)
== elsewhere (x) ==
{x}
-> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "8\n");
}

/// Variable tunnel: `-> x ->` where x is a divert parameter.
/// Must use `tunnel_call_variable`, not a literal `tunnel_call`.
#[test]
fn variable_tunnel_call() {
    let source = "\
-> one_then_tother(-> tunnel)

=== one_then_tother(-> x) ===
    -> x -> end

=== tunnel ===
    STUFF
    ->->

=== end ===
    -> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "STUFF\n");
}

// ── Pattern 2: Tunnel gather emits done instead of tunnel_return ─────

/// After choosing inside a tunnel, execution should return to the caller
/// via `tunnel_return`, not terminate with `done`.
#[test]
fn tunnel_return_at_gather_with_thread() {
    let source = "\
-> knot
=== knot
    <- threadA
    When should this get printed?
    -> DONE
=== threadA
    -> tunnel ->
    Finishing thread.
    -> DONE
=== tunnel
    -   I'm in a tunnel
    *   I'm an option
    -   ->->
";
    let result = compile_and_run(source, &[0]);
    assert_eq!(
        result,
        "I'm in a tunnel\nWhen should this get printed?\nI'm an option\nFinishing thread.\n"
    );
}

/// Bare `->->` on a gather line must emit a tunnel return.
/// `lower_gather_to_block` only handles `simple_divert()`, so `->->`
/// (a `TUNNEL_ONWARDS_NODE`) is silently dropped, producing `done`
/// instead of `tunnel_return`.
#[test]
fn gather_bare_tunnel_return() {
    let source = "\
-> start
== start ==
-> tun ->
After tunnel.
-> END
== tun ==
- Gathered.
* Pick me
- ->->
";
    let result = compile_and_run(source, &[0]);
    assert_eq!(result, "Gathered.\nPick me\nAfter tunnel.\n");
}

/// `->-> target` on a gather line — tunnel return with divert override.
#[test]
fn gather_tunnel_return_with_override() {
    let source = "\
-> start
== start ==
-> tun ->
Should not print.
-> END
== tun ==
- In tunnel.
* Pick me
- ->-> destination
== destination ==
Overridden.
-> END
";
    let result = compile_and_run(source, &[0]);
    assert_eq!(result, "In tunnel.\nPick me\nOverridden.\n");
}

/// `-> target ->` on a gather line — tunnel call from a gather.
#[test]
fn gather_tunnel_call() {
    let source = "\
-> start
== start ==
* Pick me
- -> inner_tunnel ->
After inner tunnel.
-> END
== inner_tunnel ==
Inside inner tunnel.
->->
";
    let result = compile_and_run(source, &[0]);
    assert_eq!(
        result,
        "Pick me\nInside inner tunnel.\nAfter inner tunnel.\n"
    );
}

/// `<- thread` on a gather line — thread start from a gather.
/// The thread's choice must merge with the local sticky choice.
#[test]
fn gather_thread_start() {
    let source = "\
-> start
== start ==
* Pick me
- <- bg_thread
+ Next
-
Done.
-> END
== bg_thread ==
* Background option
- -> DONE
";
    // Pick "Pick me" first, then "Background option" (from the thread)
    // If the thread start is silently dropped, only "Next" is available
    // and "Background option" never appears.
    let result = compile_and_run(source, &[0, 0]);
    assert!(
        result.contains("Background option"),
        "expected thread's choice from gather `<- bg_thread` to be available, got: {result:?}"
    );
}

/// Structural test: compile a tunnel with `->->` on a gather line and
/// verify the .inkt contains `tunnel_return`, not just `done`.
#[test]
fn gather_tunnel_return_emits_tunnel_return_opcode() {
    let source = "\
-> start
== start ==
-> tun ->
After.
-> END
== tun ==
- Top.
* Option
- ->->
";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();
    let mut buf = String::new();
    brink_format::write_inkt(&data, &mut buf).unwrap();
    assert!(
        buf.contains("tunnel_return"),
        "expected tunnel_return in bytecode for gather `->->`, got:\n{buf}"
    );
}

// ── Pattern 3: Thread choices not merged with current context ────────

/// Choices from a thread (`<- thread_with_options`) must merge with
/// choices from the current context (tunnel or inline).
#[test]
#[ignore = "thread completion doesn't resume main flow — runtime thread merging bug"]
fn tunnel_and_thread_choices_merge() {
    let source = "\
-> knot_with_options ->
Finished tunnel.
Starting thread.
<- thread_with_options
* E
-
Done.
== knot_with_options ==
* A
* B
-
->->
== thread_with_options ==
* C
* D
- -> DONE
";
    // Episode e0: choose A (idx 0), then C (idx 0 of remaining thread choices)
    let result = compile_and_run(source, &[0, 0]);
    assert_eq!(result, "A\nFinished tunnel.\nStarting thread.\nC\nDone.\n");
}

/// Thread choices must merge with tunnel choices in an interleaved scenario.
#[test]
fn thread_choices_merge_with_tunnel() {
    let source = "\
-> knot
=== knot
    <- threadB
    -> tunnel ->
    THE END
    -> END
=== tunnel
    - blah blah
    * wigwag
    - ->->
=== threadB
    *   option
    -   something
        -> DONE
";
    let result = compile_and_run(source, &[0]);
    assert_eq!(result, "blah blah\noption\nsomething\n");
}

/// Two threads contribute choices that must both appear in the choice set.
#[test]
fn multiple_thread_choices_merge() {
    let source = "\
-> start
== start ==
-> tunnel ->
The end
-> END
== tunnel ==
<- place1
<- place2
-> DONE
== place1 ==
This is place 1.
* choice in place 1
- ->->
== place2 ==
This is place 2.
* choice in place 2
- ->->
";
    let result = compile_and_run(source, &[0]);
    assert!(
        result.contains("choice in place 1"),
        "expected first thread's choice to be available, got: {result:?}"
    );
}

/// Thread choices in a loop: `<- choices(-> top)` must merge the thread's
/// "No" choice with the local "Yes" choice, and picking "No" must loop.
#[test]
fn thread_choice_loop_with_variable_divert() {
    let source = "\
-> start

=== start ===
Here is some gold. Do you want it?
- (top)
    <- choices(-> top)
    + Yes
        You win!
        -> END

=== choices(-> goback) ===
+ No
    Try again!
    -> goback
";
    // Pick No, No, then Yes
    let result = compile_and_run(source, &[1, 1, 0]);
    assert!(
        result.contains("You win!"),
        "expected loop with thread choices, got: {result:?}"
    );
}

/// Structural test: the compiler must NOT emit `begin_choice_set` in the
/// bytecode. This opcode was removed because it cleared pending choices,
/// breaking thread choice merging.
#[test]
fn choice_set_does_not_emit_begin_choice_set() {
    let source = "\
-> start
== start ==
* Choice A
* Choice B
- Done.
";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();
    let mut buf = String::new();
    brink_format::write_inkt(&data, &mut buf).unwrap();
    assert!(
        !buf.contains("begin_choice_set"),
        "begin_choice_set should not appear in compiled output:\n{buf}"
    );
    assert!(
        !buf.contains("end_choice_set"),
        "end_choice_set should not appear in compiled output:\n{buf}"
    );
}

/// Three `<- thread` calls each contributing a choice — all three must appear.
#[test]
fn three_threads_all_choices_merge() {
    let source = "\
-> start
== start ==
<- t1
<- t2
<- t3
* local choice
- Done.
== t1 ==
* thread 1 choice
- -> DONE
== t2 ==
* thread 2 choice
- -> DONE
== t3 ==
* thread 3 choice
- -> DONE
";
    let result = compile_and_run(source, &[0]);
    // If all 4 choices are available, picking index 0 should succeed.
    // The key test: the story doesn't end prematurely due to cleared choices.
    assert!(
        result.contains("Done.") || result.contains("choice"),
        "expected all thread choices to be available, got: {result:?}"
    );
}

/// Thread provides a `*` (once-only) choice, main provides a `+` (sticky).
/// After selecting the once-only, only the sticky remains on re-evaluation.
#[test]
fn thread_choice_with_once_only_filtering() {
    let source = "\
-> start
== start ==
<- thread_opts
+ [sticky] Sticky text
- -> END
== thread_opts ==
* once only
    -> start
- -> DONE
";
    // Pick once-only (should be present alongside sticky), then sticky
    let result = compile_and_run(source, &[0, 0]);
    assert!(
        result.contains("once only") || result.contains("Sticky text"),
        "expected both choices to be available initially, got: {result:?}"
    );
}

/// `-> tunnel ->` where the tunnel does `<- thread`, both tunnel and
/// thread choices must merge with the caller's choices.
#[test]
fn nested_thread_in_tunnel_choices_merge() {
    let source = "\
-> start
== start ==
-> tun ->
* caller choice
- The end.
== tun ==
<- inner_thread
* tunnel choice
- ->->
== inner_thread ==
* thread choice
- -> DONE
";
    let result = compile_and_run(source, &[0]);
    assert!(
        result.contains("The end.") || result.contains("choice"),
        "expected thread+tunnel+caller choices to merge, got: {result:?}"
    );
}

// ── Pattern 3c: Nested gather chaining in deep weaves ────────────────

/// Three levels of choices with gathers at each level. After resolving
/// the deepest choices, execution must flow through each gather level
/// back to the outermost gather.
#[test]
fn nested_gather_three_levels() {
    let source = "\
* A
    * * B
        * * * C
        - - - Inner gather.
    - - Middle gather.
- Outer gather.
-> END
";
    let result = compile_and_run(source, &[0, 0, 0]);
    assert_eq!(
        result,
        "A\nB\nC\nInner gather.\nMiddle gather.\nOuter gather.\n"
    );
}

/// Two levels with a gather-then-second-choice-set pattern: the `- -`
/// gather has content then a second round of choices. After that second
/// round resolves, execution must still reach the `-` outer gather.
#[test]
fn nested_gather_with_second_choice_round() {
    let source = "\
* First
    * * Second
    * * Third
    - - Between.
    * * Fourth
    - - After fourth.
- Final.
-> END
";
    let result = compile_and_run(source, &[0, 0, 0]);
    assert_eq!(
        result,
        "First\nSecond\nBetween.\nFourth\nAfter fourth.\nFinal.\n"
    );
}

/// Simplified version of complex-flow-v1: the key pattern is that
/// the `- -` gather has glue (`<>`) that connects to the `-` gather.
#[test]
fn nested_gather_with_glue_continuation() {
    let source = "\
* Outer choice
    * * Deep choice
    - - After deep, <>
- outer end.
-> END
";
    let result = compile_and_run(source, &[0, 0]);
    assert_eq!(
        result,
        "Outer choice\nDeep choice\nAfter deep, outer end.\n"
    );
}

// ── Pattern 3d: Stitch parameters (including ref) ────────────────────

/// Stitch parameters must receive unique temp slots and be accessible
/// within the stitch body. This is the simplest case: by-value params.
#[test]
fn stitch_params_by_value() {
    let source = "\
-> greet.say(\"Hello\", \"world\")

== greet ==
= say(greeting, who)
{greeting}, {who}!
-> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Hello, world!\n");
}

/// Ref parameters on a function must be writable and must persist changes
/// back to the caller's variable (global var case).
#[test]
fn ref_param_global_var() {
    let source = "\
VAR x = 1
~ bump(x)
{x}
-> END

=== function bump(ref target) ===
~ target = target + 1
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "2\n");
}

/// Ref param passed via function call with two ref args — the
/// `move_ring` pattern from tower-of-hanoi.
#[test]
fn ref_param_function_two_refs() {
    let source = "\
VAR a = 10
VAR b = 0
~ swap(a, b)
a={a} b={b}
-> END

=== function swap(ref x, ref y) ===
~ temp t = x
~ x = y
~ y = t
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "a=0 b=10\n");
}

/// Thread-called stitch with conditional choice and ref params —
/// the core tower-of-hanoi pattern. The stitch is called via `<-`
/// and provides a conditional choice based on `can_move`.
#[test]
fn tower_of_hanoi_mini() {
    let source = "\
LIST Discs = one, two, three
VAR post1 = ()
VAR post2 = ()
VAR post3 = ()

~ post1 = LIST_ALL(Discs)

-> gameloop

=== function can_move(from_list, to_list) ===
    {
    -   LIST_COUNT(from_list) == 0:
        ~ return false
    -   LIST_COUNT(to_list) > 0 && LIST_MIN(from_list) > LIST_MIN(to_list):
        ~ return false
    -   else:
        ~ return true
    }

=== function move_ring( ref from, ref to ) ===
    ~ temp whichRingToMove = LIST_MIN(from)
    ~ from -= whichRingToMove
    ~ to += whichRingToMove

=== gameloop
    Start.
- (top)
    +  [ Regard]
        Regarded.
    <- move_post(1, 2, post1, post2)
    -> DONE

= move_post(from_post_num, to_post_num, ref from_post_list, ref to_post_list)
    +   { can_move(from_post_list, to_post_list) }
        [ Move ]
        { move_ring(from_post_list, to_post_list) }
        Moved.
    -> top
";
    // Choose \"Move\" (from move_post thread), then \"Regard\"
    let result = compile_and_run(source, &[0, 0]);
    assert!(
        result.contains("Moved") || result.contains("Regarded"),
        "expected tower-of-hanoi mini to produce output, got: {result:?}"
    );
}

/// Ref params with list operations — minimal `move_ring` pattern.
#[test]
fn ref_param_list_move_ring() {
    let source = "\
LIST Discs = one, two, three
VAR post1 = ()
VAR post2 = ()

~ post1 = LIST_ALL(Discs)

~ move_ring(post1, post2)

{post1}
{post2}
-> END

=== function move_ring( ref from, ref to ) ===
~ temp whichRingToMove = LIST_MIN(from)
~ from -= whichRingToMove
~ to += whichRingToMove
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "two, three\none\n");
}

// ── Pattern 4: Missing space literal in string interpolation ─────────

/// `{gatherCount} {loop}` must produce "1 1", not "11" — the space
/// between interpolations must be emitted as a literal.
#[test]
#[ignore = "visit count for gather labels not incremented on re-entry"]
fn space_between_interpolations_preserved() {
    let source = "\
VAR gatherCount = 0
- (loop)
~ gatherCount++
{gatherCount} {loop}
{gatherCount<3:->loop}
-> DONE
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "1 1\n2 2\n3 3\n");
}

// ── Pattern 4b: Conditional divert in inline branch ──────────────────

/// `{condition:->target}` — divert inside a conditional inline branch.
/// The divert was silently dropped by `lower_content_node_children`,
/// so the conditional body was empty and the divert never fired.
#[test]
fn conditional_divert_basic() {
    let source = "\
VAR x = 1
{x == 1:->yes}
Nope.
-> END
== yes ==
Yes!
-> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Yes!\n");
}

/// Conditional divert in a loop — the core pattern from the space test.
#[test]
fn conditional_divert_loop() {
    let source = "\
VAR i = 0
- (loop)
~ i++
{i}
{i < 3:->loop}
-> DONE
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "1\n2\n3\n");
}

/// Conditional with text AND divert: `{cond: text ->target}`
#[test]
fn conditional_text_then_divert() {
    let source = "\
VAR x = 1
{x == 1: Going there! ->yes}
Nope.
-> END
== yes ==
Arrived.
-> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Going there! Arrived.\n");
}

/// Negative case: condition is false, divert should NOT fire.
#[test]
fn conditional_divert_false_branch() {
    let source = "\
VAR x = 0
{x == 1:->yes}
Fallthrough.
-> END
== yes ==
Yes!
-> END
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Fallthrough.\n");
}

// ── Pattern 5: ref parameters compiled as pointer ────────────────────

/// `ref` parameter should pass by reference, allowing the callee to
/// modify the caller's variable.
#[test]
fn ref_parameter_modifies_caller_variable() {
    let source = "\
VAR x = 0
~ bump(x)
{x}
-> DONE

=== function bump(ref n) ===
~ n++
";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "1\n");
}

/// Tower-of-hanoi pattern with all 6 thread starts.
/// Hangs due to runtime thread merging bug — multiple threads with
/// conditional choices create an infinite loop in the VM.
#[test]
#[ignore = "runtime thread merging infinite loop with multiple conditional-choice threads"]
fn tower_of_hanoi_6threads() {
    let source = "\
LIST Discs = one, two, three
VAR post1 = ()
VAR post2 = ()
VAR post3 = ()

~ post1 = LIST_ALL(Discs)

-> gameloop

=== function can_move(from_list, to_list) ===
    {
    -   LIST_COUNT(from_list) == 0:
        ~ return false
    -   LIST_COUNT(to_list) > 0 && LIST_MIN(from_list) > LIST_MIN(to_list):
        ~ return false
    -   else:
        ~ return true
    }

=== function move_ring( ref from, ref to ) ===
    ~ temp whichRingToMove = LIST_MIN(from)
    ~ from -= whichRingToMove
    ~ to += whichRingToMove

=== gameloop
    Start.
- (top)
    +  [ Regard]
        Regarded.
    <- move_post(1, 2, post1, post2)
    <- move_post(2, 1, post2, post1)
    <- move_post(1, 3, post1, post3)
    <- move_post(3, 1, post3, post1)
    <- move_post(3, 2, post3, post2)
    <- move_post(2, 3, post2, post3)
    -> DONE

= move_post(from_post_num, to_post_num, ref from_post_list, ref to_post_list)
    +   { can_move(from_post_list, to_post_list) }
        [ Move {from_post_num} to {to_post_num} ]
        { move_ring(from_post_list, to_post_list) }
        Moved.
    -> top
";
    let result = compile_and_run(source, &[0, 0]);
    assert!(
        result.contains("Moved") || result.contains("Regarded"),
        "expected output, got: {result:?}"
    );
}

// ── Expected compile errors ─────────────────────────────────────────
//
// Inklecate rejects these programs. Brink should too.

/// Helper: extract diagnostic codes from a compile error.
fn diagnostic_codes(err: &brink_compiler::CompileError) -> Vec<&'static str> {
    match err {
        brink_compiler::CompileError::Diagnostics(diags) => {
            diags.iter().map(|d| d.code.as_str()).collect()
        }
        _ => vec![],
    }
}

/// A choice inside `{ true: * choice }` without an explicit divert is
/// invalid — inklecate errors with "need to explicitly divert".
#[test]
fn compile_error_nested_choice_in_conditional() {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", "{ true:\n    * choice\n}\n")]);
    let result = compile_mem("main.ink", &files);
    let err = result.expect_err(
        "choice inside inline conditional should be a compile error, \
         but compilation succeeded",
    );
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E029"),
        "expected E029 (choice in conditional must explicitly divert), got: {codes:?}"
    );
}

/// A choice inside a conditional WITH a divert is valid — E029 must not fire.
#[test]
fn choice_in_conditional_with_divert_is_valid() {
    let source = "=== play_game ===\n{ true:\n  + [Burn] -> play_game\n}\n-> END\n";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let result = compile_mem("main.ink", &files);
    assert!(
        result.is_ok(),
        "choice with divert in conditional should compile: {result:?}"
    );
}

/// A choice inside a conditional WITHOUT a divert but with a gather continuation
/// after the conditional is valid ink — inklecate accepts this.
#[test]
fn choice_in_conditional_with_gather_continuation_is_valid() {
    let source =
        "=== play_game ===\n{ true:\n  + (burny) [Burn]\n    Hello\n}\n- -> burny\n-> END\n";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let result = compile_mem("main.ink", &files);
    assert!(
        result.is_ok(),
        "choice in conditional with gather continuation should compile: {result:?}"
    );
}

/// A bare `->` (empty divert) outside a choice is invalid.
/// Inklecate: "Empty diverts (->) are only valid on choices".
#[test]
fn compile_error_disallow_empty_diverts() {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", "->\n")]);
    let result = compile_mem("main.ink", &files);
    let err = result.expect_err("bare `->` should be a compile error, but compilation succeeded");
    let codes = diagnostic_codes(&err);
    assert!(
        codes.contains(&"E012"),
        "expected E012 (divert is missing a target), got: {codes:?}"
    );
}

// ── Unresolved function calls should error, not silently produce Null ─

#[test]
fn unresolved_function_call_is_compile_error() {
    // A call to a function that doesn't exist should be a compile-time
    // diagnostic, not a silent Null. This guards against the LIR lowering
    // fallback that converts unresolvable calls to Expr::Null.
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "\
~ temp x = DOES_NOT_EXIST()
{x}
-> END
",
    )]);
    let result = compile_mem("main.ink", &files);
    assert!(
        result.is_err(),
        "calling a nonexistent function should produce a compile error, not succeed silently"
    );
}

// ── TURNS() built-in ────────────────────────────────────────────────

#[test]
fn turns_builtin_compiles_and_runs() {
    // TURNS() is a zero-argument ink built-in that returns the current turn
    // index. The compiler must recognize it, lower it through LIR, and emit
    // the TurnIndex opcode. This test verifies end-to-end correctness.
    let output = compile_and_run(
        "\
~ temp t = TURNS()
turn is {t}
-> END
",
        &[],
    );
    assert_eq!(output.trim(), "turn is 0");
}

#[test]
fn turns_builtin_increments_across_choices() {
    // TURNS() should increment each time the player makes a choice and
    // the story continues. Turn 0 is the initial passage, turn 1 after
    // the first choice, etc.
    let output = compile_and_run(
        "\
turn {TURNS()}
+ [continue]
-
turn {TURNS()}
-> END
",
        &[0],
    );
    assert_eq!(output.trim(), "turn 0\nturn 1");
}

// ── Block-level sequence branch behaviors ──────────────────────────

/// Compile from in-memory source, link, and run. Returns a list of
/// (text, `choice_count`) pairs for each step.
fn compile_and_run_steps(source: &str, inputs: &[usize]) -> Vec<(String, Option<usize>)> {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);
    let mut steps = Vec::new();
    let mut input_idx = 0;
    let mut guard = 0;

    loop {
        guard += 1;
        assert!(guard < 100, "infinite loop detected");
        let lines = story.continue_maximally().unwrap();
        let combined_text: String = lines.iter().map(Step::text).collect();
        let last = lines.last().unwrap();
        match last {
            Step::Line(_) | Step::Done | Step::End | Step::Suspended => {
                steps.push((combined_text, None));
                break;
            }
            Step::Choices(choices) => {
                let count = choices.len();
                steps.push((combined_text.clone(), Some(count)));
                let idx = if input_idx < inputs.len() {
                    let c = inputs[input_idx];
                    input_idx += 1;
                    c
                } else {
                    0
                };
                assert!(
                    idx < count,
                    "choice index {idx} out of range (only {count} choices), text so far: {combined_text:?}"
                );
                story.choose(idx).unwrap();
            }
        }
    }

    steps
}

/// Block-level sequence branches must start with a newline relative to
/// preceding content. Inklecate inserts "\n" at the start of each
/// branch's content stream. Without this, output like
/// "I drew a card. 2 of Diamonds." appears on one line instead of two.
#[test]
fn sequence_branch_starts_with_newline() {
    let source = "\
-> test

=== test ===
{ stopping:
    - Branch one.
    - Branch two.
}
* [Again] Prefix. -> test
- -> END
";
    // First visit: "Branch one.\n" + choices: [Again]
    // Choose "Again" (once-only *), second visit: "Prefix.\nBranch two.\n" + no choices → END
    let steps = compile_and_run_steps(source, &[0]);
    // Step 1 (after choosing "Again") text must have a newline between
    // "Prefix." and "Branch two."
    assert!(
        steps.len() >= 2,
        "expected at least 2 steps, got {}",
        steps.len()
    );
    let text = &steps[1].0;
    assert!(
        text.contains("Prefix.") && text.contains("Branch two."),
        "expected both 'Prefix.' and 'Branch two.' in output, got: {text:?}"
    );
    // The newline must separate them (not on the same line)
    assert!(
        !text.contains("Prefix. Branch two.") && !text.contains("Prefix.Branch two."),
        "expected newline between 'Prefix.' and 'Branch two.', got: {text:?}"
    );
}

/// Choices inside a sequence branch must accumulate with choices from the
/// parent container. When a sequence branch contains a `ChoiceSet` and there
/// are also choices after the sequence in the same container, all choices
/// must be visible together (the branch's Done must not block the parent).
#[test]
fn choices_inside_sequence_branch_accumulate_with_parent() {
    // Pattern from the multiline-choice test case: a stopping sequence
    // where branch 1 has a once-only choice, plus a sticky choice after
    // the sequence. On visit 2, both must be visible.
    let source = "\
-> test
=== test ===
{ stopping:
    - At the table, I drew a card. Ace of Hearts.
    - 2 of Diamonds.
        \"Should I hit you again,\" the croupier asks.
        * [No.] I left the table. -> END
    - King of Spades.
        \"You lose,\" he crowed.
        -> END
}
+ [Draw a card] I drew a card. -> test
";
    // Visit 1: branch 0 text + choices: [Draw a card]
    // Choose "Draw a card" → visit 2: branch 1, choices: [No., Draw a card]
    let steps = compile_and_run_steps(source, &[0, 0]);
    // Second step must show 2 choices: [No., Draw a card]
    let second_choice_count = steps[1].1;
    assert_eq!(
        second_choice_count,
        Some(2),
        "expected 2 choices (No. + Draw a card) on second visit, got: {second_choice_count:?}"
    );
}

/// Content after a block-level conditional's closing `}` must not be
/// dropped. The glue and text `<> b` should join with the branch output.
#[test]
fn content_after_multiline_conditional_preserved() {
    let source = "\
{true:
    a
} <> b
";
    let result = compile_and_run(source, &[]);
    assert_eq!(
        result, "a b\n",
        "glue + text after conditional must be preserved"
    );
}

/// Same as above but with a second conditional after the glue.
#[test]
fn content_after_multiline_conditional_with_nested_conditional() {
    let source = "\
{true:
    a
} <> { true:
    b
}
";
    let result = compile_and_run(source, &[]);
    assert_eq!(
        result, "a b\n",
        "glue + conditional after conditional must be preserved"
    );
}

// ── Shuffle sequence exhaustion ────────────────────────────────────

/// `shuffle once` must stop producing content after all branches are visited.
/// This is an end-to-end behavioral test: call a shuffle-once function 4 times
/// with 2 branches — only the first 2 calls should produce text.
#[test]
fn shuffle_once_exhausts_after_all_branches_visited() {
    let source = "\
~ SEED_RANDOM(1)
one: {f()}
two: {f()}
three: {f()}
four: {f()}
== function f ==
{shuffle once:
    - A
    - B
}
";
    let result = compile_and_run(source, &[]);
    // Each of the 4 lines "N: X\n" gets the function result appended.
    // First 2 calls produce "A" or "B" (in shuffled order); last 2 produce nothing.
    let lines: Vec<&str> = result.lines().collect();
    assert_eq!(lines.len(), 4, "expected 4 output lines, got: {result:?}");

    // First two lines must each contain either "A" or "B".
    let first_two_content: Vec<&str> = lines[0..2]
        .iter()
        .map(|l| l.split(": ").nth(1).unwrap_or("").trim())
        .collect();
    let mut sorted = first_two_content.clone();
    sorted.sort_unstable();
    assert_eq!(
        sorted,
        vec!["A", "B"],
        "first two calls should produce A and B (in any order), got: {first_two_content:?}"
    );

    // Last two lines must have no content after the colon.
    for (i, line) in lines[2..].iter().enumerate() {
        let after_colon = line.split(": ").nth(1).unwrap_or("").trim();
        assert!(
            after_colon.is_empty(),
            "call {} (line {:?}) should produce no text after exhaustion, got: {after_colon:?}",
            i + 3,
            line,
        );
    }
}

/// `shuffle stopping` must pin to the last branch after all are visited.
/// Call a 3-branch shuffle-stopping function 5 times — after the first 3 calls
/// exhaust all branches, calls 4 and 5 must always return the last branch.
#[test]
fn shuffle_stopping_pins_to_last_branch() {
    let source = "\
~ SEED_RANDOM(1)
one: {f()}
two: {f()}
three: {f()}
four: {f()}
five: {f()}
== function f ==
{stopping shuffle:
    - A
    - B
    - final
}
";
    let result = compile_and_run(source, &[]);
    let lines: Vec<&str> = result.lines().collect();
    assert_eq!(lines.len(), 5, "expected 5 output lines, got: {result:?}");

    // First three calls produce A, B, final in some shuffled order.
    let first_three_content: Vec<String> = lines[0..3]
        .iter()
        .map(|l| l.split(": ").nth(1).unwrap_or("").trim().to_string())
        .collect();
    let mut sorted: Vec<&str> = first_three_content.iter().map(String::as_str).collect();
    sorted.sort_unstable();
    assert_eq!(
        sorted,
        vec!["A", "B", "final"],
        "first three calls should produce A, B, final (in any order), got: {first_three_content:?}"
    );

    // Calls 4 and 5 must produce "final" (the last/stopping branch).
    for (i, line) in lines[3..].iter().enumerate() {
        let after_colon = line.split(": ").nth(1).unwrap_or("").trim();
        assert_eq!(
            after_colon,
            "final",
            "call {} should pin to 'final' after exhaustion, got: {after_colon:?}",
            i + 4,
        );
    }
}

/// Opcode-level test: `shuffle once` codegen must emit a `Min` opcode
/// to clamp the visit count, enabling exhaustion detection.
#[test]
fn shuffle_once_codegen_emits_min_opcode() {
    use brink_format::Opcode;

    let source = "\
{shuffle once:
    - A
    - B
}
";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();

    // Find the sequence container (has VISITS + COUNT_START_ONLY flags).
    let seq_container = data
        .containers
        .iter()
        .find(|c| {
            let mut offset = 0;
            let mut has_sequence = false;
            while offset < c.bytecode.len() {
                if let Ok(op) = Opcode::decode(&c.bytecode, &mut offset) {
                    if matches!(op, Opcode::Sequence(..)) {
                        has_sequence = true;
                    }
                } else {
                    break;
                }
            }
            has_sequence
        })
        .expect("should find a container with a Sequence opcode");

    // Decode all opcodes and check for Min.
    let mut offset = 0;
    let mut has_min = false;
    while offset < seq_container.bytecode.len() {
        if let Ok(op) = Opcode::decode(&seq_container.bytecode, &mut offset) {
            if matches!(op, Opcode::Min) {
                has_min = true;
            }
        } else {
            break;
        }
    }
    assert!(
        has_min,
        "shuffle once container must emit Min opcode for exhaustion clamping"
    );
}

/// Contextual keywords like `once`, `stopping`, `shuffle`, `cycle` must be
/// usable as knot names and divert targets. Ink only treats these as keywords
/// inside sequence annotations — everywhere else they're valid identifiers.
#[test]
fn keyword_once_as_knot_name_and_divert_target() {
    let source = "\
-> once
== once ==
Hello from once.
-> END
";
    let result = compile_and_run(source, &[]);
    assert!(
        result.contains("Hello from once"),
        "knot named 'once' should work, got: {result:?}"
    );
}

/// Full thread-in-logic test (inklecate's TestThreadInLogic): tunnel calls
/// to a knot named `once` containing `{<- content|}`.
#[test]
fn thread_in_logic_compiles_and_runs() {
    let source = "\
-> once ->
-> once ->
== once ==
{<- content|}
->->
== content ==
Content
-> DONE
";
    let result = compile_and_run(source, &[]);
    assert!(
        result.contains("Content"),
        "thread-in-logic should produce 'Content', got: {result:?}"
    );
}

// ── Template tests (intl-spec phase 3) ──────────────────────────────

#[test]
fn template_single_variable() {
    let source = "VAR name = \"World\"\nHello, {name}!\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Hello, World!\n");
}

#[test]
fn template_multiple_interpolations() {
    let source = "VAR a = \"one\"\nVAR b = \"two\"\n{a} and {b}\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "one and two\n");
}

#[test]
fn template_expression_interpolation() {
    let source = "VAR n = 3\nResult: {n * 2}\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Result: 6\n");
}

#[test]
fn template_interpolation_at_start() {
    let source = "VAR x = \"Hello\"\n{x} world\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Hello world\n");
}

#[test]
fn template_interpolation_at_end() {
    let source = "VAR x = \"world\"\nHello {x}\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Hello world\n");
}

#[test]
fn plain_text_regression() {
    // Ensure plain text lines still work after template support.
    let source = "Just plain text.\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Just plain text.\n");
}

#[test]
fn template_integer_interpolation() {
    let source = "VAR count = 42\nThere are {count} items.\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "There are 42 items.\n");
}

#[test]
fn template_float_interpolation() {
    let source = "VAR pi = 3.14\nPi is {pi}.\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Pi is 3.14.\n");
}

#[test]
fn template_bool_interpolation() {
    let source = "VAR flag = true\nFlag: {flag}\n";
    let result = compile_and_run(source, &[]);
    assert_eq!(result, "Flag: true\n");
}

// ── Warning surfacing ───────────────────────────────────────────────

/// Helper: compile and return the full `CompileOutput` (data + warnings).
fn compile_mem_with_warnings(
    entry: &str,
    files: &HashMap<&str, &str>,
) -> Result<brink_compiler::CompileOutput, brink_compiler::CompileError> {
    brink_compiler::compile(entry, |path| {
        files.get(path).map(|s| (*s).to_string()).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("file not found: {path}"),
            )
        })
    })
}

#[test]
fn warnings_surfaced_alongside_successful_compilation() {
    // A CONST with string interpolation should compile successfully
    // but produce an E030 warning.
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "VAR name = \"world\"\nCONST greeting = \"hi {name}\"\n{greeting}\n",
    )]);

    let output = compile_mem_with_warnings("main.ink", &files).unwrap();
    assert!(
        !output.data.containers.is_empty(),
        "compilation should succeed"
    );
    assert!(
        output.warnings.iter().any(|w| w.code.as_str() == "E030"),
        "expected E030 warning, got: {:?}",
        output
            .warnings
            .iter()
            .map(|w| w.code.as_str())
            .collect::<Vec<_>>()
    );
}

/// A warning originating in an included file must carry that file's path, not
/// the entry's. Regression for #187 (secondary): the public API used to return
/// diagnostics keyed only by an opaque `FileId`, so a consumer had no way to
/// locate them and collapsed every diagnostic onto the entry file. The E033
/// here lives wholly in `phone.ink`, so its resolved `path` must be `phone.ink`.
#[test]
fn warning_from_included_file_carries_its_path() {
    let files: HashMap<&str, &str> = HashMap::from([
        ("main.ink", "INCLUDE phone.ink\n-> reveal\n"),
        // `-> END` is terminal; the trailing content is unreachable → E033.
        ("phone.ink", "=== reveal ===\n-> END\nAnd we're off.\n"),
    ]);

    let output = compile_mem_with_warnings("main.ink", &files).unwrap();
    let e033 = output
        .warnings
        .iter()
        .find(|w| w.code.as_str() == "E033")
        .expect("expected an E033 warning from the unreachable line in phone.ink");
    assert_eq!(
        e033.path, "phone.ink",
        "E033 from phone.ink must be attributed to phone.ink, not the entry"
    );
}

#[test]
fn clean_compilation_has_no_warnings() {
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", "Hello, world!\n-> END\n")]);

    let output = compile_mem_with_warnings("main.ink", &files).unwrap();
    assert!(
        output.warnings.is_empty(),
        "expected no warnings for clean source, got: {:?}",
        output
            .warnings
            .iter()
            .map(|w| format!("[{}] {}", w.code.as_str(), w.message))
            .collect::<Vec<_>>()
    );
}

#[test]
fn glue_in_choice_body_emits_glue_opcode() {
    let source = "\
-> knot

=== knot
* [Yes]
    Yes considered. <>
* [No]
    No way. <>
- He seemed to know.
-> END
";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();
    let mut buf = String::new();
    brink_format::write_inkt(&data, &mut buf).unwrap();
    eprintln!("{buf}");
    assert!(
        buf.contains("glue"),
        "expected glue opcode in bytecode, got:\n{buf}"
    );
}

#[test]
fn glue_in_choice_body_runtime_joins_text() {
    let source = "\
-> knot

=== knot
* [Yes]
    Yes considered. <>
* [No]
    No way. <>
- He seemed to know.
-> END
";
    let files: HashMap<&str, &str> = HashMap::from([("main.ink", source)]);
    let data = compile_mem("main.ink", &files).unwrap();
    let (program, line_tables) = brink_runtime::link(&data).unwrap();
    let mut story = Story::<DotNetRng>::new(std::sync::Arc::new(program), line_tables);

    // First continue: should get choices
    let line = story.continue_single().unwrap();
    match &line {
        Step::Choices(choices) => {
            assert_eq!(choices.len(), 2);
            story.choose(0).unwrap(); // pick "Yes"
        }
        other => panic!("expected Choices, got: {other:?}"),
    }

    // Second continue: should get the glued text
    let line = story.continue_single().unwrap();
    let text = match &line {
        Step::Line(line) => line.text.clone(),
        other => panic!("expected text output, got: {other:?}"),
    };
    eprintln!("got text: {text:?}");
    assert!(
        text.contains("Yes considered. He seemed to know."),
        "expected glue to join choice text with gather text, got: {text:?}"
    );
}

// ── Malformed inline conditionals (regression for #44) ──────────────
//
// Per WritingWithInk.md and inkle's own Tests.cs, conditional *logic* and
// conditions-on-each-branch only exist in the multiline block form. inklecate
// rejects the inline forms below; brink currently compiles them and emits the
// source as story text (silent miscompile). These assert the reference-correct
// behaviour: a malformed inline conditional must be a compile error.

/// `{ cond: ~ statement }` — a logic statement inside an inline conditional.
/// Logic must live in a multiline block (`{ cond:\n    ~ ... \n}`), so the
/// inline form is invalid ink and must error.
#[test]
fn compile_error_inline_conditional_with_logic() {
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "VAR x = 0\n{ true: ~ x = 2 }\nValue {x}.\n-> END\n",
    )]);
    let err = compile_mem("main.ink", &files).expect_err(
        "an inline conditional containing a `~` logic statement is invalid ink \
         (logic belongs in a multiline block) and should be a compile error",
    );
    let codes = diagnostic_codes(&err);
    assert!(!codes.is_empty(), "expected a diagnostic, got: {codes:?}");
}

/// `{ c1: a | c2: b | else }` — conditions on each branch, inline. Multi-branch
/// switches with per-branch conditions only exist in the multiline block form
/// (`{ - c1: a\n  - c2: b\n  - else: c }`), so the inline pipe form is invalid
/// ink and must error.
///
#[test]
fn compile_error_inline_multi_branch_conditional() {
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "VAR n = 5\nIt is {n > 8: big|n > 4: medium|small}.\n-> END\n",
    )]);
    let err = compile_mem("main.ink", &files).expect_err(
        "an inline conditional with conditions on each branch is invalid ink \
         (multi-branch switches require the multiline block form) and should be \
         a compile error",
    );
    let codes = diagnostic_codes(&err);
    assert!(!codes.is_empty(), "expected a diagnostic, got: {codes:?}");
}

// ── Directive annotations (`#@local`) ───────────────────────────────

#[test]
fn local_directive_reaches_story_data() {
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "\
#@local
VAR mood = 0
VAR shared = 1
-> guard

== guard ==
#@local
Halt! # spoken
-> END

== plaza ==
Busy.
-> END
",
    )]);

    let story = compile_mem("main.ink", &files).unwrap();

    // The VAR bit lands on the right global and only that one.
    let name = |id: brink_format::NameId| story.name_table[id.0 as usize].as_str();
    let mood = story
        .variables
        .iter()
        .find(|v| name(v.name) == "mood")
        .unwrap();
    let shared = story
        .variables
        .iter()
        .find(|v| name(v.name) == "shared")
        .unwrap();
    assert!(mood.local, "#@local VAR carries the scope bit");
    assert!(!shared.local, "unmarked VAR stays World");

    // The knot bit lands on `guard` and only `guard`.
    let guard = story
        .containers
        .iter()
        .find(|c| c.name.is_some_and(|n| name(n) == "guard"))
        .unwrap();
    let plaza = story
        .containers
        .iter()
        .find(|c| c.name.is_some_and(|n| name(n) == "plaza"))
        .unwrap();
    assert!(guard.local, "#@local knot carries the scope bit");
    assert!(!plaza.local, "unmarked knot stays World");

    // Erasure: no `@local` text anywhere in the line tables, but the
    // plain `spoken` tag survives.
    let all_lines = format!("{:?}", story.line_tables);
    assert!(
        !all_lines.contains("@local"),
        "directives never reach runtime content"
    );
    assert!(all_lines.contains("spoken"), "plain tags survive");
}

/// `#@local` declares that a knot/stitch's counts are per-flow memory —
/// the compiler must set `CountingFlags::VISITS` on the marked container
/// (and the scope-owning containers in its subtree, i.e. a marked knot's
/// stitches) even when nothing in the ink reads the count. Without this,
/// the read-site optimization compiles counting out and there is nothing
/// to privatize (#496).
#[test]
fn local_directive_implies_visits_counting() {
    let files: HashMap<&str, &str> = HashMap::from([(
        "main.ink",
        "\
-> guard

== guard ==
#@local
Halt!
-> inner

= inner
Deeper.
-> END

== plaza ==
Busy.
-> nook

= nook
#@local
Quiet.
-> END
",
    )]);

    let story = compile_mem("main.ink", &files).unwrap();

    let name = |id: brink_format::NameId| story.name_table[id.0 as usize].as_str();
    let container = |wanted: &str| {
        story
            .containers
            .iter()
            .find(|c| c.name.is_some_and(|n| name(n) == wanted))
            .unwrap_or_else(|| {
                let names: Vec<_> = story
                    .containers
                    .iter()
                    .filter_map(|c| c.name.map(name))
                    .collect();
                panic!("container {wanted:?} not found; named containers: {names:?}")
            })
    };
    let visits = |wanted: &str| {
        container(wanted)
            .counting_flags
            .contains(brink_format::CountingFlags::VISITS)
    };

    // The marked knot: no read site anywhere, VISITS forced anyway.
    assert!(visits("guard"), "#@local knot implies VISITS");
    // Scope-owning child of the marked knot: covered by the subtree rule
    // (the runtime privatizes the whole definition subtree, so the
    // stitch's count must exist too).
    assert!(
        visits("guard.inner"),
        "stitch under a #@local knot implies VISITS"
    );
    // A marked stitch inside an unmarked knot: the stitch is forced...
    assert!(visits("plaza.nook"), "#@local stitch implies VISITS");
    // ...but the read-site optimization stays intact everywhere else.
    assert!(
        !visits("plaza"),
        "unmarked, unread knot keeps counting compiled out"
    );
}

// ── Native cross-file same-named shadow can never legitimately
//    compile (issue #1901) ──────────────────────────────────────────────
//
// #1901 asked whether `declared_fn_type`'s shadow guard (issue #1895,
// `crates/internal/brink-analyzer/src/signature.rs`) being an *index-wide*,
// unscoped check — "does a `Variable`/`Constant`/`ListItem` named `double`
// exist *anywhere in the project*", not "does one exist in a module this
// declaration can actually see" — can disagree with
// `lir::lower::decls::fold_path_ref`'s real, `ImportScope`-aware
// resolution in a way that is user-visible: an unrelated, non-importing
// file's same-named global suppressing the typing of a local bare-name fn
// value that lowering would actually still resolve to the local knot.
//
// It cannot, for two independent reasons. First: `lower_native::decl::
// {lower_var_decl, lower_const_decl, lower_flags_decl}` hard-code
// `visibility: None` for every native `VAR`/`CONST`/`LIST` — there is no
// annotation grammar that overrides it (unlike ink's `#@public`/
// `#@private` tags) — and a native file is unconditionally its own module
// (`brink_db::modules::native_module_path`, decision-log 2026-07-22:
// "Native module identity: pure function of the root-relative path;
// `FileId` never in `DefinitionId`"). So a `VAR`/`CONST`/`LIST` declared
// in one `.brink` file can *never* be legitimately referenced from
// another: `modules::check`'s `E087` (private-cross-module) fires
// unconditionally the moment resolution reaches it — confirmed below,
// where `unrelated.brink`'s `double` isn't even imported by `main.brink`,
// yet still poisons the bare-name reference (kind-priority —
// `Variable`/`Constant`/`ListItem` over `Knot` — is checked project-wide,
// ahead of module scope) and the whole compile fails on `E087` before
// `alias`'s type could ever matter.
//
// Second, independently of visibility: `resolve::lookup_by_name`'s own
// `lookup_by_name_direct` fast path (`crates/internal/brink-analyzer/src/
// resolve.rs:1194`, `if !multiple { return first_match; }`) returns the
// *sole* candidate of the requested kinds without ever consulting the
// `ImportScope` — so with `unrelated.brink`'s private `const double`
// present, a direct call `{double(3)}` still resolves to `main.brink`'s
// own `fn double` and compiles clean (only the *value* reference
// `{double}` hits the `Variable`/`Constant`/`ListItem`-over-`Knot`
// kind-priority ahead of that fast path and errors `E087`). Scoping that
// fast path for native is a plausible standalone correctness change that
// would remove this second trigger with no publicity mechanism involved —
// tracked separately, not attempted here.
//
// Every case where the shadow guard's project-wide scan finds a
// same-named global in a *different* file is exactly the first case
// above: the compile fails outright, so `Sig::value_ty`'s imprecision
// (`Unknown` instead of a real resolution) is unobservable — there is no
// successful `StoryData` for it to be wrong about. Combined with the
// same-file cases (`native_bare_name_shadowed_by_a_same_named_global_is_not_typed_as_a_fn_value`
// for `Variable`/`Constant` and
// `native_bare_name_shadowed_by_a_same_named_list_item_is_not_typed_as_a_fn_value`
// for `ListItem`, both above — the latter added after review found the
// guard's original `ListItem` arm was dead code for a bare-name reference,
// since list items are indexed under their qualified `List.Item` name and
// the guard now also runs `lookup_list_item_bare`), this closes #1901's
// own question empirically: the guard cannot disagree with lowering in
// any project that compiles.
//
// If native `VAR`/`CONST`/`LIST` ever gain a real publicity mechanism, or
// `lookup_by_name_direct`'s fast path becomes `ImportScope`-aware, this
// test starts failing (the cross-file reference would newly succeed) —
// that is the signal to revisit `declared_fn_type` and thread a real
// resolution map through `signature()`, the fix #1901 itself declined to
// build pre-emptively.
#[test]
fn native_cross_file_global_shadow_of_a_fn_value_reference_fails_to_compile() {
    let dir = std::env::temp_dir().join(format!(
        "brink-compiler-native-1901-cross-file-shadow-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("main.brink"),
        "fn double(x: int): int {\n\
         \x20 return x * 2;\n}\n\
         fn total(n: int): int {\n\
         \x20 return n + 1;\n}\n\
         var alias = double\n\
         flow main() {\n  Val: {total(alias)} -> END\n}\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("unrelated.brink"),
        "const double = \"unrelated shadow\"\n",
    )
    .unwrap();
    let result = brink_compiler::compile_path_with_options(
        &dir.join("main.brink"),
        brink_compiler::AnalysisOptions {
            dialect: brink_compiler::Dialect::Brink,
            types: Some(brink_compiler::TypePolicy::Strict),
            ..brink_compiler::AnalysisOptions::default()
        },
    );
    std::fs::remove_dir_all(&dir).ok();
    let err = result.expect_err(
        "an unrelated file's same-named global must never be a legitimate reference target",
    );
    let brink_compiler::CompileError::Diagnostics(diags) = &err else {
        panic!("expected a Diagnostics compile error, got: {err:?}");
    };
    assert_eq!(
        diags.iter().map(|d| d.code).collect::<Vec<_>>(),
        vec![brink_ir::DiagnosticCode::E087],
        "expected the cross-module privacy gate alone, got: {diags:?}"
    );
}