asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
//! Runtime builder, handles, and configuration.
//!
//! This module provides [`RuntimeBuilder`] for constructing an Asupersync runtime
//! with customizable threading, scheduling, and deadline monitoring. The builder
//! follows a move-based fluent pattern where each method consumes `self` and
//! returns `Self`, enabling natural chaining.
//!
//! # Quick Start
//!
//! ```ignore
//! use asupersync::runtime::RuntimeBuilder;
//!
//! // Minimal — uses all defaults (available parallelism, 128 poll budget, etc.)
//! let runtime = RuntimeBuilder::new().build()?;
//!
//! runtime.block_on(async {
//!     println!("Hello from asupersync!");
//! });
//! ```
//!
//! # Common Configurations
//!
//! ## High-Throughput Server
//!
//! ```ignore
//! let runtime = RuntimeBuilder::high_throughput()
//!     .blocking_threads(4, 256)
//!     .build()?;
//! ```
//!
//! ## Low-Latency Application
//!
//! ```ignore
//! let runtime = RuntimeBuilder::low_latency()
//!     .worker_threads(2)
//!     .build()?;
//! ```
//!
//! ## Single-Threaded (Phase 0 / Testing)
//!
//! ```ignore
//! let runtime = RuntimeBuilder::current_thread().build()?;
//! ```
//!
//! ## Browser/WASM Status
//!
//! Browser-safe profiles can validate semantic-core closure on `wasm32`, and
//! this module now exposes a preview public browser bootstrap path through
//! [`RuntimeBuilder::browser`]. The preview surface is dispatcher-backed and
//! truthful about the current execution ladder: supported hosts receive a
//! browser runtime handle, while unsupported hosts fail closed with structured
//! diagnostics instead of pretending native-thread parity already exists.
//! Runtime startup still routes through an explicit `RuntimeHostServices`
//! seam, and the native std-thread host implementation remains the only
//! shipped full runtime host. Browser-facing guidance should continue to rely
//! on the repository-maintained Rust/WASM fixture and the shipped JS/TS Browser
//! Edition packages when broad end-user parity is required.
//!
//! ## With Deadline Monitoring
//!
//! ```ignore
//! use std::time::Duration;
//!
//! let runtime = RuntimeBuilder::new()
//!     .deadline_monitoring(|m| {
//!         m.enabled(true)
//!          .check_interval(Duration::from_secs(1))
//!          .warning_threshold_fraction(0.2)
//!          .checkpoint_timeout(Duration::from_secs(30))
//!     })
//!     .build()?;
//! ```
//!
//! ## With Environment Variable Overrides
//!
//! The builder supports 12-factor app style environment variable configuration.
//! Environment variables override defaults but are themselves overridden by
//! programmatic settings applied after the call:
//!
//! ```ignore
//! // ASUPERSYNC_WORKER_THREADS=8 in environment
//! let runtime = RuntimeBuilder::new()
//!     .with_env_overrides()?     // reads env vars
//!     .steal_batch_size(32)      // programmatic override (highest priority)
//!     .build()?;
//!
//! assert_eq!(runtime.config().worker_threads, 8);  // from env
//! assert_eq!(runtime.config().steal_batch_size, 32); // from code
//! ```
//!
//! See [`env_config`](super::env_config) for the full list of supported variables.
//!
//! ## With TOML Config File (requires `config-file` feature)
//!
//! ```ignore
//! let runtime = RuntimeBuilder::from_toml("config/runtime.toml")?
//!     .with_env_overrides()?   // env vars override file values
//!     .worker_threads(4)       // programmatic override (highest priority)
//!     .build()?;
//! ```
//!
//! # Configuration Precedence
//!
//! When multiple sources set the same field, the highest-priority source wins:
//!
//! 1. **Programmatic** — `builder.worker_threads(4)` (highest)
//! 2. **Environment** — `ASUPERSYNC_WORKER_THREADS=8`
//! 3. **Config file** — `worker_threads = 16` in TOML
//! 4. **Defaults** — `RuntimeConfig::default()` (lowest)
//!
//! # Configuration Reference
//!
//! | Method | Default | Description |
//! |--------|---------|-------------|
//! | [`worker_threads`](RuntimeBuilder::worker_threads) | available parallelism | Number of async worker threads |
//! | [`thread_stack_size`](RuntimeBuilder::thread_stack_size) | 2 MiB | Stack size per worker |
//! | [`thread_name_prefix`](RuntimeBuilder::thread_name_prefix) | `"asupersync-worker"` | Thread name prefix |
//! | [`global_queue_limit`](RuntimeBuilder::global_queue_limit) | 0 (unbounded) | Global queue depth |
//! | [`steal_batch_size`](RuntimeBuilder::steal_batch_size) | 16 | Work-stealing batch size |
//! | [`blocking_threads`](RuntimeBuilder::blocking_threads) | 0, 0 | Blocking pool min/max |
//! | [`enable_parking`](RuntimeBuilder::enable_parking) | true | Park idle workers |
//! | [`poll_budget`](RuntimeBuilder::poll_budget) | 128 | Polls before cooperative yield |
//! | [`browser_ready_handoff_limit`](RuntimeBuilder::browser_ready_handoff_limit) | 0 (disabled) | Max ready dispatch burst before host-turn handoff |
//! | [`browser_worker_offload`](RuntimeBuilder::browser_worker_offload) | disabled | Browser worker offload policy contract |
//! | [`cancel_lane_max_streak`](RuntimeBuilder::cancel_lane_max_streak) | 16 | Max consecutive cancel dispatches |
//! | [`enable_adaptive_cancel_streak`](RuntimeBuilder::enable_adaptive_cancel_streak) | true | Enable regret-bounded adaptive cancel streak |
//! | [`adaptive_cancel_streak_epoch_steps`](RuntimeBuilder::adaptive_cancel_streak_epoch_steps) | 128 | Dispatches per adaptive epoch |
//! | [`root_region_limits`](RuntimeBuilder::root_region_limits) | None | Admission limits for the root region |
//! | [`observability`](RuntimeBuilder::observability) | None | Attach structured logging collectors |
//!
//! # Error Handling
//!
//! The `build()` method returns `Result<Runtime, Error>`. Configuration values
//! are normalized (e.g., `worker_threads = 0` becomes 1) rather than rejected,
//! so `build()` rarely fails in practice:
//!
//! ```ignore
//! match RuntimeBuilder::new().build() {
//!     Ok(runtime) => { /* ready */ }
//!     Err(e) => eprintln!("runtime build failed: {e}"),
//! }
//! ```
//!
//! Environment variable and config file errors are returned eagerly:
//!
//! ```ignore
//! // Returns Err immediately if ASUPERSYNC_WORKER_THREADS contains "abc"
//! let builder = RuntimeBuilder::new().with_env_overrides()?;
//! ```

use crate::error::Error;
use crate::observability::ObservabilityConfig;
use crate::observability::metrics::MetricsProvider;
use crate::record::RegionLimits;
use crate::runtime::RuntimeState;
use crate::runtime::SpawnError;
use crate::runtime::config::RuntimeConfig;
use crate::runtime::deadline_monitor::{
    AdaptiveDeadlineConfig, DeadlineTaskSnapshot, DeadlineWarning, MonitorConfig,
    default_warning_handler,
};
use crate::runtime::io_driver::IoDriverHandle;
use crate::runtime::reactor::Reactor;
use crate::runtime::scheduler::{ThreeLaneScheduler, ThreeLaneWorker};
use crate::time::TimerDriverHandle;
use crate::trace::distributed::LogicalClockMode;
use crate::types::{Budget, CancelAttributionConfig};
use crate::util::EntropySource;
#[cfg(target_arch = "wasm32")]
use js_sys::{Reflect, global};
use parking_lot::{Mutex, MutexGuard};
use std::cell::RefCell;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, Weak};
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use thiserror::Error as ThisError;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;

use crate::types::{
    WasmAbiOutcomeEnvelope, WasmAbiVersion, WasmAbortPropagationMode, WasmDispatchError,
    WasmDispatcherDiagnostics, WasmExportDispatcher, WasmHandleRef, WasmScopeEnterBuilder,
};

// ---------------------------------------------------------------------------
// Thread-local RuntimeHandle (issue #21)
// ---------------------------------------------------------------------------
//
// When `Runtime::block_on` enters the poll loop, it installs a thread-local
// `RuntimeHandle` so that futures running inside `block_on` can discover the
// runtime and spawn tasks onto the real scheduler via
// `Runtime::current_handle()`.

thread_local! {
    static CURRENT_RUNTIME_HANDLE: RefCell<Option<RuntimeHandle>> = const { RefCell::new(None) };
}

/// RAII guard that installs (and restores) a thread-local [`RuntimeHandle`].
struct ScopedRuntimeHandle {
    prev: Option<RuntimeHandle>,
}

impl ScopedRuntimeHandle {
    fn new(handle: RuntimeHandle) -> Self {
        let prev = CURRENT_RUNTIME_HANDLE.with(|cell| cell.replace(Some(handle)));
        Self { prev }
    }
}

impl Drop for ScopedRuntimeHandle {
    fn drop(&mut self) {
        let prev = self.prev.take();
        let _ = CURRENT_RUNTIME_HANDLE.try_with(|cell| {
            *cell.borrow_mut() = prev;
        });
    }
}

#[allow(dead_code)] // Used on wasm32 target
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RuntimeHostServicesKind {
    NativeStdThread,
}

#[allow(dead_code)] // Used on wasm32 target
impl RuntimeHostServicesKind {
    const fn as_str(self) -> &'static str {
        match self {
            Self::NativeStdThread => "native-std-thread",
        }
    }
}

#[allow(dead_code)] // Used on wasm32 target
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct BrowserHostServicesContract {
    required_capabilities: &'static [&'static str],
}

#[allow(dead_code)] // Used on wasm32 target
impl BrowserHostServicesContract {
    const V1: Self = Self {
        required_capabilities: &[
            "host-turn wakeups",
            "worker bootstrap hooks",
            "timer/deadline driving",
            "lane-health callbacks",
        ],
    };

    fn diagnostic_requirements(self) -> &'static str {
        if self
            .required_capabilities
            .contains(&"lane-health callbacks")
        {
            "host-turn wakeups, worker bootstrap hooks, timer/deadline driving, and lane-health callbacks for threadless startup"
        } else {
            "browser host-services contract requirements"
        }
    }
}

struct DeadlineMonitorHostService {
    shutdown: Option<Arc<std::sync::atomic::AtomicBool>>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl DeadlineMonitorHostService {
    const fn disabled() -> Self {
        Self {
            shutdown: None,
            thread: None,
        }
    }
}

trait RuntimeHostServices: Send + Sync {
    fn kind(&self) -> RuntimeHostServicesKind;

    fn browser_contract(&self) -> BrowserHostServicesContract {
        BrowserHostServicesContract::V1
    }

    fn spawn_workers(
        &self,
        runtime: &Arc<RuntimeInner>,
        workers: Vec<ThreeLaneWorker>,
    ) -> io::Result<Vec<std::thread::JoinHandle<()>>>;

    fn start_deadline_monitor(
        &self,
        config: &RuntimeConfig,
        state: &Arc<crate::sync::ContendedMutex<RuntimeState>>,
    ) -> DeadlineMonitorHostService;
}

#[derive(Default)]
struct NativeThreadHostServices;

impl NativeThreadHostServices {
    const fn new() -> Self {
        Self
    }

    fn spawn_worker_threads(
        runtime: &Arc<RuntimeInner>,
        workers: Vec<ThreeLaneWorker>,
    ) -> io::Result<Vec<std::thread::JoinHandle<()>>> {
        let mut worker_threads: Vec<std::thread::JoinHandle<()>> = Vec::new();
        if runtime.config.worker_threads == 0 {
            return Ok(worker_threads);
        }

        for worker in workers {
            let name = {
                let id = worker.id;
                format!("{}-{id}", runtime.config.thread_name_prefix)
            };
            let runtime_handle = RuntimeHandle::weak(runtime);
            let on_start = runtime.config.on_thread_start.clone();
            let on_stop = runtime.config.on_thread_stop.clone();
            let mut builder = std::thread::Builder::new().name(name);
            if runtime.config.thread_stack_size > 0 {
                builder = builder.stack_size(runtime.config.thread_stack_size);
            }
            let handle = builder
                .spawn(move || {
                    let _guard = ScopedRuntimeHandle::new(runtime_handle);
                    if let Some(callback) = on_start.as_ref() {
                        callback();
                    }
                    let mut worker = worker;
                    worker.run_loop();
                    if let Some(callback) = on_stop.as_ref() {
                        callback();
                    }
                })
                .map_err(|e| {
                    // Signal already-running workers to exit their run loops,
                    // then join them so they don't leak.
                    runtime.scheduler.shutdown();
                    while let Some(handle) = worker_threads.pop() {
                        let _ = handle.join();
                    }
                    io::Error::other(format!("failed to spawn worker thread: {e}"))
                })?;
            worker_threads.push(handle);
        }

        Ok(worker_threads)
    }

    fn start_deadline_monitor(
        config: &RuntimeConfig,
        state: &Arc<crate::sync::ContendedMutex<RuntimeState>>,
    ) -> DeadlineMonitorHostService {
        use crate::runtime::deadline_monitor::DeadlineMonitor;
        use std::sync::atomic::AtomicBool;

        let monitor_config = match config.deadline_monitor {
            Some(ref mc) if mc.enabled => mc,
            _ => return DeadlineMonitorHostService::disabled(),
        };

        let dm_shutdown = Arc::new(AtomicBool::new(false));
        let dm_shutdown_clone = Arc::clone(&dm_shutdown);
        let dm_state = Arc::clone(state);
        let check_interval = monitor_config.check_interval;
        let mut monitor = DeadlineMonitor::new(monitor_config.clone());
        if let Some(ref handler) = config.deadline_warning_handler {
            let handler = Arc::clone(handler);
            monitor.on_warning(move |w| handler(w));
        }
        monitor.set_metrics_provider(Arc::clone(&config.metrics_provider));

        let thread_name = format!("{}-deadline-monitor", config.thread_name_prefix);
        let thread = std::thread::Builder::new()
            .name(thread_name)
            .spawn(move || {
                while !dm_shutdown_clone.load(std::sync::atomic::Ordering::Relaxed) {
                    std::thread::sleep(check_interval);
                    if dm_shutdown_clone.load(std::sync::atomic::Ordering::Relaxed) {
                        break;
                    }
                    let guard = dm_state
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    let now = guard.now;
                    let tasks = guard
                        .tasks_iter()
                        .map(|(_, record)| DeadlineTaskSnapshot::from_task_record(record))
                        .collect::<Vec<_>>();
                    drop(guard);
                    monitor.check_snapshots(now, tasks);
                }
            })
            .ok();

        DeadlineMonitorHostService {
            shutdown: Some(dm_shutdown),
            thread,
        }
    }
}

impl RuntimeHostServices for NativeThreadHostServices {
    fn kind(&self) -> RuntimeHostServicesKind {
        RuntimeHostServicesKind::NativeStdThread
    }

    fn spawn_workers(
        &self,
        runtime: &Arc<RuntimeInner>,
        workers: Vec<ThreeLaneWorker>,
    ) -> io::Result<Vec<std::thread::JoinHandle<()>>> {
        Self::spawn_worker_threads(runtime, workers)
    }

    fn start_deadline_monitor(
        &self,
        config: &RuntimeConfig,
        state: &Arc<crate::sync::ContendedMutex<RuntimeState>>,
    ) -> DeadlineMonitorHostService {
        Self::start_deadline_monitor(config, state)
    }
}

fn default_runtime_host_services() -> Arc<dyn RuntimeHostServices> {
    Arc::new(NativeThreadHostServices::new())
}

#[allow(dead_code)] // Used on wasm32 target
fn unsupported_browser_bootstrap_message(host_services: &dyn RuntimeHostServices) -> String {
    let contract = host_services.browser_contract();
    format!(
        "RuntimeBuilder browser bootstrap is not yet supported on wasm browser profiles; \
         startup now routes through the RuntimeHostServices seam, but this build still only \
         ships the {} host implementation. A future browser host must provide {}. Use the \
         Browser Edition JS/TS bindings or the repository-maintained browser fixtures until \
         that browser host implementation lands.",
        host_services.kind().as_str(),
        contract.diagnostic_requirements(),
    )
}

/// Browser execution API capabilities used for runtime support diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserExecutionApiCapabilities {
    /// Whether `AbortController` is available.
    pub has_abort_controller: bool,
    /// Whether `fetch` is available.
    pub has_fetch: bool,
    /// Whether `WebAssembly` is available.
    pub has_webassembly: bool,
}

/// Browser DOM capabilities used for runtime support diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserDomCapabilities {
    /// Whether `document` is available.
    pub has_document: bool,
    /// Whether `window` is available.
    pub has_window: bool,
}

/// Browser storage capabilities used for runtime support diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserStorageCapabilities {
    /// Whether `indexedDB` is available.
    pub has_indexed_db: bool,
    /// Whether `localStorage` is available.
    pub has_local_storage: bool,
}

/// Browser transport capabilities used for runtime support diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserTransportCapabilities {
    /// Whether `WebSocket` is available.
    pub has_web_socket: bool,
    /// Whether `WebTransport` is available.
    pub has_web_transport: bool,
}

/// Browser capability snapshot used for runtime support diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserCapabilitySnapshot {
    /// Execution-related browser APIs.
    pub execution_api: BrowserExecutionApiCapabilities,
    /// DOM-related capabilities.
    pub dom: BrowserDomCapabilities,
    /// Storage-related capabilities.
    pub storage: BrowserStorageCapabilities,
    /// Transport-related capabilities.
    pub transport: BrowserTransportCapabilities,
}

/// Browser runtime support classes aligned with the Browser Edition control plane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserRuntimeSupportClass {
    /// The current host context truthfully supports direct runtime execution.
    DirectRuntimeSupported,
    /// The current host context does not support a direct browser runtime lane.
    Unsupported,
}

impl BrowserRuntimeSupportClass {
    /// Stable string label aligned with the Browser Edition package surface.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DirectRuntimeSupported => "direct_runtime_supported",
            Self::Unsupported => "unsupported",
        }
    }
}

/// Browser runtime context classification aligned with the Browser Edition package surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserRuntimeContext {
    /// Browser main-thread context (`window` + `document`).
    BrowserMainThread,
    /// Dedicated worker context.
    DedicatedWorker,
    /// Service worker context.
    ServiceWorker,
    /// Shared worker context.
    SharedWorker,
    /// Anything outside the currently classified browser runtime contexts.
    Unknown,
}

impl BrowserRuntimeContext {
    /// Stable string label aligned with the Browser Edition package surface.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BrowserMainThread => "browser_main_thread",
            Self::DedicatedWorker => "dedicated_worker",
            Self::ServiceWorker => "service_worker",
            Self::SharedWorker => "shared_worker",
            Self::Unknown => "unknown",
        }
    }
}

/// Browser runtime support reasons aligned with the Browser Edition diagnostics model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserRuntimeSupportReason {
    /// `globalThis` or an equivalent global object is missing.
    MissingGlobalThis,
    /// The current context is a service worker, which is not yet a shipped lane.
    ServiceWorkerNotYetShipped,
    /// The current context is a shared worker, which is not yet a shipped lane.
    SharedWorkerNotYetShipped,
    /// The current context is not a shipped direct-runtime browser role.
    UnsupportedRuntimeContext,
    /// `WebAssembly` is unavailable in the current host.
    MissingWebAssembly,
    /// The current context is supported.
    Supported,
}

/// Runtime support diagnostics for the Rust-authored browser surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserRuntimeSupportDiagnostics {
    /// Whether the current host truthfully supports direct runtime execution.
    pub supported: bool,
    /// High-level support class.
    pub support_class: BrowserRuntimeSupportClass,
    /// Browser runtime context classification.
    pub runtime_context: BrowserRuntimeContext,
    /// Support reason code.
    pub reason: BrowserRuntimeSupportReason,
    /// Human-readable explanation.
    pub message: String,
    /// Operator guidance for this support decision.
    pub guidance: Vec<String>,
    /// Capability snapshot used to reach the decision.
    pub capabilities: BrowserCapabilitySnapshot,
}

const BROWSER_SERVICE_WORKER_BROKER_CONTRACT_ID: &str = "wasm-service-worker-broker-contract-v1";
const BROWSER_SERVICE_WORKER_BROKER_LANE: &str = "lane.browser.service_worker.broker";
const BROWSER_SHARED_WORKER_COORDINATOR_CONTRACT_ID: &str =
    "wasm-shared-worker-tenancy-lifecycle-v1";
const BROWSER_SHARED_WORKER_COORDINATOR_LANE: &str = "lane.browser.shared_worker.coordinator";

/// Truthful fallback targets for bounded browser worker helper surfaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserWorkerFallbackTarget {
    /// Downgrade to the dedicated-worker direct-runtime lane.
    DedicatedWorkerDirectRuntime,
    /// Downgrade to the browser main-thread direct-runtime lane.
    BrowserMainThreadDirectRuntime,
    /// Downgrade to an application-owned bridge-only fallback.
    BridgeFallback,
}

impl BrowserWorkerFallbackTarget {
    /// Stable string label aligned with the Browser Edition package surface.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DedicatedWorkerDirectRuntime => "lane.browser.dedicated_worker.direct_runtime",
            Self::BrowserMainThreadDirectRuntime => "lane.browser.main_thread.direct_runtime",
            Self::BridgeFallback => "bridge_fallback",
        }
    }

    const fn fallback_lane_id(self) -> Option<BrowserExecutionLane> {
        match self {
            Self::DedicatedWorkerDirectRuntime => {
                Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime)
            }
            Self::BrowserMainThreadDirectRuntime => {
                Some(BrowserExecutionLane::BrowserMainThreadDirectRuntime)
            }
            Self::BridgeFallback => None,
        }
    }
}

/// Reason codes for service-worker broker host-class preflight diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserServiceWorkerBrokerSupportReason {
    /// The current host supports the bounded broker surface.
    Supported,
    /// The current host is not a service-worker-like host.
    ServiceWorkerApiMissing,
    /// The current host lacks the durable store required by the default restartable profile.
    DurableStoreUnavailableForRestartableProfile,
}

impl BrowserServiceWorkerBrokerSupportReason {
    /// Stable string label aligned with the Browser Edition package surface.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Supported => "supported",
            Self::ServiceWorkerApiMissing => "service_worker_api_missing",
            Self::DurableStoreUnavailableForRestartableProfile => {
                "durable_store_unavailable_for_restartable_profile"
            }
        }
    }
}

/// Host-class preflight diagnostics for the bounded service-worker broker surface.
///
/// Unlike the JS helper, this Rust preview surface does not try to mirror every
/// registration/admission field. It only reports the host-class facts that the
/// Rust browser builder can inspect truthfully without widening the shipped
/// direct-runtime contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserServiceWorkerBrokerSupportDiagnostics {
    /// Whether the current host satisfies the bounded broker preflight.
    pub supported: bool,
    /// Stable bounded broker contract id.
    pub contract_id: &'static str,
    /// Stable bounded broker lane id.
    pub requested_lane: &'static str,
    /// Truthful first downgrade target when broker admission is unavailable.
    pub fallback_target: BrowserWorkerFallbackTarget,
    /// Truthful first downgrade lane, if it maps to a direct-runtime lane.
    pub fallback_lane_id: Option<BrowserExecutionLane>,
    /// Ordered downgrade targets for this helper surface.
    pub downgrade_order: Vec<BrowserWorkerFallbackTarget>,
    /// Browser host-role classification.
    pub host_role: BrowserExecutionHostRole,
    /// Browser runtime context classification.
    pub runtime_context: BrowserRuntimeContext,
    /// Host-class support reason.
    pub reason: BrowserServiceWorkerBrokerSupportReason,
    /// Human-readable explanation.
    pub message: String,
    /// Operator guidance.
    pub guidance: Vec<String>,
    /// Underlying direct-runtime support reason for the current host.
    pub direct_runtime_reason: BrowserRuntimeSupportReason,
    /// Underlying execution-ladder reason for the current host.
    pub direct_execution_reason_code: BrowserExecutionReasonCode,
    /// Underlying runtime-support diagnostics for the current host.
    pub runtime_support: BrowserRuntimeSupportDiagnostics,
    /// Capability snapshot copied from runtime support diagnostics.
    pub capabilities: BrowserCapabilitySnapshot,
}

/// Reason codes for shared-worker coordinator caller-side preflight diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserSharedWorkerCoordinatorSupportReason {
    /// The current caller host supports the bounded coordinator surface.
    Supported,
    /// The current caller host cannot attach to the bounded coordinator surface.
    SharedWorkerApiMissing,
}

impl BrowserSharedWorkerCoordinatorSupportReason {
    /// Stable string label aligned with the Browser Edition package surface.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Supported => "supported",
            Self::SharedWorkerApiMissing => "shared_worker_api_missing",
        }
    }
}

/// Host-class preflight diagnostics for the bounded shared-worker coordinator surface.
///
/// This remains intentionally narrower than the JS helper. The Rust preview
/// surface only reports whether the current caller host is a truthful place to
/// start a bounded coordinator attach flow; full same-origin script resolution
/// and admission checks remain on the JS helper surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserSharedWorkerCoordinatorSupportDiagnostics {
    /// Whether the current caller host satisfies the bounded coordinator preflight.
    pub supported: bool,
    /// Stable bounded coordinator contract id.
    pub contract_id: &'static str,
    /// Stable bounded coordinator lane id.
    pub requested_lane: &'static str,
    /// Truthful first downgrade target when coordinator attach is unavailable.
    pub fallback_target: BrowserWorkerFallbackTarget,
    /// Truthful first downgrade lane, if it maps to a direct-runtime lane.
    pub fallback_lane_id: Option<BrowserExecutionLane>,
    /// Ordered downgrade targets for this helper surface.
    pub downgrade_order: Vec<BrowserWorkerFallbackTarget>,
    /// Browser host-role classification for the caller host.
    pub host_role: BrowserExecutionHostRole,
    /// Browser runtime context classification for the caller host.
    pub runtime_context: BrowserRuntimeContext,
    /// Caller-side support reason.
    pub reason: BrowserSharedWorkerCoordinatorSupportReason,
    /// Human-readable explanation.
    pub message: String,
    /// Operator guidance.
    pub guidance: Vec<String>,
    /// Direct-runtime reason for the shared-worker host itself.
    pub direct_runtime_reason: BrowserRuntimeSupportReason,
    /// Execution-ladder reason for the shared-worker host itself.
    pub direct_execution_reason_code: BrowserExecutionReasonCode,
    /// Underlying runtime-support diagnostics for the caller host.
    pub runtime_support: BrowserRuntimeSupportDiagnostics,
    /// Capability snapshot copied from runtime support diagnostics.
    pub capabilities: BrowserCapabilitySnapshot,
}

/// Browser execution host-role classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserExecutionHostRole {
    /// Browser main-thread entrypoint.
    BrowserMainThread,
    /// Dedicated worker entrypoint.
    DedicatedWorker,
    /// Service worker entrypoint.
    ServiceWorker,
    /// Shared worker entrypoint.
    SharedWorker,
    /// Anything else, including non-browser hosts.
    NonBrowserOrUnknown,
}

impl BrowserExecutionHostRole {
    /// Stable string label aligned with the shared execution-ladder contract.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BrowserMainThread => "browser_main_thread",
            Self::DedicatedWorker => "dedicated_worker",
            Self::ServiceWorker => "service_worker",
            Self::SharedWorker => "shared_worker",
            Self::NonBrowserOrUnknown => "non_browser_or_unknown",
        }
    }
}

/// Browser execution lane identifiers aligned with the shared execution ladder contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserExecutionLane {
    /// Browser main-thread direct-runtime lane.
    BrowserMainThreadDirectRuntime,
    /// Dedicated-worker direct-runtime lane.
    DedicatedWorkerDirectRuntime,
    /// Terminal fail-closed lane.
    Unsupported,
}

impl BrowserExecutionLane {
    /// Stable lane identifier aligned with the shared execution-ladder contract.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BrowserMainThreadDirectRuntime => "lane.browser.main_thread.direct_runtime",
            Self::DedicatedWorkerDirectRuntime => "lane.browser.dedicated_worker.direct_runtime",
            Self::Unsupported => "lane.unsupported",
        }
    }

    const fn lane_kind(self) -> BrowserExecutionLaneKind {
        match self {
            Self::Unsupported => BrowserExecutionLaneKind::Unsupported,
            Self::BrowserMainThreadDirectRuntime | Self::DedicatedWorkerDirectRuntime => {
                BrowserExecutionLaneKind::DirectRuntime
            }
        }
    }

    const fn lane_rank(self) -> u16 {
        match self {
            Self::BrowserMainThreadDirectRuntime => 10,
            Self::DedicatedWorkerDirectRuntime => 20,
            Self::Unsupported => 99,
        }
    }

    const fn fallback_lane(self) -> Option<Self> {
        match self {
            Self::Unsupported => None,
            Self::BrowserMainThreadDirectRuntime | Self::DedicatedWorkerDirectRuntime => {
                Some(Self::Unsupported)
            }
        }
    }
}

/// Browser execution lane kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserExecutionLaneKind {
    /// Direct browser runtime execution.
    DirectRuntime,
    /// Terminal fail-closed lane.
    Unsupported,
}

/// Browser execution reason codes aligned with the shared ladder semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserExecutionReasonCode {
    /// The selected lane is directly supported.
    Supported,
    /// The candidate lane does not match the current host role.
    CandidateHostRoleMismatch,
    /// The candidate lane matches the host role but prerequisites are missing.
    CandidatePrerequisiteMissing,
    /// The current context is a service worker and that lane is not yet shipped.
    ServiceWorkerDirectRuntimeNotShipped,
    /// The current context is a shared worker and that lane is not yet shipped.
    SharedWorkerDirectRuntimeNotShipped,
    /// `globalThis` is unavailable.
    MissingGlobalThis,
    /// `WebAssembly` is unavailable.
    MissingWebAssembly,
    /// The runtime context is unsupported.
    UnsupportedRuntimeContext,
    /// The current host is not a browser runtime.
    NonBrowserRuntime,
}

impl BrowserExecutionReasonCode {
    /// Stable string label aligned with the shared execution-ladder contract.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Supported => "supported",
            Self::CandidateHostRoleMismatch => "candidate_host_role_mismatch",
            Self::CandidatePrerequisiteMissing => "candidate_prerequisite_missing",
            Self::ServiceWorkerDirectRuntimeNotShipped => {
                "service_worker_direct_runtime_not_shipped"
            }
            Self::SharedWorkerDirectRuntimeNotShipped => "shared_worker_direct_runtime_not_shipped",
            Self::MissingGlobalThis => "missing_global_this",
            Self::MissingWebAssembly => "missing_webassembly",
            Self::UnsupportedRuntimeContext => "unsupported_runtime_context",
            Self::NonBrowserRuntime => "non_browser_runtime",
        }
    }
}

/// Candidate diagnostics for one browser execution lane.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserExecutionLaneCandidate {
    /// Candidate lane id.
    pub lane_id: BrowserExecutionLane,
    /// Candidate lane kind.
    pub lane_kind: BrowserExecutionLaneKind,
    /// Candidate lane rank.
    pub lane_rank: u16,
    /// Host role used for candidate evaluation.
    pub host_role: BrowserExecutionHostRole,
    /// Support class inherited from runtime support diagnostics.
    pub support_class: BrowserRuntimeSupportClass,
    /// Terminal fallback lane, if any.
    pub fallback_lane_id: Option<BrowserExecutionLane>,
    /// Whether the candidate is currently available.
    pub available: bool,
    /// Whether the candidate was selected.
    pub selected: bool,
    /// Candidate reason code.
    pub reason_code: BrowserExecutionReasonCode,
    /// Candidate explanation.
    pub message: String,
    /// Candidate operator guidance.
    pub guidance: Vec<String>,
}

/// Rust-side Browser Edition execution ladder diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowserExecutionLadderDiagnostics {
    /// Whether the selected lane is a supported direct-runtime lane.
    pub supported: bool,
    /// Operator-requested preferred lane, if any.
    pub preferred_lane: Option<BrowserExecutionLane>,
    /// Selected lane id.
    pub selected_lane: BrowserExecutionLane,
    /// Selected lane kind.
    pub lane_kind: BrowserExecutionLaneKind,
    /// Selected lane rank.
    pub lane_rank: u16,
    /// Host role classification.
    pub host_role: BrowserExecutionHostRole,
    /// Support class inherited from runtime support diagnostics.
    pub support_class: BrowserRuntimeSupportClass,
    /// Runtime context classification.
    pub runtime_context: BrowserRuntimeContext,
    /// Selected reason code.
    pub reason_code: BrowserExecutionReasonCode,
    /// Human-readable explanation.
    pub message: String,
    /// Operator guidance.
    pub guidance: Vec<String>,
    /// Terminal fallback lane, if any.
    pub fallback_lane_id: Option<BrowserExecutionLane>,
    /// Truthful lane downgrade order for the current host role.
    pub downgrade_order: Vec<BrowserExecutionLane>,
    /// Reproduction command for the maintained Rust browser fixture.
    pub repro_command: String,
    /// Candidate diagnostics across the ladder.
    pub candidates: Vec<BrowserExecutionLaneCandidate>,
    /// Underlying runtime support diagnostics.
    pub runtime_support: BrowserRuntimeSupportDiagnostics,
    /// Capability snapshot copied from runtime support diagnostics.
    pub capabilities: BrowserCapabilitySnapshot,
}

/// Synthetic or observed host snapshot used to inspect browser ladder behavior.
///
/// This lets external Rust callers and maintained fixtures exercise the
/// execution-ladder policy against a deterministic host snapshot without
/// widening runtime support claims or depending on browser-only globals.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BrowserExecutionProbe {
    /// Whether a browser-like `globalThis` object exists.
    pub has_global_this: bool,
    /// Runtime context classification associated with this host snapshot.
    pub runtime_context: BrowserRuntimeContext,
    /// Browser host role associated with this host snapshot.
    pub host_role: BrowserExecutionHostRole,
    /// Capability snapshot carried by the synthetic or observed host.
    pub capabilities: BrowserCapabilitySnapshot,
}

impl BrowserExecutionProbe {
    /// Creates a non-browser probe that truthfully fail-closes the ladder.
    #[must_use]
    pub const fn non_browser() -> Self {
        Self {
            has_global_this: false,
            runtime_context: BrowserRuntimeContext::Unknown,
            host_role: BrowserExecutionHostRole::NonBrowserOrUnknown,
            capabilities: BrowserCapabilitySnapshot {
                execution_api: BrowserExecutionApiCapabilities {
                    has_abort_controller: false,
                    has_fetch: false,
                    has_webassembly: false,
                },
                dom: BrowserDomCapabilities {
                    has_document: false,
                    has_window: false,
                },
                storage: BrowserStorageCapabilities {
                    has_indexed_db: false,
                    has_local_storage: false,
                },
                transport: BrowserTransportCapabilities {
                    has_web_socket: false,
                    has_web_transport: false,
                },
            },
        }
    }

    /// Creates a browser main-thread probe with a minimal direct-runtime shape.
    #[must_use]
    pub const fn browser_main_thread() -> Self {
        Self {
            has_global_this: true,
            runtime_context: BrowserRuntimeContext::BrowserMainThread,
            host_role: BrowserExecutionHostRole::BrowserMainThread,
            capabilities: BrowserCapabilitySnapshot {
                execution_api: BrowserExecutionApiCapabilities {
                    has_abort_controller: true,
                    has_fetch: true,
                    has_webassembly: true,
                },
                dom: BrowserDomCapabilities {
                    has_document: true,
                    has_window: true,
                },
                storage: browser_storage_capabilities_for_host_role(
                    BrowserExecutionHostRole::BrowserMainThread,
                ),
                transport: BrowserTransportCapabilities {
                    has_web_socket: true,
                    has_web_transport: false,
                },
            },
        }
    }

    /// Creates a dedicated-worker probe with a minimal direct-runtime shape.
    #[must_use]
    pub const fn dedicated_worker() -> Self {
        Self {
            has_global_this: true,
            runtime_context: BrowserRuntimeContext::DedicatedWorker,
            host_role: BrowserExecutionHostRole::DedicatedWorker,
            capabilities: BrowserCapabilitySnapshot {
                execution_api: BrowserExecutionApiCapabilities {
                    has_abort_controller: true,
                    has_fetch: true,
                    has_webassembly: true,
                },
                dom: BrowserDomCapabilities {
                    has_document: false,
                    has_window: false,
                },
                storage: browser_storage_capabilities_for_host_role(
                    BrowserExecutionHostRole::DedicatedWorker,
                ),
                transport: BrowserTransportCapabilities {
                    has_web_socket: true,
                    has_web_transport: false,
                },
            },
        }
    }

    /// Creates a service-worker probe that remains fail-closed for direct runtime.
    #[must_use]
    pub const fn service_worker() -> Self {
        Self {
            has_global_this: true,
            runtime_context: BrowserRuntimeContext::ServiceWorker,
            host_role: BrowserExecutionHostRole::ServiceWorker,
            capabilities: BrowserCapabilitySnapshot {
                execution_api: BrowserExecutionApiCapabilities {
                    has_abort_controller: true,
                    has_fetch: true,
                    has_webassembly: true,
                },
                dom: BrowserDomCapabilities {
                    has_document: false,
                    has_window: false,
                },
                storage: browser_storage_capabilities_for_host_role(
                    BrowserExecutionHostRole::ServiceWorker,
                ),
                transport: BrowserTransportCapabilities {
                    has_web_socket: true,
                    has_web_transport: false,
                },
            },
        }
    }

    /// Creates a shared-worker probe that remains fail-closed for direct runtime.
    #[must_use]
    pub const fn shared_worker() -> Self {
        Self {
            has_global_this: true,
            runtime_context: BrowserRuntimeContext::SharedWorker,
            host_role: BrowserExecutionHostRole::SharedWorker,
            capabilities: BrowserCapabilitySnapshot {
                execution_api: BrowserExecutionApiCapabilities {
                    has_abort_controller: true,
                    has_fetch: true,
                    has_webassembly: true,
                },
                dom: BrowserDomCapabilities {
                    has_document: false,
                    has_window: false,
                },
                storage: browser_storage_capabilities_for_host_role(
                    BrowserExecutionHostRole::SharedWorker,
                ),
                transport: BrowserTransportCapabilities {
                    has_web_socket: true,
                    has_web_transport: false,
                },
            },
        }
    }
}

const fn browser_storage_capabilities_for_host_role(
    host_role: BrowserExecutionHostRole,
) -> BrowserStorageCapabilities {
    match host_role {
        BrowserExecutionHostRole::BrowserMainThread => BrowserStorageCapabilities {
            has_indexed_db: true,
            has_local_storage: true,
        },
        BrowserExecutionHostRole::DedicatedWorker
        | BrowserExecutionHostRole::ServiceWorker
        | BrowserExecutionHostRole::SharedWorker => BrowserStorageCapabilities {
            has_indexed_db: true,
            has_local_storage: false,
        },
        BrowserExecutionHostRole::NonBrowserOrUnknown => BrowserStorageCapabilities {
            has_indexed_db: false,
            has_local_storage: false,
        },
    }
}

#[cfg(target_arch = "wasm32")]
fn browser_capability_snapshot(global_object: &JsValue) -> BrowserCapabilitySnapshot {
    BrowserCapabilitySnapshot {
        execution_api: BrowserExecutionApiCapabilities {
            has_abort_controller: browser_global_has(global_object, "AbortController"),
            has_fetch: browser_global_has(global_object, "fetch"),
            has_webassembly: browser_global_has(global_object, "WebAssembly"),
        },
        dom: BrowserDomCapabilities {
            has_document: browser_global_has(global_object, "document"),
            has_window: browser_global_has(global_object, "window"),
        },
        storage: BrowserStorageCapabilities {
            has_indexed_db: browser_global_has(global_object, "indexedDB"),
            has_local_storage: browser_global_has(global_object, "localStorage"),
        },
        transport: BrowserTransportCapabilities {
            has_web_socket: browser_global_has(global_object, "WebSocket"),
            has_web_transport: browser_global_has(global_object, "WebTransport"),
        },
    }
}

#[cfg(target_arch = "wasm32")]
fn browser_global_has(global_object: &JsValue, key: &str) -> bool {
    Reflect::has(global_object, &JsValue::from_str(key)).unwrap_or(false)
}

#[cfg(target_arch = "wasm32")]
fn browser_global_constructor_name(global_object: &JsValue) -> Option<String> {
    let constructor = Reflect::get(global_object, &JsValue::from_str("constructor")).ok()?;
    let name = Reflect::get(&constructor, &JsValue::from_str("name")).ok()?;
    name.as_string()
}

#[cfg(target_arch = "wasm32")]
fn detect_browser_execution_probe() -> BrowserExecutionProbe {
    let global_object = global();
    let has_global_this = global_object.is_object();
    let capabilities = browser_capability_snapshot(&global_object);
    let constructor_name = browser_global_constructor_name(&global_object);

    let host_role = match constructor_name.as_deref() {
        Some("ServiceWorkerGlobalScope") => BrowserExecutionHostRole::ServiceWorker,
        Some("SharedWorkerGlobalScope") => BrowserExecutionHostRole::SharedWorker,
        Some("DedicatedWorkerGlobalScope") => BrowserExecutionHostRole::DedicatedWorker,
        _ if capabilities.dom.has_window && capabilities.dom.has_document => {
            BrowserExecutionHostRole::BrowserMainThread
        }
        _ => BrowserExecutionHostRole::NonBrowserOrUnknown,
    };

    let runtime_context = match host_role {
        BrowserExecutionHostRole::BrowserMainThread => BrowserRuntimeContext::BrowserMainThread,
        BrowserExecutionHostRole::DedicatedWorker => BrowserRuntimeContext::DedicatedWorker,
        BrowserExecutionHostRole::ServiceWorker => BrowserRuntimeContext::ServiceWorker,
        BrowserExecutionHostRole::SharedWorker => BrowserRuntimeContext::SharedWorker,
        BrowserExecutionHostRole::NonBrowserOrUnknown => BrowserRuntimeContext::Unknown,
    };

    BrowserExecutionProbe {
        has_global_this,
        runtime_context,
        host_role,
        capabilities,
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn detect_browser_execution_probe() -> BrowserExecutionProbe {
    BrowserExecutionProbe::non_browser()
}

fn browser_runtime_support_diagnostics(
    probe: BrowserExecutionProbe,
    supported: bool,
    support_class: BrowserRuntimeSupportClass,
    reason: BrowserRuntimeSupportReason,
    message: &str,
    guidance: &[&str],
) -> BrowserRuntimeSupportDiagnostics {
    BrowserRuntimeSupportDiagnostics {
        supported,
        support_class,
        runtime_context: probe.runtime_context,
        reason,
        message: message.to_string(),
        guidance: guidance.iter().map(|entry| (*entry).to_string()).collect(),
        capabilities: probe.capabilities,
    }
}

fn browser_runtime_support_missing_global_this(
    probe: BrowserExecutionProbe,
) -> BrowserRuntimeSupportDiagnostics {
    browser_runtime_support_diagnostics(
        probe,
        false,
        BrowserRuntimeSupportClass::Unsupported,
        BrowserRuntimeSupportReason::MissingGlobalThis,
        "Rust Browser Edition runtime inspection could not find a browser global object.",
        &[
            "Run this inspection from a browser main-thread or dedicated-worker entrypoint.",
            "Use the maintained Rust browser fixture when validating browser support outside a browser host.",
        ],
    )
}

fn browser_runtime_support_not_yet_shipped(
    probe: BrowserExecutionProbe,
    reason: BrowserRuntimeSupportReason,
) -> BrowserRuntimeSupportDiagnostics {
    let (message, guidance) = match reason {
        BrowserRuntimeSupportReason::ServiceWorkerNotYetShipped => (
            "Rust Browser Edition does not yet ship a service-worker direct-runtime lane.",
            &[
                "Keep Rust Browser Edition runtime creation out of service-worker hosts; the direct-runtime lane is intentionally fail-closed today.",
                "Use the bounded service-worker broker helpers for registration, durable handoff, and fallback orchestration instead of widening the direct-runtime claim.",
            ][..],
        ),
        BrowserRuntimeSupportReason::SharedWorkerNotYetShipped => (
            "Rust Browser Edition does not yet ship a shared-worker direct-runtime lane.",
            &[
                "Keep Rust Browser Edition runtime creation out of shared-worker hosts; the direct-runtime lane is intentionally fail-closed today.",
                "Use the bounded shared-worker coordinator helpers from a browser main-thread or dedicated-worker caller instead of widening the direct-runtime claim.",
            ][..],
        ),
        BrowserRuntimeSupportReason::MissingGlobalThis
        | BrowserRuntimeSupportReason::UnsupportedRuntimeContext
        | BrowserRuntimeSupportReason::MissingWebAssembly
        | BrowserRuntimeSupportReason::Supported => {
            unreachable!("only not-yet-shipped reasons are valid here")
        }
    };
    browser_runtime_support_diagnostics(
        probe,
        false,
        BrowserRuntimeSupportClass::Unsupported,
        reason,
        message,
        guidance,
    )
}

fn browser_runtime_support_unsupported_context(
    probe: BrowserExecutionProbe,
) -> BrowserRuntimeSupportDiagnostics {
    browser_runtime_support_diagnostics(
        probe,
        false,
        BrowserRuntimeSupportClass::Unsupported,
        BrowserRuntimeSupportReason::UnsupportedRuntimeContext,
        "Rust Browser Edition inspection only recognizes browser main-thread and dedicated-worker direct-runtime contexts.",
        &[
            "Move the call into a browser main-thread or dedicated-worker entrypoint before expecting a direct runtime lane.",
        ],
    )
}

fn browser_runtime_support_missing_webassembly(
    probe: BrowserExecutionProbe,
) -> BrowserRuntimeSupportDiagnostics {
    browser_runtime_support_diagnostics(
        probe,
        false,
        BrowserRuntimeSupportClass::Unsupported,
        BrowserRuntimeSupportReason::MissingWebAssembly,
        "Rust Browser Edition runtime inspection found no WebAssembly support in the current host.",
        &[
            "Enable WebAssembly in the target browser/runtime before expecting a direct runtime lane.",
        ],
    )
}

fn browser_runtime_support_supported(
    probe: BrowserExecutionProbe,
) -> BrowserRuntimeSupportDiagnostics {
    let message = match probe.runtime_context {
        BrowserRuntimeContext::BrowserMainThread => {
            "Rust Browser Edition runtime inspection found a browser main-thread direct-runtime context."
        }
        BrowserRuntimeContext::DedicatedWorker => {
            "Rust Browser Edition runtime inspection found a dedicated-worker direct-runtime context."
        }
        BrowserRuntimeContext::ServiceWorker
        | BrowserRuntimeContext::SharedWorker
        | BrowserRuntimeContext::Unknown => {
            unreachable!(
                "supported browser runtime inspection requires a shipped direct-runtime context"
            )
        }
    };
    browser_runtime_support_diagnostics(
        probe,
        true,
        BrowserRuntimeSupportClass::DirectRuntimeSupported,
        BrowserRuntimeSupportReason::Supported,
        message,
        &[],
    )
}

fn browser_runtime_support_from_probe(
    probe: BrowserExecutionProbe,
) -> BrowserRuntimeSupportDiagnostics {
    if !probe.has_global_this {
        return browser_runtime_support_missing_global_this(probe);
    }

    match probe.host_role {
        BrowserExecutionHostRole::ServiceWorker => browser_runtime_support_not_yet_shipped(
            probe,
            BrowserRuntimeSupportReason::ServiceWorkerNotYetShipped,
        ),
        BrowserExecutionHostRole::SharedWorker => browser_runtime_support_not_yet_shipped(
            probe,
            BrowserRuntimeSupportReason::SharedWorkerNotYetShipped,
        ),
        BrowserExecutionHostRole::BrowserMainThread
        | BrowserExecutionHostRole::DedicatedWorker
        | BrowserExecutionHostRole::NonBrowserOrUnknown => {
            if probe.runtime_context == BrowserRuntimeContext::Unknown {
                return browser_runtime_support_unsupported_context(probe);
            }

            if !probe.capabilities.execution_api.has_webassembly {
                return browser_runtime_support_missing_webassembly(probe);
            }

            browser_runtime_support_supported(probe)
        }
    }
}

const fn browser_execution_direct_lane_for_host_role(
    host_role: BrowserExecutionHostRole,
) -> Option<BrowserExecutionLane> {
    match host_role {
        BrowserExecutionHostRole::BrowserMainThread => {
            Some(BrowserExecutionLane::BrowserMainThreadDirectRuntime)
        }
        BrowserExecutionHostRole::DedicatedWorker => {
            Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime)
        }
        BrowserExecutionHostRole::ServiceWorker
        | BrowserExecutionHostRole::SharedWorker
        | BrowserExecutionHostRole::NonBrowserOrUnknown => None,
    }
}

fn browser_execution_downgrade_order(
    host_role: BrowserExecutionHostRole,
) -> Vec<BrowserExecutionLane> {
    browser_execution_direct_lane_for_host_role(host_role).map_or_else(
        || vec![BrowserExecutionLane::Unsupported],
        |direct| vec![direct, BrowserExecutionLane::Unsupported],
    )
}

fn browser_execution_reason_from_support(
    support: &BrowserRuntimeSupportDiagnostics,
    host_role: BrowserExecutionHostRole,
) -> BrowserExecutionReasonCode {
    match support.reason {
        BrowserRuntimeSupportReason::MissingGlobalThis => {
            BrowserExecutionReasonCode::MissingGlobalThis
        }
        BrowserRuntimeSupportReason::ServiceWorkerNotYetShipped => {
            BrowserExecutionReasonCode::ServiceWorkerDirectRuntimeNotShipped
        }
        BrowserRuntimeSupportReason::SharedWorkerNotYetShipped => {
            BrowserExecutionReasonCode::SharedWorkerDirectRuntimeNotShipped
        }
        BrowserRuntimeSupportReason::UnsupportedRuntimeContext => {
            if host_role == BrowserExecutionHostRole::NonBrowserOrUnknown {
                BrowserExecutionReasonCode::NonBrowserRuntime
            } else {
                BrowserExecutionReasonCode::UnsupportedRuntimeContext
            }
        }
        BrowserRuntimeSupportReason::MissingWebAssembly => {
            BrowserExecutionReasonCode::MissingWebAssembly
        }
        BrowserRuntimeSupportReason::Supported => BrowserExecutionReasonCode::Supported,
    }
}

fn browser_execution_repro_command() -> String {
    "PATH=/usr/bin:$PATH bash scripts/validate_rust_browser_consumer.sh".to_string()
}

fn browser_execution_host_mismatch_message(lane_id: BrowserExecutionLane) -> String {
    match lane_id {
        BrowserExecutionLane::BrowserMainThreadDirectRuntime => {
            "lane.browser.main_thread.direct_runtime only applies when Rust Browser Edition is running on the browser main thread."
                .to_string()
        }
        BrowserExecutionLane::DedicatedWorkerDirectRuntime => {
            "lane.browser.dedicated_worker.direct_runtime only applies when Rust Browser Edition is already executing inside a dedicated worker."
                .to_string()
        }
        BrowserExecutionLane::Unsupported => {
            "lane.unsupported is the terminal fail-closed lane and is only selected after a truthful downgrade."
                .to_string()
        }
    }
}

fn browser_execution_host_mismatch_guidance(lane_id: BrowserExecutionLane) -> Vec<String> {
    match lane_id {
        BrowserExecutionLane::BrowserMainThreadDirectRuntime => vec![
            "Initialize the Rust browser surface from a browser main-thread entrypoint before pinning this lane."
                .to_string(),
        ],
        BrowserExecutionLane::DedicatedWorkerDirectRuntime => vec![
            "Move the Rust browser surface into a dedicated-worker entrypoint before pinning this lane."
                .to_string(),
        ],
        BrowserExecutionLane::Unsupported => vec![
            "Treat lane.unsupported as the terminal fail-closed lane when no truthful direct-runtime browser lane remains."
                .to_string(),
        ],
    }
}

fn browser_execution_missing_prerequisite_message(lane_id: BrowserExecutionLane) -> String {
    match lane_id {
        BrowserExecutionLane::Unsupported => {
            "lane.unsupported remains the terminal fail-closed fallback if the current direct-runtime lane loses truthful prerequisites."
                .to_string()
        }
        BrowserExecutionLane::BrowserMainThreadDirectRuntime
        | BrowserExecutionLane::DedicatedWorkerDirectRuntime => {
            format!(
                "{} matches the current host role but is unavailable until the required Browser Edition prerequisites are restored.",
                match lane_id {
                    BrowserExecutionLane::BrowserMainThreadDirectRuntime => {
                        "lane.browser.main_thread.direct_runtime"
                    }
                    BrowserExecutionLane::DedicatedWorkerDirectRuntime => {
                        "lane.browser.dedicated_worker.direct_runtime"
                    }
                    BrowserExecutionLane::Unsupported => unreachable!(),
                }
            )
        }
    }
}

fn browser_execution_missing_prerequisite_guidance(lane_id: BrowserExecutionLane) -> Vec<String> {
    match lane_id {
        BrowserExecutionLane::Unsupported => vec![
            "Expect Rust Browser Edition to demote here instead of pretending a direct-runtime lane exists when prerequisites disappear."
                .to_string(),
        ],
        BrowserExecutionLane::BrowserMainThreadDirectRuntime
        | BrowserExecutionLane::DedicatedWorkerDirectRuntime => vec![
            "Restore the missing Browser Edition prerequisites before pinning this lane again."
                .to_string(),
        ],
    }
}

fn browser_execution_preferred_lane_mismatch(
    preferred_lane: BrowserExecutionLane,
    selected_lane: BrowserExecutionLane,
    host_role: BrowserExecutionHostRole,
    direct_lane_for_host: Option<BrowserExecutionLane>,
    reason_code: BrowserExecutionReasonCode,
) -> (String, Vec<String>) {
    if preferred_lane != BrowserExecutionLane::Unsupported
        && Some(preferred_lane) != direct_lane_for_host
    {
        return (
            format!(
                "Preferred lane {} is not truthful for host role {}, so Rust Browser Edition stayed on {}.",
                preferred_lane.as_str(),
                host_role.as_str(),
                selected_lane.as_str(),
            ),
            vec![format!(
                "Use {} for this host role, or switch entrypoints before pinning {}.",
                selected_lane.as_str(),
                preferred_lane.as_str(),
            )],
        );
    }

    if selected_lane == BrowserExecutionLane::Unsupported {
        return (
            format!(
                "Preferred lane {} could not be selected because Rust Browser Edition currently reports {} and stayed on {}.",
                preferred_lane.as_str(),
                reason_code.as_str(),
                selected_lane.as_str(),
            ),
            vec![format!(
                "Restore the reported Browser Edition prerequisites before pinning {} again.",
                preferred_lane.as_str(),
            )],
        );
    }

    (
        format!(
            "Preferred lane {} is a lower-priority fail-closed fallback, so Rust Browser Edition stayed on {}.",
            preferred_lane.as_str(),
            selected_lane.as_str(),
        ),
        vec![format!(
            "Only pin {} when you intentionally want the fail-closed fallback lane.",
            preferred_lane.as_str(),
        )],
    )
}

struct BrowserExecutionLaneCandidateInput {
    lane_id: BrowserExecutionLane,
    host_role: BrowserExecutionHostRole,
    support_class: BrowserRuntimeSupportClass,
    available: bool,
    selected: bool,
    reason_code: BrowserExecutionReasonCode,
    message: String,
    guidance: Vec<String>,
}

fn create_browser_execution_lane_candidate(
    input: BrowserExecutionLaneCandidateInput,
) -> BrowserExecutionLaneCandidate {
    BrowserExecutionLaneCandidate {
        lane_id: input.lane_id,
        lane_kind: input.lane_id.lane_kind(),
        lane_rank: input.lane_id.lane_rank(),
        host_role: input.host_role,
        support_class: input.support_class,
        fallback_lane_id: input.lane_id.fallback_lane(),
        available: input.available,
        selected: input.selected,
        reason_code: input.reason_code,
        message: input.message,
        guidance: input.guidance,
    }
}

fn browser_execution_candidates(
    selected_lane: BrowserExecutionLane,
    host_role: BrowserExecutionHostRole,
    support_class: BrowserRuntimeSupportClass,
    selected_reason_code: BrowserExecutionReasonCode,
    selected_message: &str,
    selected_guidance: &[String],
) -> Vec<BrowserExecutionLaneCandidate> {
    let direct_lane_for_host = browser_execution_direct_lane_for_host_role(host_role);
    let lane_ids = [
        BrowserExecutionLane::BrowserMainThreadDirectRuntime,
        BrowserExecutionLane::DedicatedWorkerDirectRuntime,
        BrowserExecutionLane::Unsupported,
    ];

    lane_ids
        .into_iter()
        .map(|lane_id| {
            if lane_id == selected_lane {
                return create_browser_execution_lane_candidate(
                    BrowserExecutionLaneCandidateInput {
                        lane_id,
                        host_role,
                        support_class,
                        available: true,
                        selected: true,
                        reason_code: selected_reason_code,
                        message: selected_message.to_string(),
                        guidance: selected_guidance.to_vec(),
                    },
                );
            }

            let prerequisite_missing = if lane_id == BrowserExecutionLane::Unsupported {
                selected_lane != BrowserExecutionLane::Unsupported
            } else {
                direct_lane_for_host == Some(lane_id)
                    && selected_lane == BrowserExecutionLane::Unsupported
            };

            if prerequisite_missing {
                return create_browser_execution_lane_candidate(
                    BrowserExecutionLaneCandidateInput {
                        lane_id,
                        host_role,
                        support_class,
                        available: false,
                        selected: false,
                        reason_code: BrowserExecutionReasonCode::CandidatePrerequisiteMissing,
                        message: browser_execution_missing_prerequisite_message(lane_id),
                        guidance: browser_execution_missing_prerequisite_guidance(lane_id),
                    },
                );
            }

            create_browser_execution_lane_candidate(BrowserExecutionLaneCandidateInput {
                lane_id,
                host_role,
                support_class,
                available: false,
                selected: false,
                reason_code: BrowserExecutionReasonCode::CandidateHostRoleMismatch,
                message: browser_execution_host_mismatch_message(lane_id),
                guidance: browser_execution_host_mismatch_guidance(lane_id),
            })
        })
        .collect()
}

fn build_browser_execution_ladder_from_probe(
    preferred_lane: Option<BrowserExecutionLane>,
    probe: BrowserExecutionProbe,
) -> BrowserExecutionLadderDiagnostics {
    let runtime_support = browser_runtime_support_from_probe(probe);
    let host_role = probe.host_role;
    let direct_lane_for_host = browser_execution_direct_lane_for_host_role(host_role);
    let selected_lane = runtime_support
        .supported
        .then_some(direct_lane_for_host)
        .flatten()
        .unwrap_or(BrowserExecutionLane::Unsupported);
    let reason_code = browser_execution_reason_from_support(&runtime_support, host_role);
    let mut message = runtime_support.message.clone();
    let mut guidance = runtime_support.guidance.clone();

    if let Some(preferred_lane) = preferred_lane.filter(|lane| *lane != selected_lane) {
        let (mismatch_message, mismatch_guidance) = browser_execution_preferred_lane_mismatch(
            preferred_lane,
            selected_lane,
            host_role,
            direct_lane_for_host,
            reason_code,
        );
        message = format!("{message} {mismatch_message}");
        guidance.extend(mismatch_guidance);
    }

    let support_class = runtime_support.support_class;
    let candidates = browser_execution_candidates(
        selected_lane,
        host_role,
        support_class,
        reason_code,
        &message,
        &guidance,
    );
    let capabilities = runtime_support.capabilities;

    BrowserExecutionLadderDiagnostics {
        supported: selected_lane != BrowserExecutionLane::Unsupported,
        preferred_lane,
        selected_lane,
        lane_kind: selected_lane.lane_kind(),
        lane_rank: selected_lane.lane_rank(),
        host_role,
        support_class,
        runtime_context: runtime_support.runtime_context,
        reason_code,
        message,
        guidance,
        fallback_lane_id: selected_lane.fallback_lane(),
        downgrade_order: browser_execution_downgrade_order(host_role),
        repro_command: browser_execution_repro_command(),
        candidates,
        runtime_support,
        capabilities,
    }
}

fn browser_service_worker_broker_downgrade_order() -> Vec<BrowserWorkerFallbackTarget> {
    vec![
        BrowserWorkerFallbackTarget::DedicatedWorkerDirectRuntime,
        BrowserWorkerFallbackTarget::BrowserMainThreadDirectRuntime,
        BrowserWorkerFallbackTarget::BridgeFallback,
    ]
}

fn browser_shared_worker_coordinator_downgrade_order(
    host_role: BrowserExecutionHostRole,
) -> Vec<BrowserWorkerFallbackTarget> {
    let mut targets = Vec::new();
    if host_role == BrowserExecutionHostRole::DedicatedWorker {
        targets.push(BrowserWorkerFallbackTarget::DedicatedWorkerDirectRuntime);
    }
    if host_role == BrowserExecutionHostRole::BrowserMainThread {
        targets.push(BrowserWorkerFallbackTarget::BrowserMainThreadDirectRuntime);
    }
    if !targets.contains(&BrowserWorkerFallbackTarget::DedicatedWorkerDirectRuntime) {
        targets.push(BrowserWorkerFallbackTarget::DedicatedWorkerDirectRuntime);
    }
    if !targets.contains(&BrowserWorkerFallbackTarget::BrowserMainThreadDirectRuntime) {
        targets.push(BrowserWorkerFallbackTarget::BrowserMainThreadDirectRuntime);
    }
    targets.push(BrowserWorkerFallbackTarget::BridgeFallback);
    targets
}

fn browser_service_worker_broker_support_from_probe(
    probe: BrowserExecutionProbe,
) -> BrowserServiceWorkerBrokerSupportDiagnostics {
    let runtime_support = browser_runtime_support_from_probe(probe);
    let capabilities = runtime_support.capabilities;
    let downgrade_order = browser_service_worker_broker_downgrade_order();
    let fallback_target = downgrade_order[0];
    let direct_runtime_reason = runtime_support.reason;
    let direct_execution_reason_code =
        browser_execution_reason_from_support(&runtime_support, probe.host_role);
    let (supported, reason, message, guidance) = if probe.host_role
        != BrowserExecutionHostRole::ServiceWorker
    {
        (
            false,
            BrowserServiceWorkerBrokerSupportReason::ServiceWorkerApiMissing,
            "Rust Browser Edition service-worker broker preflight only admits service-worker hosts."
                .to_string(),
            vec![
                "Call the bounded broker surface only from a service-worker entrypoint."
                    .to_string(),
                format!(
                    "Keep direct BrowserRuntime creation on {} or {} when broker admission is unavailable.",
                    BrowserExecutionLane::DedicatedWorkerDirectRuntime.as_str(),
                    BrowserExecutionLane::BrowserMainThreadDirectRuntime.as_str()
                ),
            ],
        )
    } else if !probe.capabilities.storage.has_indexed_db {
        (
            false,
            BrowserServiceWorkerBrokerSupportReason::DurableStoreUnavailableForRestartableProfile,
            "Rust Browser Edition service-worker broker preflight found no durable store for the default restartable broker profile."
                .to_string(),
            vec![
                "Restore IndexedDB-backed durability before claiming restartable broker progress."
                    .to_string(),
                "Downgrade explicitly instead of pretending restartability without a durable substrate."
                    .to_string(),
            ],
        )
    } else {
        (
            true,
            BrowserServiceWorkerBrokerSupportReason::Supported,
            "Rust Browser Edition service-worker broker preflight found a bounded broker host surface; direct runtime creation remains fail-closed and work must hand off explicitly."
                .to_string(),
            vec![
                "Keep direct BrowserRuntime creation out of the service-worker host itself."
                    .to_string(),
                "Treat registration-scope and capability-manifest checks as explicit broker admission work on the JS helper surface."
                    .to_string(),
            ],
        )
    };

    BrowserServiceWorkerBrokerSupportDiagnostics {
        supported,
        contract_id: BROWSER_SERVICE_WORKER_BROKER_CONTRACT_ID,
        requested_lane: BROWSER_SERVICE_WORKER_BROKER_LANE,
        fallback_target,
        fallback_lane_id: fallback_target.fallback_lane_id(),
        downgrade_order,
        host_role: probe.host_role,
        runtime_context: runtime_support.runtime_context,
        reason,
        message,
        guidance,
        direct_runtime_reason,
        direct_execution_reason_code,
        runtime_support,
        capabilities,
    }
}

fn browser_shared_worker_coordinator_support_from_probe(
    probe: BrowserExecutionProbe,
) -> BrowserSharedWorkerCoordinatorSupportDiagnostics {
    let runtime_support = browser_runtime_support_from_probe(probe);
    let capabilities = runtime_support.capabilities;
    let downgrade_order = browser_shared_worker_coordinator_downgrade_order(probe.host_role);
    let fallback_target = downgrade_order[0];
    let direct_runtime_reason = BrowserRuntimeSupportReason::SharedWorkerNotYetShipped;
    let direct_execution_reason_code =
        BrowserExecutionReasonCode::SharedWorkerDirectRuntimeNotShipped;
    let (supported, reason, message, guidance) = match probe.host_role {
        BrowserExecutionHostRole::BrowserMainThread | BrowserExecutionHostRole::DedicatedWorker => (
            true,
            BrowserSharedWorkerCoordinatorSupportReason::Supported,
            "Rust Browser Edition shared-worker coordinator preflight found a truthful caller host; direct BrowserRuntime creation inside the shared-worker host remains fail-closed."
                .to_string(),
            vec![
                "Call the bounded shared-worker coordinator only from a browser main-thread or dedicated-worker caller."
                    .to_string(),
                "Treat same-origin script resolution, admission tuple checks, and protocol negotiation as explicit JS helper responsibilities."
                    .to_string(),
            ],
        ),
        _ => (
            false,
            BrowserSharedWorkerCoordinatorSupportReason::SharedWorkerApiMissing,
            "Rust Browser Edition shared-worker coordinator preflight only admits browser main-thread or dedicated-worker callers."
                .to_string(),
            vec![
                "Move the coordinator attach flow into a browser main-thread or dedicated-worker caller before expecting a bounded coordinator surface."
                    .to_string(),
                "Keep direct BrowserRuntime creation fail-closed inside the shared-worker host itself."
                    .to_string(),
            ],
        ),
    };

    BrowserSharedWorkerCoordinatorSupportDiagnostics {
        supported,
        contract_id: BROWSER_SHARED_WORKER_COORDINATOR_CONTRACT_ID,
        requested_lane: BROWSER_SHARED_WORKER_COORDINATOR_LANE,
        fallback_target,
        fallback_lane_id: fallback_target.fallback_lane_id(),
        downgrade_order,
        host_role: probe.host_role,
        runtime_context: runtime_support.runtime_context,
        reason,
        message,
        guidance,
        direct_runtime_reason,
        direct_execution_reason_code,
        runtime_support,
        capabilities,
    }
}

/// Error returned when the preview Rust browser runtime cannot be constructed.
#[derive(Debug, Clone, PartialEq, Eq, ThisError)]
pub enum BrowserRuntimeBuildError {
    /// The current host truthfully fail-closed to `lane.unsupported`.
    #[error("{message}")]
    Unsupported {
        /// Execution-ladder diagnostics that explain the fail-closed decision.
        execution_ladder: BrowserExecutionLadderDiagnostics,
        /// Human-readable explanation preserved for quick surfacing.
        message: String,
    },
    /// Runtime handle creation failed at the dispatcher boundary.
    #[error("failed to create preview browser runtime handle: {source}")]
    RuntimeCreate {
        /// Execution-ladder diagnostics in effect when creation failed.
        execution_ladder: BrowserExecutionLadderDiagnostics,
        /// Boundary-level error returned by the dispatcher.
        source: WasmDispatchError,
    },
}

impl BrowserRuntimeBuildError {
    /// Returns the browser execution-ladder diagnostics associated with this failure.
    #[must_use]
    pub fn execution_ladder(&self) -> &BrowserExecutionLadderDiagnostics {
        match self {
            Self::Unsupported {
                execution_ladder, ..
            }
            | Self::RuntimeCreate {
                execution_ladder, ..
            } => execution_ladder,
        }
    }
}

#[derive(Debug)]
struct BrowserRuntimeInner {
    dispatcher: RefCell<WasmExportDispatcher>,
    runtime_handle: WasmHandleRef,
    consumer_version: Option<WasmAbiVersion>,
    execution_ladder: BrowserExecutionLadderDiagnostics,
}

/// Dispatcher-backed preview runtime for Rust-authored browser consumers.
///
/// This is intentionally narrower than the native [`Runtime`]: it provides a
/// truthful browser entrypoint over the wasm ABI dispatcher instead of
/// pretending the browser already has full native-thread runtime parity.
#[derive(Debug, Clone)]
pub struct BrowserRuntime {
    inner: Rc<BrowserRuntimeInner>,
}

impl BrowserRuntime {
    fn new(
        dispatcher: WasmExportDispatcher,
        runtime_handle: WasmHandleRef,
        consumer_version: Option<WasmAbiVersion>,
        execution_ladder: BrowserExecutionLadderDiagnostics,
    ) -> Self {
        Self {
            inner: Rc::new(BrowserRuntimeInner {
                dispatcher: RefCell::new(dispatcher),
                runtime_handle,
                consumer_version,
                execution_ladder,
            }),
        }
    }

    /// Returns the browser runtime handle exported through the wasm dispatcher.
    #[must_use]
    pub fn runtime_handle(&self) -> WasmHandleRef {
        self.inner.runtime_handle
    }

    /// Returns the consumer ABI version used for boundary calls, if pinned.
    #[must_use]
    pub fn consumer_version(&self) -> Option<WasmAbiVersion> {
        self.inner.consumer_version
    }

    /// Returns the execution-ladder diagnostics used to select this runtime.
    #[must_use]
    pub fn execution_ladder(&self) -> &BrowserExecutionLadderDiagnostics {
        &self.inner.execution_ladder
    }

    /// Returns a snapshot of dispatcher state for leak detection and observability.
    #[must_use]
    pub fn dispatcher_diagnostics(&self) -> WasmDispatcherDiagnostics {
        self.inner.dispatcher.borrow().diagnostic_snapshot()
    }

    /// Enters a child scope beneath the runtime handle.
    pub fn enter_scope(&self, label: Option<&str>) -> Result<WasmHandleRef, WasmDispatchError> {
        let mut dispatcher = self.inner.dispatcher.borrow_mut();
        dispatcher.scope_enter(
            &WasmScopeEnterBuilder::new(self.runtime_handle())
                .label(label.unwrap_or("root"))
                .build(),
            self.consumer_version(),
        )
    }

    /// Closes a previously entered child scope.
    pub fn close_scope(
        &self,
        scope: &WasmHandleRef,
    ) -> Result<WasmAbiOutcomeEnvelope, WasmDispatchError> {
        self.inner
            .dispatcher
            .borrow_mut()
            .scope_close(scope, self.consumer_version())
    }

    /// Closes the runtime and drains all remaining child handles.
    pub fn close(&self) -> Result<WasmAbiOutcomeEnvelope, WasmDispatchError> {
        self.inner
            .dispatcher
            .borrow_mut()
            .runtime_close(&self.inner.runtime_handle, self.consumer_version())
    }
}

/// No-throw preview browser runtime selection result.
#[derive(Debug, Clone)]
pub struct BrowserRuntimeSelectionResult {
    /// Truthful execution-ladder diagnostics for the current host.
    pub execution_ladder: BrowserExecutionLadderDiagnostics,
    /// Constructed preview runtime, when the selected lane is supported.
    pub runtime: Option<BrowserRuntime>,
    /// Structured failure, when construction fail-closes.
    pub error: Option<BrowserRuntimeBuildError>,
}

impl BrowserRuntimeSelectionResult {
    /// Returns `true` when a preview runtime was constructed successfully.
    #[must_use]
    pub fn runtime_available(&self) -> bool {
        self.runtime.is_some()
    }
}

fn build_browser_runtime_selection_from_probe(
    preferred_lane: Option<BrowserExecutionLane>,
    consumer_version: Option<WasmAbiVersion>,
    abort_mode: WasmAbortPropagationMode,
    probe: BrowserExecutionProbe,
) -> BrowserRuntimeSelectionResult {
    let execution_ladder = build_browser_execution_ladder_from_probe(preferred_lane, probe);

    if !execution_ladder.supported {
        return BrowserRuntimeSelectionResult {
            runtime: None,
            error: Some(BrowserRuntimeBuildError::Unsupported {
                message: execution_ladder.message.clone(),
                execution_ladder: execution_ladder.clone(),
            }),
            execution_ladder,
        };
    }

    let mut dispatcher = WasmExportDispatcher::new().with_abort_mode(abort_mode);
    match dispatcher.runtime_create(consumer_version) {
        Ok(runtime_handle) => BrowserRuntimeSelectionResult {
            runtime: Some(BrowserRuntime::new(
                dispatcher,
                runtime_handle,
                consumer_version,
                execution_ladder.clone(),
            )),
            error: None,
            execution_ladder,
        },
        Err(source) => BrowserRuntimeSelectionResult {
            runtime: None,
            error: Some(BrowserRuntimeBuildError::RuntimeCreate {
                execution_ladder: execution_ladder.clone(),
                source,
            }),
            execution_ladder,
        },
    }
}

/// Preview builder for Rust-authored browser runtime construction.
#[derive(Debug, Clone)]
pub struct BrowserRuntimeBuilder {
    preferred_lane: Option<BrowserExecutionLane>,
    consumer_version: Option<WasmAbiVersion>,
    abort_mode: WasmAbortPropagationMode,
}

impl Default for BrowserRuntimeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl BrowserRuntimeBuilder {
    /// Creates a preview browser runtime builder with automatic lane negotiation.
    #[must_use]
    pub fn new() -> Self {
        Self {
            preferred_lane: None,
            consumer_version: None,
            abort_mode: WasmAbortPropagationMode::Bidirectional,
        }
    }

    /// Requests an explicit browser execution lane.
    #[must_use]
    pub fn preferred_lane(mut self, lane: BrowserExecutionLane) -> Self {
        self.preferred_lane = Some(lane);
        self
    }

    /// Restores automatic truthful lane negotiation.
    #[must_use]
    pub fn automatic_lane(mut self) -> Self {
        self.preferred_lane = None;
        self
    }

    /// Pins the consumer ABI version used for dispatcher boundary calls.
    #[must_use]
    pub fn consumer_version(mut self, version: WasmAbiVersion) -> Self {
        self.consumer_version = Some(version);
        self
    }

    /// Configures abort propagation semantics for the preview runtime dispatcher.
    #[must_use]
    pub fn abort_mode(mut self, mode: WasmAbortPropagationMode) -> Self {
        self.abort_mode = mode;
        self
    }

    /// Returns the truthful execution ladder for the current host and builder options.
    #[must_use]
    pub fn inspect_execution_ladder(self) -> BrowserExecutionLadderDiagnostics {
        build_browser_execution_ladder_from_probe(
            self.preferred_lane,
            detect_browser_execution_probe(),
        )
    }

    /// Returns a no-throw preview browser runtime selection result.
    #[must_use]
    pub fn build_selection(self) -> BrowserRuntimeSelectionResult {
        build_browser_runtime_selection_from_probe(
            self.preferred_lane,
            self.consumer_version,
            self.abort_mode,
            detect_browser_execution_probe(),
        )
    }

    /// Builds a preview browser runtime or returns a structured fail-closed error.
    #[allow(clippy::result_large_err)]
    pub fn build(self) -> Result<BrowserRuntime, BrowserRuntimeBuildError> {
        let selection = self.build_selection();
        match (selection.runtime, selection.error) {
            (Some(runtime), None) => Ok(runtime),
            (None | Some(_), Some(error)) => Err(error),
            (None, None) => Err(BrowserRuntimeBuildError::Unsupported {
                message: selection.execution_ladder.message.clone(),
                execution_ladder: selection.execution_ladder,
            }),
        }
    }
}

/// Builder for constructing an Asupersync [`Runtime`] with custom configuration.
///
/// Use the fluent API to set fields, then call [`build()`](Self::build) to
/// produce a [`Runtime`]. Each setter takes `self` by value and returns `Self`,
/// so the builder cannot be partially consumed.
///
/// # Example
///
/// ```ignore
/// use asupersync::runtime::RuntimeBuilder;
/// use std::time::Duration;
///
/// let runtime = RuntimeBuilder::new()
///     .worker_threads(4)
///     .poll_budget(256)
///     .steal_batch_size(32)
///     .deadline_monitoring(|m| {
///         m.enabled(true)
///          .check_interval(Duration::from_secs(1))
///     })
///     .build()?;
/// ```
#[derive(Clone)]
pub struct RuntimeBuilder {
    config: RuntimeConfig,
    reactor: Option<Arc<dyn Reactor>>,
    io_driver: Option<IoDriverHandle>,
    timer_driver: Option<TimerDriverHandle>,
    entropy_source: Option<Arc<dyn EntropySource>>,
    host_services: Arc<dyn RuntimeHostServices>,
}

impl RuntimeBuilder {
    /// Create a new builder with default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: RuntimeConfig::default(),
            reactor: None,
            io_driver: None,
            timer_driver: None,
            entropy_source: None,
            host_services: default_runtime_host_services(),
        }
    }

    /// Creates a preview builder for Rust-authored browser runtime construction.
    ///
    /// The returned builder performs truthful execution-ladder selection and
    /// fail-closes to structured diagnostics when no direct browser-runtime
    /// lane is available.
    #[must_use]
    pub fn browser() -> BrowserRuntimeBuilder {
        BrowserRuntimeBuilder::new()
    }

    /// Set the number of worker threads.
    #[must_use]
    pub fn worker_threads(mut self, n: usize) -> Self {
        self.config.worker_threads = n;
        self
    }

    /// Set the response policy for obligation leaks.
    #[must_use]
    pub fn obligation_leak_response(
        mut self,
        response: crate::runtime::config::ObligationLeakResponse,
    ) -> Self {
        self.config.obligation_leak_response = response;
        self
    }

    /// Set the worker thread stack size.
    #[must_use]
    pub fn thread_stack_size(mut self, size: usize) -> Self {
        self.config.thread_stack_size = size;
        self
    }

    /// Set the worker thread name prefix.
    #[must_use]
    pub fn thread_name_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config.thread_name_prefix = prefix.into();
        self
    }

    /// Set the global queue limit (0 = unbounded).
    #[must_use]
    pub fn global_queue_limit(mut self, limit: usize) -> Self {
        self.config.global_queue_limit = limit;
        self
    }

    /// Set the work stealing batch size.
    #[must_use]
    pub fn steal_batch_size(mut self, size: usize) -> Self {
        self.config.steal_batch_size = size;
        self
    }

    /// Set the logical clock mode used for causal trace ordering.
    #[must_use]
    pub fn logical_clock_mode(mut self, mode: LogicalClockMode) -> Self {
        self.config.logical_clock_mode = Some(mode);
        self
    }

    /// Set cancellation attribution chain limits.
    #[must_use]
    pub fn cancel_attribution_config(mut self, config: CancelAttributionConfig) -> Self {
        self.config.cancel_attribution = config;
        self
    }

    /// Configure blocking pool thread limits.
    #[must_use]
    pub fn blocking_threads(mut self, min: usize, max: usize) -> Self {
        self.config.blocking.min_threads = min;
        self.config.blocking.max_threads = max;
        self
    }

    /// Enable or disable parking for idle workers.
    #[must_use]
    pub fn enable_parking(mut self, enable: bool) -> Self {
        self.config.enable_parking = enable;
        self
    }

    /// Set the poll budget before yielding.
    #[must_use]
    pub fn poll_budget(mut self, budget: u32) -> Self {
        self.config.poll_budget = budget;
        self
    }

    /// Set browser-style ready-lane burst handoff limit.
    ///
    /// When non-zero, scheduler workers can force a one-shot handoff after
    /// `limit` consecutive ready dispatches, allowing host task queues to run.
    /// This is primarily intended for browser event-loop adapters.
    /// `0` disables forced handoff (default).
    #[must_use]
    pub fn browser_ready_handoff_limit(mut self, limit: usize) -> Self {
        self.config.browser_ready_handoff_limit = limit;
        self
    }

    /// Set the browser worker offload policy contract.
    ///
    /// This config defines ownership, cancellation, and transfer semantics
    /// for CPU-heavy work that may be dispatched to browser workers.
    #[must_use]
    pub fn browser_worker_offload(
        mut self,
        config: crate::runtime::config::BrowserWorkerOffloadConfig,
    ) -> Self {
        self.config.browser_worker_offload = config;
        self
    }

    /// Enable or disable browser worker offload.
    #[must_use]
    pub fn browser_worker_offload_enabled(mut self, enabled: bool) -> Self {
        self.config.browser_worker_offload.enabled = enabled;
        self
    }

    /// Set worker offload cost/in-flight thresholds.
    #[must_use]
    pub fn browser_worker_offload_limits(
        mut self,
        min_task_cost: u32,
        max_in_flight: usize,
    ) -> Self {
        self.config.browser_worker_offload.min_task_cost = min_task_cost;
        self.config.browser_worker_offload.max_in_flight = max_in_flight;
        self
    }

    /// Set payload transfer strategy for browser worker offload.
    #[must_use]
    pub fn browser_worker_transfer_mode(
        mut self,
        mode: crate::runtime::config::WorkerTransferMode,
    ) -> Self {
        self.config.browser_worker_offload.transfer_mode = mode;
        self
    }

    /// Set cancellation propagation strategy for browser worker offload.
    #[must_use]
    pub fn browser_worker_cancellation_mode(
        mut self,
        mode: crate::runtime::config::WorkerCancellationMode,
    ) -> Self {
        self.config.browser_worker_offload.cancellation_mode = mode;
        self
    }

    /// Set the maximum consecutive cancel-lane dispatches before yielding.
    #[must_use]
    pub fn cancel_lane_max_streak(mut self, max_streak: usize) -> Self {
        self.config.cancel_lane_max_streak = max_streak;
        self
    }

    /// Enable the Lyapunov governor for scheduling suggestions.
    ///
    /// When enabled, the scheduler periodically snapshots runtime state and
    /// consults the governor for lane-ordering hints that accelerate
    /// cancellation convergence.
    #[must_use]
    pub fn enable_governor(mut self, enable: bool) -> Self {
        self.config.enable_governor = enable;
        self
    }

    /// Set the number of scheduling steps between governor snapshots.
    ///
    /// Lower values increase responsiveness but add snapshot overhead.
    /// Default is 32. Only relevant when the governor is enabled.
    #[must_use]
    pub fn governor_interval(mut self, interval: u32) -> Self {
        self.config.governor_interval = interval;
        self
    }

    /// Enable or disable adaptive cancel-streak scheduling.
    ///
    /// When enabled, workers run a deterministic no-regret online policy that
    /// updates the base cancel streak limit across fixed-length epochs.
    #[must_use]
    pub fn enable_adaptive_cancel_streak(mut self, enable: bool) -> Self {
        self.config.enable_adaptive_cancel_streak = enable;
        self
    }

    /// Set the number of dispatches per adaptive cancel-streak epoch.
    ///
    /// Lower values react faster but add policy-update overhead.
    #[must_use]
    pub fn adaptive_cancel_streak_epoch_steps(mut self, steps: u32) -> Self {
        self.config.adaptive_cancel_streak_epoch_steps = steps;
        self
    }

    /// Set admission limits for the root region.
    #[must_use]
    pub fn root_region_limits(mut self, limits: RegionLimits) -> Self {
        self.config.root_region_limits = Some(limits);
        self
    }

    /// Clear root region admission limits (unlimited).
    #[must_use]
    pub fn clear_root_region_limits(mut self) -> Self {
        self.config.root_region_limits = None;
        self
    }

    /// Register a callback to run when a worker thread starts.
    #[must_use]
    pub fn on_thread_start<F>(mut self, f: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.config.on_thread_start = Some(Arc::new(f));
        self
    }

    /// Register a callback to run when a worker thread stops.
    #[must_use]
    pub fn on_thread_stop<F>(mut self, f: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.config.on_thread_stop = Some(Arc::new(f));
        self
    }

    /// Set the metrics provider for the runtime.
    ///
    /// The metrics provider receives callbacks for task spawning, completion,
    /// region lifecycle events, and scheduler metrics. Use this to export
    /// runtime metrics to OpenTelemetry, Prometheus, or custom backends.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use asupersync::runtime::RuntimeBuilder;
    /// use asupersync::observability::OtelMetrics;
    /// use opentelemetry::global;
    ///
    /// let meter = global::meter("asupersync");
    /// let metrics = OtelMetrics::new(meter);
    ///
    /// let runtime = RuntimeBuilder::new()
    ///     .metrics(metrics)
    ///     .build()?;
    /// ```
    #[must_use]
    pub fn metrics<M: MetricsProvider>(mut self, provider: M) -> Self {
        self.config.metrics_provider = Arc::new(provider);
        self
    }

    /// Configure runtime observability (logging and diagnostic context).
    ///
    /// When provided, the runtime attaches a shared log collector to task
    /// contexts and configures diagnostic context defaults.
    #[must_use]
    pub fn observability(mut self, config: ObservabilityConfig) -> Self {
        self.config.observability = Some(config);
        self
    }

    /// Configure deadline monitoring for this runtime.
    ///
    /// The provided closure can customize thresholds and warning handlers.
    ///
    /// ```ignore
    /// use asupersync::runtime::RuntimeBuilder;
    /// use std::time::Duration;
    ///
    /// let runtime = RuntimeBuilder::new()
    ///     .deadline_monitoring(|m| {
    ///         m.check_interval(Duration::from_secs(1))
    ///             .warning_threshold_fraction(0.2)
    ///             .checkpoint_timeout(Duration::from_secs(30))
    ///             .on_warning(|w| {
    ///                 asupersync::tracing_compat::warn!(?w, "deadline warning");
    ///             })
    ///     })
    ///     .build();
    /// ```
    #[must_use]
    pub fn deadline_monitoring<F>(mut self, f: F) -> Self
    where
        F: FnOnce(DeadlineMonitoringBuilder) -> DeadlineMonitoringBuilder,
    {
        let builder = f(DeadlineMonitoringBuilder::new());
        let (config, handler) = builder.finish();
        let handler =
            handler.or_else(|| {
                if config.enabled {
                    Some(Arc::new(default_warning_handler)
                        as Arc<dyn Fn(DeadlineWarning) + Send + Sync>)
                } else {
                    None
                }
            });

        self.config.deadline_monitor = Some(config);
        self.config.deadline_warning_handler = handler;
        self
    }

    /// Apply environment variable overrides to the current configuration.
    ///
    /// Only environment variables that are set are applied. Unset variables
    /// leave the current configuration unchanged.
    ///
    /// # Precedence
    ///
    /// Environment variables override config file values and defaults, but
    /// programmatic settings applied *after* this call take highest priority.
    ///
    /// Typical usage:
    ///
    /// ```ignore
    /// let runtime = RuntimeBuilder::new()
    ///     .with_env_overrides()?   // env vars override defaults
    ///     .worker_threads(4)       // programmatic override (highest priority)
    ///     .build()?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if an environment variable is set but contains an
    /// unparseable value (e.g., `ASUPERSYNC_WORKER_THREADS=abc`).
    ///
    /// See [`env_config`](super::env_config) for the full list of supported variables.
    #[allow(clippy::result_large_err)]
    pub fn with_env_overrides(mut self) -> Result<Self, Error> {
        crate::runtime::env_config::apply_env_overrides(&mut self.config).map_err(|e| {
            Error::new(crate::error::ErrorKind::ConfigError).with_message(e.to_string())
        })?;
        Ok(self)
    }

    /// Load configuration from a TOML file.
    ///
    /// Values from the file are applied as a base; environment variables
    /// and programmatic settings take precedence.
    ///
    /// Requires the `config-file` feature.
    ///
    /// ```ignore
    /// let runtime = RuntimeBuilder::from_toml("config/runtime.toml")?
    ///     .with_env_overrides()?   // env vars override file values
    ///     .worker_threads(4)       // programmatic override (highest priority)
    ///     .build()?;
    /// ```
    #[cfg(feature = "config-file")]
    #[allow(clippy::result_large_err)]
    pub fn from_toml(path: impl AsRef<std::path::Path>) -> Result<Self, Error> {
        let toml_config =
            crate::runtime::env_config::parse_toml_file(path.as_ref()).map_err(|e| {
                Error::new(crate::error::ErrorKind::ConfigError).with_message(e.to_string())
            })?;
        let mut config = RuntimeConfig::default();
        crate::runtime::env_config::apply_toml_config(&mut config, &toml_config);
        Ok(Self {
            config,
            reactor: None,
            io_driver: None,
            timer_driver: None,
            entropy_source: None,
            host_services: default_runtime_host_services(),
        })
    }

    /// Load configuration from a TOML string.
    ///
    /// Values from the string are applied as a base; environment variables
    /// and programmatic settings take precedence.
    ///
    /// Requires the `config-file` feature.
    ///
    /// ```ignore
    /// let toml = r#"
    /// [scheduler]
    /// worker_threads = 4
    /// poll_budget = 256
    /// "#;
    /// let runtime = RuntimeBuilder::from_toml_str(toml)?
    ///     .with_env_overrides()?
    ///     .build()?;
    /// ```
    #[cfg(feature = "config-file")]
    #[allow(clippy::result_large_err)]
    pub fn from_toml_str(toml: &str) -> Result<Self, Error> {
        let toml_config = crate::runtime::env_config::parse_toml_str(toml).map_err(|e| {
            Error::new(crate::error::ErrorKind::ConfigError).with_message(e.to_string())
        })?;
        let mut config = RuntimeConfig::default();
        crate::runtime::env_config::apply_toml_config(&mut config, &toml_config);
        Ok(Self {
            config,
            reactor: None,
            io_driver: None,
            timer_driver: None,
            entropy_source: None,
            host_services: default_runtime_host_services(),
        })
    }

    /// Build a runtime from this configuration.
    #[allow(clippy::result_large_err)]
    pub fn build(self) -> Result<Runtime, Error> {
        let Self {
            config,
            reactor,
            io_driver,
            timer_driver,
            entropy_source,
            host_services,
        } = self;
        Runtime::with_config_and_platform(
            config,
            reactor,
            io_driver,
            timer_driver,
            entropy_source,
            host_services.as_ref(),
        )
    }

    /// Inspect the truthful browser execution ladder for the current host.
    ///
    /// This surfaces Rust-side lane negotiation diagnostics that stay aligned
    /// with the shared Browser Edition execution-ladder contract without
    /// claiming that a public direct browser-runtime constructor already
    /// exists on every target.
    #[must_use]
    pub fn inspect_browser_execution_ladder(&self) -> BrowserExecutionLadderDiagnostics {
        let _ = self;
        build_browser_execution_ladder_from_probe(None, detect_browser_execution_probe())
    }

    /// Inspect the truthful browser execution ladder for a supplied host snapshot.
    ///
    /// This is intended for deterministic fixtures, documentation examples,
    /// and contract tests that need to preserve Rust-side ladder semantics for
    /// host roles that are not directly executing the runtime.
    #[must_use]
    pub fn inspect_browser_execution_ladder_for_probe(
        &self,
        probe: BrowserExecutionProbe,
    ) -> BrowserExecutionLadderDiagnostics {
        let _ = self;
        build_browser_execution_ladder_from_probe(None, probe)
    }

    /// Inspect the truthful browser execution ladder while requesting a preferred lane.
    ///
    /// When the preferred lane is not truthful for the current host role, the
    /// returned diagnostics preserve the truthful selected lane and annotate
    /// the mismatch in the message and guidance.
    #[must_use]
    pub fn inspect_browser_execution_ladder_with_preferred_lane(
        &self,
        preferred_lane: BrowserExecutionLane,
    ) -> BrowserExecutionLadderDiagnostics {
        let _ = self;
        build_browser_execution_ladder_from_probe(
            Some(preferred_lane),
            detect_browser_execution_probe(),
        )
    }

    /// Inspect the truthful browser execution ladder for a supplied probe while
    /// also requesting a preferred lane.
    #[must_use]
    pub fn inspect_browser_execution_ladder_with_preferred_lane_for_probe(
        &self,
        probe: BrowserExecutionProbe,
        preferred_lane: BrowserExecutionLane,
    ) -> BrowserExecutionLadderDiagnostics {
        let _ = self;
        build_browser_execution_ladder_from_probe(Some(preferred_lane), probe)
    }

    /// Inspect bounded service-worker broker host-class diagnostics for the current host.
    ///
    /// This stays intentionally narrower than the JS helper surface: it only
    /// reports the truthful host-class facts that the Rust browser builder can
    /// inspect locally without widening the shipped direct-runtime contract.
    #[must_use]
    pub fn inspect_browser_service_worker_broker_support(
        &self,
    ) -> BrowserServiceWorkerBrokerSupportDiagnostics {
        let _ = self;
        browser_service_worker_broker_support_from_probe(detect_browser_execution_probe())
    }

    /// Inspect bounded service-worker broker host-class diagnostics for a supplied probe.
    #[must_use]
    pub fn inspect_browser_service_worker_broker_support_for_probe(
        &self,
        probe: BrowserExecutionProbe,
    ) -> BrowserServiceWorkerBrokerSupportDiagnostics {
        let _ = self;
        browser_service_worker_broker_support_from_probe(probe)
    }

    /// Inspect bounded shared-worker coordinator caller-side diagnostics for the current host.
    ///
    /// This reports whether the current caller host is a truthful place to
    /// start a bounded coordinator attach flow while preserving the fail-closed
    /// shared-worker direct-runtime truth.
    #[must_use]
    pub fn inspect_browser_shared_worker_coordinator_support(
        &self,
    ) -> BrowserSharedWorkerCoordinatorSupportDiagnostics {
        let _ = self;
        browser_shared_worker_coordinator_support_from_probe(detect_browser_execution_probe())
    }

    /// Inspect bounded shared-worker coordinator caller-side diagnostics for a supplied probe.
    #[must_use]
    pub fn inspect_browser_shared_worker_coordinator_support_for_probe(
        &self,
        probe: BrowserExecutionProbe,
    ) -> BrowserSharedWorkerCoordinatorSupportDiagnostics {
        let _ = self;
        browser_shared_worker_coordinator_support_from_probe(probe)
    }

    /// Provide a reactor for runtime I/O integration.
    ///
    /// When set, the runtime will attach an `IoDriver` backed by this reactor.
    #[must_use]
    pub fn with_reactor(mut self, reactor: Arc<dyn Reactor>) -> Self {
        self.reactor = Some(reactor);
        self
    }

    /// Provide an explicit I/O driver handle for runtime capability contexts.
    ///
    /// This overrides the default reactor-backed driver creation path and is
    /// useful for platform seam injection (for example, browser adapters).
    #[must_use]
    pub fn with_io_driver(mut self, driver: IoDriverHandle) -> Self {
        self.io_driver = Some(driver);
        self
    }

    /// Provide an explicit timer driver handle for runtime capability contexts.
    ///
    /// When set, this driver is installed into runtime state before root-region
    /// initialization, so spawned tasks inherit it through `Cx`.
    #[must_use]
    pub fn with_timer_driver(mut self, driver: TimerDriverHandle) -> Self {
        self.timer_driver = Some(driver);
        self
    }

    /// Provide an explicit entropy source for capability-based randomness.
    ///
    /// The runtime forks this source per task and wires it into task contexts,
    /// avoiding implicit ambient entropy.
    #[must_use]
    pub fn with_entropy_source(mut self, source: Arc<dyn EntropySource>) -> Self {
        self.entropy_source = Some(source);
        self
    }

    /// Preset: single-threaded runtime.
    ///
    /// Equivalent to `RuntimeBuilder::new().worker_threads(1)`.
    /// Suitable for testing, deterministic replay, and Phase 0 usage.
    ///
    /// ```ignore
    /// let rt = RuntimeBuilder::current_thread().build()?;
    /// rt.block_on(async { /* single-threaded execution */ });
    /// ```
    #[must_use]
    pub fn current_thread() -> Self {
        Self::new().worker_threads(1)
    }

    /// Preset: multi-threaded runtime with default parallelism.
    ///
    /// Equivalent to `RuntimeBuilder::new()`. Worker count defaults to
    /// the available CPU parallelism.
    #[must_use]
    pub fn multi_thread() -> Self {
        Self::new()
    }

    /// Preset: high-throughput server.
    ///
    /// Uses 2x the available parallelism for workers and a larger
    /// steal batch size (32) to amortize scheduling overhead.
    ///
    /// ```ignore
    /// let rt = RuntimeBuilder::high_throughput()
    ///     .blocking_threads(4, 256)
    ///     .build()?;
    /// ```
    #[must_use]
    pub fn high_throughput() -> Self {
        let workers = RuntimeConfig::default_worker_threads()
            .saturating_mul(2)
            .max(1);
        Self::new().worker_threads(workers).steal_batch_size(32)
    }

    /// Preset: low-latency interactive application.
    ///
    /// Uses smaller steal batches (4) and tighter poll budgets (32)
    /// to reduce tail latency at the cost of throughput.
    ///
    /// ```ignore
    /// let rt = RuntimeBuilder::low_latency()
    ///     .worker_threads(2)
    ///     .build()?;
    /// ```
    #[must_use]
    pub fn low_latency() -> Self {
        Self::new().steal_batch_size(4).poll_budget(32)
    }
}

/// Sub-builder for deadline monitoring configuration.
///
/// Obtained through [`RuntimeBuilder::deadline_monitoring`]. Allows fine-grained
/// control over deadline checking intervals, warning thresholds, and adaptive
/// deadline behavior.
///
/// # Example
///
/// ```ignore
/// use std::time::Duration;
///
/// RuntimeBuilder::new()
///     .deadline_monitoring(|m| {
///         m.enabled(true)
///          .check_interval(Duration::from_secs(1))
///          .warning_threshold_fraction(0.2) // warn at 80% of deadline
///          .checkpoint_timeout(Duration::from_secs(30))
///          .adaptive_enabled(true)
///          .adaptive_warning_percentile(0.95)
///          .on_warning(|w| eprintln!("deadline warning: {w:?}"))
///     })
///     .build()?;
/// ```
pub struct DeadlineMonitoringBuilder {
    config: MonitorConfig,
    on_warning: Option<Arc<dyn Fn(DeadlineWarning) + Send + Sync>>,
}

impl DeadlineMonitoringBuilder {
    fn new() -> Self {
        Self {
            config: MonitorConfig::default(),
            on_warning: None,
        }
    }

    /// Use an explicit monitor configuration.
    #[must_use]
    pub fn config(mut self, config: MonitorConfig) -> Self {
        self.config = config;
        self
    }

    /// Set how often the monitor should scan for warnings.
    #[must_use]
    pub fn check_interval(mut self, interval: Duration) -> Self {
        self.config.check_interval = interval;
        self
    }

    /// Set the fraction of deadline remaining that triggers a warning.
    #[must_use]
    pub fn warning_threshold_fraction(mut self, fraction: f64) -> Self {
        self.config.warning_threshold_fraction = fraction;
        self
    }

    /// Set how long a task may go without progress before warning.
    #[must_use]
    pub fn checkpoint_timeout(mut self, timeout: Duration) -> Self {
        self.config.checkpoint_timeout = timeout;
        self
    }

    /// Use an explicit adaptive deadline configuration.
    #[must_use]
    pub fn adaptive_config(mut self, config: AdaptiveDeadlineConfig) -> Self {
        self.config.adaptive = config;
        self
    }

    /// Enable or disable adaptive deadline thresholds.
    #[must_use]
    pub fn adaptive_enabled(mut self, enabled: bool) -> Self {
        self.config.adaptive.adaptive_enabled = enabled;
        self
    }

    /// Set the adaptive warning percentile.
    #[must_use]
    pub fn adaptive_warning_percentile(mut self, percentile: f64) -> Self {
        self.config.adaptive.warning_percentile = percentile;
        self
    }

    /// Set the minimum samples required for adaptive thresholds.
    #[must_use]
    pub fn adaptive_min_samples(mut self, min_samples: usize) -> Self {
        self.config.adaptive.min_samples = min_samples;
        self
    }

    /// Set the maximum history length per task type.
    #[must_use]
    pub fn adaptive_max_history(mut self, max_history: usize) -> Self {
        self.config.adaptive.max_history = max_history;
        self
    }

    /// Set the fallback threshold used before enough samples are collected.
    #[must_use]
    pub fn adaptive_fallback_threshold(mut self, threshold: Duration) -> Self {
        self.config.adaptive.fallback_threshold = threshold;
        self
    }

    /// Enable or disable deadline monitoring.
    #[must_use]
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    /// Register a custom warning handler.
    #[must_use]
    pub fn on_warning<F>(mut self, f: F) -> Self
    where
        F: Fn(DeadlineWarning) + Send + Sync + 'static,
    {
        self.on_warning = Some(Arc::new(f));
        self
    }

    #[allow(clippy::type_complexity)]
    fn finish(
        self,
    ) -> (
        MonitorConfig,
        Option<Arc<dyn Fn(DeadlineWarning) + Send + Sync>>,
    ) {
        (self.config, self.on_warning)
    }
}

impl Default for RuntimeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// A configured Asupersync runtime.
///
/// Created via [`RuntimeBuilder`]. The runtime owns worker threads and a
/// three-lane priority scheduler. Clone is cheap (shared `Arc`).
///
/// # Example
///
/// ```ignore
/// let runtime = RuntimeBuilder::new().worker_threads(2).build()?;
///
/// // Run a future to completion on the current thread.
/// let result = runtime.block_on(async { 1 + 1 });
/// assert_eq!(result, 2);
///
/// // Spawn from outside async context via a handle.
/// let handle = runtime.handle().spawn(async { 42u32 });
/// let value = runtime.block_on(handle);
/// assert_eq!(value, 42);
/// ```
#[derive(Clone)]
pub struct Runtime {
    inner: Arc<RuntimeInner>,
}

impl Runtime {
    /// Construct a runtime from the given configuration.
    #[allow(clippy::result_large_err)]
    pub fn with_config(config: RuntimeConfig) -> Result<Self, Error> {
        let host_services = default_runtime_host_services();
        Self::with_config_and_platform(config, None, None, None, None, host_services.as_ref())
    }

    /// Construct a runtime from the given configuration and reactor.
    #[allow(clippy::result_large_err)]
    pub fn with_config_and_reactor(
        config: RuntimeConfig,
        reactor: Option<Arc<dyn Reactor>>,
    ) -> Result<Self, Error> {
        let host_services = default_runtime_host_services();
        Self::with_config_and_platform(config, reactor, None, None, None, host_services.as_ref())
    }

    /// Construct a runtime from configuration, explicit platform seams, and
    /// startup host services.
    #[allow(clippy::result_large_err)]
    fn with_config_and_platform(
        mut config: RuntimeConfig,
        reactor: Option<Arc<dyn Reactor>>,
        io_driver: Option<IoDriverHandle>,
        timer_driver: Option<TimerDriverHandle>,
        entropy_source: Option<Arc<dyn EntropySource>>,
        host_services: &dyn RuntimeHostServices,
    ) -> Result<Self, Error> {
        config.normalize();
        #[cfg(target_arch = "wasm32")]
        {
            let _ = (reactor, io_driver, timer_driver, entropy_source);
            Err(Error::new(crate::error::ErrorKind::ConfigError)
                .with_message(unsupported_browser_bootstrap_message(host_services)))
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let (inner, workers) = RuntimeInner::new(
                config,
                reactor,
                io_driver,
                timer_driver,
                entropy_source,
                host_services,
            );
            let inner = Arc::new(inner);
            let worker_threads = host_services.spawn_workers(&inner, workers).map_err(|e| {
                Error::new(crate::error::ErrorKind::Internal)
                    .with_message(format!("runtime init: {e}"))
            })?;
            *lock_state(&inner.worker_threads) = worker_threads;
            Ok(Self { inner })
        }
    }

    /// Returns a handle that can spawn tasks from outside the runtime.
    #[must_use]
    pub fn handle(&self) -> RuntimeHandle {
        RuntimeHandle::strong(Arc::clone(&self.inner))
    }

    /// Run a future to completion on the current thread.
    ///
    /// While the future is being polled, a thread-local [`RuntimeHandle`] is
    /// available via [`Runtime::current_handle`]. This allows futures inside
    /// `block_on` to spawn tasks onto the real scheduler without having to
    /// thread the handle through every layer.
    pub fn block_on<F: Future>(&self, future: F) -> F::Output {
        let _guard = ScopedRuntimeHandle::new(self.handle());
        run_future_with_budget(future, self.inner.config.poll_budget)
    }

    /// Run a future to completion with an ambient [`Cx`](crate::cx::Cx).
    ///
    /// This is for execution paths that are polled directly by `block_on`
    /// rather than through the scheduler, but still need `Cx::current()` to
    /// reflect the active request/task context.
    pub(crate) fn block_on_with_cx<F: Future>(
        &self,
        request_cx: crate::cx::Cx,
        future: F,
    ) -> F::Output {
        let _runtime_guard = ScopedRuntimeHandle::new(self.handle());
        let _cx_guard = crate::cx::Cx::set_current(Some(request_cx));
        run_future_with_budget(future, self.inner.config.poll_budget)
    }

    /// Run a future to completion using the currently installed runtime handle
    /// while temporarily overriding the ambient [`Cx`](crate::cx::Cx).
    ///
    /// Unlike [`block_on_with_cx`](Self::block_on_with_cx), this preserves the
    /// existing thread-local runtime handle instead of replacing it. That is
    /// required for framework adapter paths that are invoked from within an
    /// already-running runtime task and must not sever deadline/cancellation
    /// propagation by switching to a detached helper runtime.
    pub(crate) fn block_on_current_with_cx<F: Future>(
        request_cx: crate::cx::Cx,
        future: F,
    ) -> Option<F::Output> {
        let handle = Self::current_handle()?;
        let inner = handle.try_inner().ok()?;
        let _cx_guard = crate::cx::Cx::set_current(Some(request_cx));
        Some(run_future_with_budget(future, inner.config.poll_budget))
    }

    /// Create a request-scoped [`Cx`](crate::cx::Cx) backed by this runtime's
    /// drivers, tracing, and logical clock configuration.
    #[must_use]
    pub(crate) fn request_cx_with_budget(&self, budget: Budget) -> crate::cx::Cx {
        build_request_cx_from_inner(&self.inner, budget)
    }

    /// Create a request-scoped [`Cx`](crate::cx::Cx) from the currently
    /// installed runtime handle, if one exists.
    #[must_use]
    pub(crate) fn current_request_cx_with_budget(budget: Budget) -> Option<crate::cx::Cx> {
        let handle = Self::current_handle()?;
        let inner = handle.try_inner().ok()?;
        Some(build_request_cx_from_inner(&inner, budget))
    }

    /// Returns a handle to the current runtime, if called from within
    /// [`Runtime::block_on`] or a worker thread.
    ///
    /// Returns `None` when called outside of a runtime context.
    ///
    /// # Example
    ///
    /// ```ignore
    /// runtime.block_on(async {
    ///     let handle = Runtime::current_handle()
    ///         .expect("inside block_on");
    ///     handle.spawn(async { do_work().await });
    /// });
    /// ```
    ///
    /// Returns `None` when no runtime is installed on the current thread and
    /// during thread-local teardown, where the ambient handle is no longer
    /// accessible.
    #[must_use]
    pub fn current_handle() -> Option<RuntimeHandle> {
        CURRENT_RUNTIME_HANDLE
            .try_with(|cell| cell.borrow().clone())
            .unwrap_or(None)
    }

    /// Returns a reference to the runtime configuration.
    #[must_use]
    pub fn config(&self) -> &RuntimeConfig {
        &self.inner.config
    }

    /// Returns true if the runtime is quiescent (no live tasks or I/O).
    #[must_use]
    pub fn is_quiescent(&self) -> bool {
        let guard = self
            .inner
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.is_quiescent()
    }

    /// Spawns a blocking task on the blocking pool.
    ///
    /// Returns `None` if the blocking pool is not configured (max_threads = 0).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let runtime = RuntimeBuilder::new()
    ///     .blocking_threads(1, 4)
    ///     .build()?;
    ///
    /// let handle = runtime.spawn_blocking(|| {
    ///     std::fs::read_to_string("/etc/hosts")
    /// });
    /// ```
    pub fn spawn_blocking<F>(
        &self,
        f: F,
    ) -> Option<crate::runtime::blocking_pool::BlockingTaskHandle>
    where
        F: FnOnce() + Send + 'static,
    {
        self.inner.blocking_pool.as_ref().map(|pool| pool.spawn(f))
    }

    /// Returns a handle to the blocking pool, if configured.
    #[must_use]
    pub fn blocking_handle(&self) -> Option<crate::runtime::blocking_pool::BlockingPoolHandle> {
        self.inner.blocking_handle()
    }
}

/// Handle for spawning tasks onto a runtime from outside async context.
///
/// Cheap to clone (shared `Arc`). Use [`Runtime::handle`] to obtain one.
///
/// ```ignore
/// let runtime = RuntimeBuilder::new().build()?;
/// let handle = runtime.handle();
///
/// // Spawn from any thread.
/// let join = handle.spawn(async { compute_result().await });
/// let result = runtime.block_on(join);
/// ```
#[derive(Clone)]
enum RuntimeHandleRef {
    Strong(Arc<RuntimeInner>),
    Weak(Weak<RuntimeInner>),
}

/// Handle for spawning tasks onto a runtime from outside async context.
///
/// Cheap to clone (shared handle backing). Use [`Runtime::handle`] to obtain one.
///
/// ```ignore
/// let runtime = RuntimeBuilder::new().build()?;
/// let handle = runtime.handle();
///
/// // Spawn from any thread.
/// let join = handle.spawn(async { compute_result().await });
/// let result = runtime.block_on(join);
/// ```
#[derive(Clone)]
pub struct RuntimeHandle {
    inner: RuntimeHandleRef,
}

impl RuntimeHandle {
    fn strong(inner: Arc<RuntimeInner>) -> Self {
        Self {
            inner: RuntimeHandleRef::Strong(inner),
        }
    }

    fn weak(inner: &Arc<RuntimeInner>) -> Self {
        Self {
            inner: RuntimeHandleRef::Weak(Arc::downgrade(inner)),
        }
    }

    fn try_inner(&self) -> Result<Arc<RuntimeInner>, SpawnError> {
        match &self.inner {
            RuntimeHandleRef::Strong(inner) => Ok(Arc::clone(inner)),
            RuntimeHandleRef::Weak(inner) => inner.upgrade().ok_or(SpawnError::RuntimeUnavailable),
        }
    }

    /// Spawn a task from outside async context.
    ///
    /// Panics if the runtime is no longer available or if the root region
    /// rejects admission. Use [`RuntimeHandle::try_spawn`] to handle those
    /// failures explicitly.
    pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        self.try_spawn(future)
            .expect("failed to create runtime task")
    }

    /// Spawn a task from outside async context, returning runtime-availability
    /// or admission errors instead of panicking.
    pub fn try_spawn<F>(&self, future: F) -> Result<JoinHandle<F::Output>, SpawnError>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        self.try_inner()?.spawn(future)
    }

    /// Spawn a task with a [`Cx`](crate::cx::Cx) from outside async context.
    ///
    /// Creates a child Cx in the runtime's root region and passes it to the
    /// factory closure. The Cx participates in structured cancellation: it
    /// will observe cancellation when the runtime shuts down.
    ///
    /// Panics if the runtime is no longer available or if the root region
    /// rejects admission. Use [`RuntimeHandle::try_spawn_with_cx`] to handle
    /// those failures explicitly.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let handle = runtime.handle();
    /// handle.spawn_with_cx(|cx| async move {
    ///     while !cx.is_cancel_requested() {
    ///         // do work
    ///     }
    /// });
    /// ```
    pub fn spawn_with_cx<F, Fut>(&self, f: F)
    where
        F: FnOnce(crate::cx::Cx) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.try_spawn_with_cx(f)
            .expect("failed to spawn task with cx");
    }

    /// Spawn a task with a [`Cx`](crate::cx::Cx) from outside async context,
    /// returning runtime-availability or admission errors instead of panicking.
    ///
    /// Creates a child Cx in the runtime's root region and passes it to the
    /// factory closure. The Cx participates in structured cancellation: it
    /// will observe cancellation when the runtime shuts down.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let handle = runtime.handle();
    /// handle.try_spawn_with_cx(|cx| async move {
    ///     while !cx.is_cancel_requested() {
    ///         // do work
    ///     }
    /// })?;
    /// ```
    pub fn try_spawn_with_cx<F, Fut>(&self, f: F) -> Result<(), SpawnError>
    where
        F: FnOnce(crate::cx::Cx) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.try_inner()?.spawn_with_cx(f)
    }

    /// Spawns a blocking task on the blocking pool.
    ///
    /// Returns `None` if the blocking pool is not configured or if this handle
    /// is a stale weak handle whose runtime has already been dropped.
    pub fn spawn_blocking<F>(
        &self,
        f: F,
    ) -> Option<crate::runtime::blocking_pool::BlockingTaskHandle>
    where
        F: FnOnce() + Send + 'static,
    {
        let inner = self.try_inner().ok()?;
        inner.blocking_pool.as_ref().map(|pool| pool.spawn(f))
    }

    /// Returns a handle to the blocking pool, if configured and the runtime is
    /// still alive.
    #[must_use]
    pub fn blocking_handle(&self) -> Option<crate::runtime::blocking_pool::BlockingPoolHandle> {
        self.try_inner().ok()?.blocking_handle()
    }
}

/// A join handle returned by [`RuntimeHandle::spawn`].
pub struct JoinHandle<T> {
    state: Arc<Mutex<JoinState<T>>>,
    completed: bool,
}

impl<T> JoinHandle<T> {
    fn new(state: Arc<Mutex<JoinState<T>>>) -> Self {
        Self {
            state,
            completed: false,
        }
    }

    /// Returns true if the task has completed.
    #[must_use]
    pub fn is_finished(&self) -> bool {
        if self.completed {
            return true;
        }
        let guard = lock_state(&self.state);
        guard.result.is_some() || Arc::strong_count(&self.state) == 1
    }
}

impl<T> Future for JoinHandle<T> {
    type Output = T;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        assert!(
            !this.completed,
            "runtime::JoinHandle polled after completion"
        );
        let mut guard = lock_state(&this.state);
        match guard.result.take() {
            None => {
                if Arc::strong_count(&this.state) == 1 {
                    // The executor side was dropped without producing a result or panic payload
                    // (e.g. the runtime was shut down and tasks were force-cancelled).
                    this.completed = true;
                    drop(guard);
                    panic!("task was dropped or cancelled before completion"); // ubs:ignore - runtime shutdown panic
                }

                if !guard
                    .waker
                    .as_ref()
                    .is_some_and(|w| w.will_wake(cx.waker()))
                {
                    guard.waker = Some(cx.waker().clone());
                }
                Poll::Pending
            }
            Some(Ok(output)) => {
                this.completed = true;
                Poll::Ready(output)
            }
            Some(Err(payload)) => {
                this.completed = true;
                drop(guard);
                std::panic::resume_unwind(payload)
            }
        }
    }
}

#[pin_project::pin_project]
struct CatchUnwind<F> {
    #[pin]
    inner: F,
}

impl<F: Future> Future for CatchUnwind<F> {
    type Output = std::thread::Result<F::Output>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            this.inner.as_mut().poll(cx)
        }));
        match result {
            Ok(Poll::Pending) => Poll::Pending,
            Ok(Poll::Ready(v)) => Poll::Ready(Ok(v)),
            Err(payload) => Poll::Ready(Err(payload)),
        }
    }
}

struct RuntimeInner {
    config: RuntimeConfig,
    state: Arc<crate::sync::ContendedMutex<RuntimeState>>,
    scheduler: ThreeLaneScheduler,
    worker_threads: Mutex<Vec<std::thread::JoinHandle<()>>>,
    root_region: crate::types::RegionId,
    /// Blocking pool for synchronous operations.
    blocking_pool: Option<crate::runtime::blocking_pool::BlockingPool>,
    /// Shutdown signal for the deadline monitor thread.
    deadline_monitor_shutdown: Option<Arc<std::sync::atomic::AtomicBool>>,
    /// Deadline monitor background thread handle.
    deadline_monitor_thread: Option<std::thread::JoinHandle<()>>,
}

impl RuntimeInner {
    fn initialize_runtime_state(
        config: &RuntimeConfig,
        reactor: Option<Arc<dyn Reactor>>,
        io_driver: Option<IoDriverHandle>,
        timer_driver: Option<TimerDriverHandle>,
        entropy_source: Option<Arc<dyn EntropySource>>,
    ) -> RuntimeState {
        let mut runtime_state = reactor.map_or_else(
            || RuntimeState::new_with_metrics(config.metrics_provider.clone()),
            |reactor| {
                RuntimeState::with_reactor_and_metrics(reactor, config.metrics_provider.clone())
            },
        );
        if let Some(driver) = io_driver {
            runtime_state.set_io_driver(driver);
        }
        if let Some(driver) = timer_driver {
            runtime_state.set_timer_driver(driver);
        }
        if let Some(source) = entropy_source {
            runtime_state.set_entropy_source(source);
        }
        runtime_state
    }

    fn initialize_root_region(
        config: &RuntimeConfig,
        state: &Arc<crate::sync::ContendedMutex<RuntimeState>>,
    ) -> crate::types::RegionId {
        let mut guard = state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(observability) = config.observability.clone() {
            guard.set_observability_config(observability);
        }
        if let Some(mode) = config.logical_clock_mode.clone() {
            guard.set_logical_clock_mode(mode);
        }
        guard.set_cancel_attribution_config(config.cancel_attribution);
        guard.set_obligation_leak_response(config.obligation_leak_response);
        guard.set_leak_escalation(config.leak_escalation);
        if guard.timer_driver().is_none() {
            guard.set_timer_driver(TimerDriverHandle::with_wall_clock());
        }
        let root = guard.create_root_region(Budget::INFINITE);
        if let Some(limits) = config.root_region_limits.clone() {
            let _ = guard.set_region_limits(root, limits);
        }
        root
    }

    fn new(
        config: RuntimeConfig,
        reactor: Option<Arc<dyn Reactor>>,
        io_driver: Option<IoDriverHandle>,
        timer_driver: Option<TimerDriverHandle>,
        entropy_source: Option<Arc<dyn EntropySource>>,
        host_services: &dyn RuntimeHostServices,
    ) -> (Self, Vec<ThreeLaneWorker>) {
        // Runtime currently instantiates the unified RuntimeState path.
        // ShardedState exists behind migration work, but there is not yet a
        // RuntimeConfig layout switch wired here (see bd-2f7uj runbook).
        let runtime_state = Self::initialize_runtime_state(
            &config,
            reactor,
            io_driver,
            timer_driver,
            entropy_source,
        );
        let state = Arc::new(crate::sync::ContendedMutex::new(
            "runtime_state",
            runtime_state,
        ));
        let root_region = Self::initialize_root_region(&config, &state);

        let mut scheduler = ThreeLaneScheduler::new_with_options(
            config.worker_threads,
            &state,
            config.cancel_lane_max_streak,
            config.enable_governor,
            config.governor_interval,
        );
        scheduler.set_steal_batch_size(config.steal_batch_size);
        scheduler.set_enable_parking(config.enable_parking);
        scheduler.set_global_queue_limit(config.global_queue_limit);
        scheduler.set_browser_ready_handoff_limit(config.browser_ready_handoff_limit);
        scheduler.set_adaptive_cancel_streak(
            config.enable_adaptive_cancel_streak,
            config.adaptive_cancel_streak_epoch_steps,
        );
        let workers = scheduler.take_workers();

        let deadline_monitor = host_services.start_deadline_monitor(&config, &state);

        let blocking_pool = Self::create_blocking_pool(&config);
        if let Some(pool) = blocking_pool.as_ref() {
            let mut guard = state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            guard.set_blocking_pool(pool.handle());
        }

        (
            Self {
                config,
                state,
                scheduler,
                worker_threads: Mutex::new(Vec::new()),
                root_region,
                blocking_pool,
                deadline_monitor_shutdown: deadline_monitor.shutdown,
                deadline_monitor_thread: deadline_monitor.thread,
            },
            workers,
        )
    }

    /// Creates the blocking pool if configured with non-zero max threads.
    fn create_blocking_pool(
        config: &RuntimeConfig,
    ) -> Option<crate::runtime::blocking_pool::BlockingPool> {
        if config.blocking.max_threads == 0 {
            return None;
        }
        let options = crate::runtime::blocking_pool::BlockingPoolOptions {
            idle_timeout: Duration::from_secs(10),
            thread_name_prefix: format!("{}-blocking", config.thread_name_prefix),
            on_thread_start: config.on_thread_start.clone(),
            on_thread_stop: config.on_thread_stop.clone(),
            ..Default::default()
        };
        Some(crate::runtime::blocking_pool::BlockingPool::with_config(
            config.blocking.min_threads,
            config.blocking.max_threads,
            options,
        ))
    }

    fn spawn<F>(&self, future: F) -> Result<JoinHandle<F::Output>, SpawnError>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        let join_state = Arc::new(Mutex::new(JoinState::new()));
        let join_state_for_task = Arc::clone(&join_state);

        let wrapped = async move {
            // Ensure panics in the spawned task don't take down a worker thread. If the join
            // handle is awaited, we re-raise the original panic payload on the awaiter.
            let result = CatchUnwind { inner: future }.await;
            complete_task(&join_state_for_task, result);
        };

        let task_id = {
            let mut guard = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (task_id, _handle) = guard.create_task(self.root_region, Budget::new(), wrapped)?;
            task_id
        };

        self.scheduler.inject_ready(task_id, Budget::new().priority);

        Ok(JoinHandle::new(join_state))
    }

    /// Spawn a task with a [`Cx`](crate::cx::Cx) passed to the factory closure.
    ///
    /// The Cx is created in the root region and linked to the runtime's
    /// cancellation tree, so it will observe cancellation when the runtime
    /// shuts down.
    fn spawn_with_cx<F, Fut>(&self, f: F) -> Result<(), SpawnError>
    where
        F: FnOnce(crate::cx::Cx) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        use crate::runtime::StoredTask;
        use crate::types::Outcome;

        let task_id = {
            let mut guard = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);

            let (task_id, _handle, cx, _result_tx) =
                guard.create_task_infrastructure::<()>(self.root_region, Budget::new(), false)?;

            let future = f(cx);

            let wrapped = async move {
                future.await;
                Outcome::Ok(())
            };

            guard.store_spawned_task(task_id, StoredTask::new_with_id(wrapped, task_id));
            drop(guard);

            task_id
        };

        self.scheduler.inject_ready(task_id, Budget::new().priority);

        Ok(())
    }

    /// Returns a handle to the blocking pool, if configured.
    fn blocking_handle(&self) -> Option<crate::runtime::blocking_pool::BlockingPoolHandle> {
        self.blocking_pool
            .as_ref()
            .map(crate::runtime::blocking_pool::BlockingPool::handle)
    }
}

impl Drop for RuntimeInner {
    fn drop(&mut self) {
        // Signal deadline monitor to stop, then join its thread.
        if let Some(shutdown) = self.deadline_monitor_shutdown.take() {
            shutdown.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        if let Some(thread) = self.deadline_monitor_thread.take() {
            let _ = thread.join();
        }
        self.scheduler.shutdown();
        // Shutdown blocking pool first (it may have tasks that need to drain)
        if let Some(pool) = self.blocking_pool.take() {
            pool.shutdown();
        }
        let mut handles = lock_state(&self.worker_threads);
        for handle in handles.drain(..) {
            let _ = handle.join();
        }
    }
}

struct JoinState<T> {
    result: Option<std::thread::Result<T>>,
    waker: Option<Waker>,
}

impl<T> JoinState<T> {
    fn new() -> Self {
        Self {
            result: None,
            waker: None,
        }
    }
}

fn lock_state<T>(state: &Mutex<T>) -> MutexGuard<'_, T> {
    state.lock()
}

fn complete_task<T>(state: &Arc<Mutex<JoinState<T>>>, output: std::thread::Result<T>) {
    let waker = {
        let mut guard = lock_state(state);
        guard.result = Some(output);
        guard.waker.take()
    };
    if let Some(waker) = waker {
        waker.wake();
    }
}

struct ThreadWaker {
    thread: std::thread::Thread,
    woken: std::sync::atomic::AtomicBool,
}

use std::task::Wake;
impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.woken.store(true, std::sync::atomic::Ordering::Release);
        self.thread.unpark();
    }
    fn wake_by_ref(self: &Arc<Self>) {
        self.woken.store(true, std::sync::atomic::Ordering::Release);
        self.thread.unpark();
    }
}

fn run_future_with_budget<F: Future>(future: F, poll_budget: u32) -> F::Output {
    let thread = std::thread::current();
    let thread_waker = Arc::new(ThreadWaker {
        thread,
        woken: std::sync::atomic::AtomicBool::new(false),
    });
    let waker = Waker::from(Arc::clone(&thread_waker));
    let mut cx = Context::from_waker(&waker);
    let mut future = std::pin::pin!(future);
    let mut polls = 0u32;
    let budget = poll_budget.max(1);
    let mut consecutive_budget_exhaustions: u32 = 0;

    loop {
        // Clear the woken flag BEFORE polling. This tracks if the future
        // wakes itself during the poll or immediately after.
        thread_waker
            .woken
            .store(false, std::sync::atomic::Ordering::Relaxed);

        match future.as_mut().poll(&mut cx) {
            Poll::Ready(output) => return output,
            Poll::Pending => {
                if thread_waker
                    .woken
                    .load(std::sync::atomic::Ordering::Acquire)
                {
                    // The future was woken without parking. This indicates a spin.
                    polls = polls.saturating_add(1);
                    if polls >= budget {
                        // Budget exhausted: the future keeps returning Pending despite
                        // immediate wakeups. Use exponential backoff sleep to prevent a
                        // tight spin loop.
                        consecutive_budget_exhaustions =
                            consecutive_budget_exhaustions.saturating_add(1);
                        let backoff_ms = match consecutive_budget_exhaustions {
                            1 => 1,
                            2 => 5,
                            _ => 25,
                        };
                        std::thread::sleep(Duration::from_millis(backoff_ms));
                        polls = 0;
                    }
                } else {
                    // Not woken. We can safely park. The task is yielding to the OS,
                    // so it is NOT in a tight spin loop. We must reset the spin counters
                    // to prevent penalizing long-lived futures that genuinely wait.
                    polls = 0;
                    consecutive_budget_exhaustions = 0;
                    std::thread::park();
                }
            }
        }
    }
}

fn build_request_cx_from_inner(inner: &Arc<RuntimeInner>, budget: Budget) -> crate::cx::Cx {
    let task = crate::types::TaskId::new_ephemeral();
    let (observability, io_driver, timer_driver, blocking_pool, logical_clock, entropy, trace) = {
        let guard = inner
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let timer_driver = guard.timer_driver_handle();
        let logical_clock = guard
            .logical_clock_mode()
            .build_handle(timer_driver.clone());
        (
            guard.observability_for_task(inner.root_region, task),
            guard.io_driver_handle(),
            timer_driver,
            guard.blocking_pool_handle(),
            logical_clock,
            guard.entropy_source().fork(task),
            guard.trace_handle(),
        )
    };

    let request_cx = crate::cx::Cx::new_with_drivers(
        inner.root_region,
        task,
        budget,
        observability,
        io_driver,
        None,
        timer_driver,
        Some(entropy),
    )
    .with_blocking_pool_handle(blocking_pool)
    .with_logical_clock(logical_clock);
    request_cx.set_trace_buffer(trace);
    request_cx
}

#[cfg(test)]
#[allow(unsafe_code)]
mod tests {
    use super::*;
    use crate::cx::Cx;
    use crate::lab::{LabConfig, LabRuntime};
    use crate::record::TaskRecord;
    use crate::runtime::reactor::{Event, Interest, LabReactor, Reactor};
    use crate::test_utils::init_test_logging;
    use crate::time::sleep;
    use crate::trace::{TraceEvent, TraceEventKind};
    use crate::types::{Budget, CancelReason, CxInner, Time};
    use parking_lot::RwLock;
    use std::collections::HashSet;
    use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
    use std::time::Duration;

    static CURRENT_HANDLE_DTOR_STATE: AtomicU8 = AtomicU8::new(0);

    thread_local! {
        static CURRENT_HANDLE_DTOR_PROBE: CurrentHandleDtorProbe = const { CurrentHandleDtorProbe };
    }

    struct CurrentHandleDtorProbe;

    impl Drop for CurrentHandleDtorProbe {
        fn drop(&mut self) {
            let state = match CURRENT_RUNTIME_HANDLE.try_with(|cell| cell.borrow().clone()) {
                Ok(Some(_)) => 1,
                Ok(None) => 2,
                Err(_) => {
                    if Runtime::current_handle().is_none() {
                        3
                    } else {
                        4
                    }
                }
            };
            CURRENT_HANDLE_DTOR_STATE.store(state, Ordering::SeqCst);
        }
    }

    fn noop_waker() -> Waker {
        std::task::Waker::noop().clone()
    }

    fn panic_payload_to_string(payload: Box<dyn std::any::Any + Send>) -> String {
        match payload.downcast::<String>() {
            Ok(message) => *message,
            Err(payload) => payload.downcast::<&'static str>().map_or_else(
                |_| "<non-string panic payload>".to_string(),
                |message| (*message).to_string(),
            ),
        }
    }

    #[derive(Default)]
    struct RecordingNativeHostServices {
        worker_bootstrap_calls: AtomicUsize,
        deadline_monitor_calls: AtomicUsize,
    }

    impl RuntimeHostServices for RecordingNativeHostServices {
        fn kind(&self) -> RuntimeHostServicesKind {
            RuntimeHostServicesKind::NativeStdThread
        }

        fn spawn_workers(
            &self,
            runtime: &Arc<RuntimeInner>,
            workers: Vec<ThreeLaneWorker>,
        ) -> io::Result<Vec<std::thread::JoinHandle<()>>> {
            self.worker_bootstrap_calls.fetch_add(1, Ordering::SeqCst);
            NativeThreadHostServices::spawn_worker_threads(runtime, workers)
        }

        fn start_deadline_monitor(
            &self,
            config: &RuntimeConfig,
            state: &Arc<crate::sync::ContendedMutex<RuntimeState>>,
        ) -> DeadlineMonitorHostService {
            self.deadline_monitor_calls.fetch_add(1, Ordering::SeqCst);
            NativeThreadHostServices::start_deadline_monitor(config, state)
        }
    }

    #[test]
    fn browser_host_services_contract_pins_threadless_startup_requirements() {
        let contract = BrowserHostServicesContract::V1;
        assert!(
            contract
                .required_capabilities
                .contains(&"host-turn wakeups"),
            "browser contract must require host-turn wakeups"
        );
        assert!(
            contract
                .required_capabilities
                .contains(&"worker bootstrap hooks"),
            "browser contract must require worker bootstrap hooks"
        );
        assert!(
            contract
                .required_capabilities
                .contains(&"timer/deadline driving"),
            "browser contract must require timer/deadline driving"
        );
        assert!(
            contract
                .required_capabilities
                .contains(&"lane-health callbacks"),
            "browser contract must require lane-health callbacks"
        );
        assert!(
            contract
                .diagnostic_requirements()
                .contains("threadless startup"),
            "diagnostics should explain why the browser path is threadless"
        );
    }

    #[test]
    fn browser_bootstrap_error_describes_host_services_requirements() {
        let message = unsupported_browser_bootstrap_message(&NativeThreadHostServices::new());
        assert!(
            message.contains("RuntimeHostServices seam"),
            "diagnostic should name the startup seam: {message}"
        );
        assert!(
            message.contains("native-std-thread"),
            "diagnostic should name the shipped native host implementation: {message}"
        );
        assert!(
            message.contains("host-turn wakeups") && message.contains("lane-health callbacks"),
            "diagnostic should enumerate the missing browser host requirements: {message}"
        );
        assert!(
            message.contains("threadless startup"),
            "diagnostic should explain the threadless browser target: {message}"
        );
    }

    fn browser_probe(
        host_role: BrowserExecutionHostRole,
        runtime_context: BrowserRuntimeContext,
        has_window: bool,
        has_document: bool,
        has_webassembly: bool,
    ) -> BrowserExecutionProbe {
        BrowserExecutionProbe {
            has_global_this: true,
            runtime_context,
            host_role,
            capabilities: BrowserCapabilitySnapshot {
                execution_api: BrowserExecutionApiCapabilities {
                    has_abort_controller: true,
                    has_fetch: true,
                    has_webassembly,
                },
                dom: BrowserDomCapabilities {
                    has_document,
                    has_window,
                },
                storage: browser_storage_capabilities_for_host_role(host_role),
                transport: BrowserTransportCapabilities {
                    has_web_socket: true,
                    has_web_transport: false,
                },
            },
        }
    }

    #[test]
    fn browser_execution_ladder_selects_main_thread_lane_for_supported_probe() {
        let diagnostics = build_browser_execution_ladder_from_probe(
            None,
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                true,
            ),
        );

        assert!(
            diagnostics.supported,
            "main-thread probe should be supported"
        );
        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::BrowserMainThreadDirectRuntime,
            "main-thread probe should select the main-thread direct-runtime lane"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::Supported,
            "supported probe should keep the supported reason code"
        );
        assert_eq!(
            diagnostics.host_role,
            BrowserExecutionHostRole::BrowserMainThread,
            "host role should stay on the browser main thread"
        );
        assert_eq!(
            diagnostics.runtime_context,
            BrowserRuntimeContext::BrowserMainThread,
            "runtime context should stay on the browser main thread"
        );
        let selected_candidate = diagnostics
            .candidates
            .iter()
            .find(|candidate| candidate.selected)
            .expect("one selected candidate");
        assert_eq!(
            selected_candidate.lane_id,
            BrowserExecutionLane::BrowserMainThreadDirectRuntime,
            "selected candidate should match the selected lane"
        );
        assert!(
            diagnostics.capabilities.storage.has_indexed_db,
            "main-thread probe should surface IndexedDB availability in ladder diagnostics"
        );
        assert!(
            diagnostics.capabilities.storage.has_local_storage,
            "main-thread probe should surface localStorage availability in ladder diagnostics"
        );
    }

    #[test]
    fn browser_execution_ladder_preserves_truthful_lane_when_preferred_lane_mismatches() {
        let diagnostics = build_browser_execution_ladder_from_probe(
            Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime),
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                true,
            ),
        );

        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::BrowserMainThreadDirectRuntime,
            "preferred-lane mismatch must not override the truthful selected lane"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::Supported,
            "preferred-lane mismatch should not rewrite the truthful selected reason"
        );
        assert!(
            diagnostics
                .message
                .contains("lane.browser.dedicated_worker.direct_runtime"),
            "message should name the preferred lane mismatch"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("switch entrypoints")),
            "guidance should explain how to satisfy the preferred lane"
        );
    }

    #[test]
    fn browser_execution_ladder_keeps_prerequisite_reason_when_preferred_lane_fails_closed() {
        let diagnostics = build_browser_execution_ladder_from_probe(
            Some(BrowserExecutionLane::BrowserMainThreadDirectRuntime),
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                false,
            ),
        );

        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::Unsupported,
            "missing prerequisites should still fail closed to lane.unsupported"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::MissingWebAssembly,
            "preferred-lane mismatch must preserve the real missing-prerequisite reason"
        );
        assert!(
            diagnostics.message.contains("missing_webassembly"),
            "message should preserve the real missing-prerequisite reason code"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("Restore the reported Browser Edition prerequisites")),
            "guidance should explain how to restore the missing prerequisite"
        );
    }

    #[test]
    fn browser_execution_ladder_distinguishes_intentional_fail_closed_preference() {
        let diagnostics = build_browser_execution_ladder_from_probe(
            Some(BrowserExecutionLane::Unsupported),
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                true,
            ),
        );

        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::BrowserMainThreadDirectRuntime,
            "preferred fallback pin must not override the truthful direct-runtime lane"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::Supported,
            "preferred fallback pin should not rewrite the selected reason"
        );
        assert!(
            diagnostics
                .message
                .contains("lower-priority fail-closed fallback"),
            "message should describe the explicit fallback pin instead of a host-role mismatch"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("Only pin")),
            "guidance should explain that lane.unsupported is an intentional fail-closed pin"
        );
    }

    #[test]
    fn browser_execution_ladder_fail_closes_non_browser_probe() {
        let diagnostics =
            build_browser_execution_ladder_from_probe(None, BrowserExecutionProbe::non_browser());

        assert!(!diagnostics.supported, "non-browser probe must fail closed");
        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::Unsupported,
            "non-browser probe must demote to the terminal unsupported lane"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::MissingGlobalThis,
            "non-browser probe should surface the missing-global diagnostic"
        );
    }

    #[test]
    fn browser_execution_ladder_fail_closes_service_worker_probe_with_not_shipped_reason() {
        let diagnostics = RuntimeBuilder::new()
            .inspect_browser_execution_ladder_for_probe(BrowserExecutionProbe::service_worker());

        assert!(!diagnostics.supported, "service worker must fail close");
        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::Unsupported,
            "service worker must remain on the fail-closed lane"
        );
        assert_eq!(
            diagnostics.host_role,
            BrowserExecutionHostRole::ServiceWorker,
            "service worker probe must preserve host role"
        );
        assert_eq!(
            diagnostics.runtime_context,
            BrowserRuntimeContext::ServiceWorker,
            "service worker probe must preserve the explicit service-worker runtime context"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::ServiceWorkerDirectRuntimeNotShipped,
            "service worker probe must preserve the explicit not-shipped reason"
        );
        assert_eq!(
            diagnostics.runtime_support.reason,
            BrowserRuntimeSupportReason::ServiceWorkerNotYetShipped,
            "runtime-support reason must stay aligned with the execution-ladder reason"
        );
        assert_eq!(
            diagnostics.runtime_support.runtime_context,
            BrowserRuntimeContext::ServiceWorker,
            "runtime-support diagnostics must preserve the explicit service-worker runtime context"
        );
        assert!(
            diagnostics.capabilities.storage.has_indexed_db,
            "service-worker probe should surface truthful IndexedDB support even while direct runtime stays fail-closed"
        );
        assert!(
            !diagnostics.capabilities.storage.has_local_storage,
            "service-worker probe should keep localStorage unavailable"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("service-worker broker")),
            "service-worker guidance should point callers at the bounded broker helpers"
        );
    }

    #[test]
    fn browser_service_worker_broker_support_is_explicit_for_service_worker_probe() {
        let diagnostics = RuntimeBuilder::new()
            .inspect_browser_service_worker_broker_support_for_probe(
                BrowserExecutionProbe::service_worker(),
            );

        assert!(
            diagnostics.supported,
            "service-worker broker support must be explicit for a truthful service-worker probe"
        );
        assert_eq!(
            diagnostics.contract_id, BROWSER_SERVICE_WORKER_BROKER_CONTRACT_ID,
            "service-worker broker contract id must stay stable"
        );
        assert_eq!(
            diagnostics.requested_lane, BROWSER_SERVICE_WORKER_BROKER_LANE,
            "service-worker broker lane id must stay stable"
        );
        assert_eq!(
            diagnostics.fallback_target,
            BrowserWorkerFallbackTarget::DedicatedWorkerDirectRuntime,
            "service-worker broker should prefer the dedicated-worker fallback first"
        );
        assert_eq!(
            diagnostics.fallback_lane_id,
            Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime),
            "service-worker broker should map its first fallback to the dedicated-worker lane"
        );
        assert_eq!(
            diagnostics.reason,
            BrowserServiceWorkerBrokerSupportReason::Supported,
            "service-worker broker reason must remain supported on the truthful host"
        );
        assert_eq!(
            diagnostics.direct_runtime_reason,
            BrowserRuntimeSupportReason::ServiceWorkerNotYetShipped,
            "service-worker broker must preserve the fail-closed direct-runtime truth"
        );
        assert_eq!(
            diagnostics.direct_execution_reason_code,
            BrowserExecutionReasonCode::ServiceWorkerDirectRuntimeNotShipped,
            "service-worker broker must preserve the fail-closed direct execution reason"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("registration-scope")),
            "service-worker broker guidance should preserve explicit broker-admission boundaries"
        );
    }

    #[test]
    fn browser_execution_ladder_fail_closes_shared_worker_probe_with_not_shipped_reason() {
        let diagnostics = RuntimeBuilder::new()
            .inspect_browser_execution_ladder_for_probe(BrowserExecutionProbe::shared_worker());

        assert!(!diagnostics.supported, "shared worker must fail close");
        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::Unsupported,
            "shared worker must remain on the fail-closed lane"
        );
        assert_eq!(
            diagnostics.host_role,
            BrowserExecutionHostRole::SharedWorker,
            "shared worker probe must preserve host role"
        );
        assert_eq!(
            diagnostics.runtime_context,
            BrowserRuntimeContext::SharedWorker,
            "shared worker probe must preserve the explicit shared-worker runtime context"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::SharedWorkerDirectRuntimeNotShipped,
            "shared worker probe must preserve the explicit not-shipped reason"
        );
        assert_eq!(
            diagnostics.runtime_support.reason,
            BrowserRuntimeSupportReason::SharedWorkerNotYetShipped,
            "runtime-support reason must stay aligned with the execution-ladder reason"
        );
        assert_eq!(
            diagnostics.runtime_support.runtime_context,
            BrowserRuntimeContext::SharedWorker,
            "runtime-support diagnostics must preserve the explicit shared-worker runtime context"
        );
        assert!(
            diagnostics.capabilities.storage.has_indexed_db,
            "shared-worker probe should surface truthful IndexedDB support even while direct runtime stays fail-closed"
        );
        assert!(
            !diagnostics.capabilities.storage.has_local_storage,
            "shared-worker probe should keep localStorage unavailable"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("shared-worker coordinator")),
            "shared-worker guidance should point callers at the bounded coordinator helpers"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("browser main-thread or dedicated-worker")),
            "shared-worker guidance should preserve the truthful caller boundary"
        );
    }

    #[test]
    fn browser_shared_worker_coordinator_support_is_explicit_for_supported_callers() {
        let main_thread = RuntimeBuilder::new()
            .inspect_browser_shared_worker_coordinator_support_for_probe(
                BrowserExecutionProbe::browser_main_thread(),
            );
        let dedicated_worker = RuntimeBuilder::new()
            .inspect_browser_shared_worker_coordinator_support_for_probe(
                BrowserExecutionProbe::dedicated_worker(),
            );

        assert!(
            main_thread.supported,
            "browser main thread must remain a truthful shared-worker coordinator caller"
        );
        assert_eq!(
            main_thread.contract_id, BROWSER_SHARED_WORKER_COORDINATOR_CONTRACT_ID,
            "shared-worker coordinator contract id must stay stable"
        );
        assert_eq!(
            main_thread.requested_lane, BROWSER_SHARED_WORKER_COORDINATOR_LANE,
            "shared-worker coordinator lane id must stay stable"
        );
        assert_eq!(
            main_thread.fallback_target,
            BrowserWorkerFallbackTarget::BrowserMainThreadDirectRuntime,
            "browser main-thread callers should preserve their current lane as the first truthful fallback"
        );
        assert_eq!(
            main_thread.fallback_lane_id,
            Some(BrowserExecutionLane::BrowserMainThreadDirectRuntime),
            "browser main-thread callers should map the first fallback to the current direct-runtime lane"
        );
        assert_eq!(
            main_thread.reason,
            BrowserSharedWorkerCoordinatorSupportReason::Supported,
            "browser main-thread callers must preserve the bounded coordinator support reason"
        );
        assert_eq!(
            main_thread.direct_runtime_reason,
            BrowserRuntimeSupportReason::SharedWorkerNotYetShipped,
            "caller-side coordinator diagnostics must preserve the shared-worker fail-closed truth"
        );
        assert_eq!(
            main_thread.direct_execution_reason_code,
            BrowserExecutionReasonCode::SharedWorkerDirectRuntimeNotShipped,
            "caller-side coordinator diagnostics must preserve the shared-worker execution reason"
        );
        assert!(
            main_thread
                .guidance
                .iter()
                .any(|entry| entry.contains("same-origin")),
            "shared-worker coordinator guidance should preserve explicit JS attach prerequisites"
        );

        assert!(
            dedicated_worker.supported,
            "dedicated-worker callers must remain truthful shared-worker coordinator callers"
        );
        assert_eq!(
            dedicated_worker.fallback_target,
            BrowserWorkerFallbackTarget::DedicatedWorkerDirectRuntime,
            "dedicated-worker callers should preserve their current lane as the first truthful fallback"
        );
        assert_eq!(
            dedicated_worker.fallback_lane_id,
            Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime),
            "dedicated-worker callers should map the first fallback to the current direct-runtime lane"
        );
    }

    #[test]
    fn browser_shared_worker_coordinator_support_rejects_shared_worker_host() {
        let diagnostics = RuntimeBuilder::new()
            .inspect_browser_shared_worker_coordinator_support_for_probe(
                BrowserExecutionProbe::shared_worker(),
            );

        assert!(
            !diagnostics.supported,
            "shared-worker coordinator preflight must reject the shared-worker host itself"
        );
        assert_eq!(
            diagnostics.reason,
            BrowserSharedWorkerCoordinatorSupportReason::SharedWorkerApiMissing,
            "shared-worker coordinator preflight must preserve the unsupported-caller reason"
        );
        assert!(
            diagnostics
                .guidance
                .iter()
                .any(|entry| entry.contains("browser main-thread or dedicated-worker")),
            "shared-worker coordinator rejection guidance must preserve the truthful caller boundary"
        );
    }

    #[test]
    fn browser_execution_ladder_preserves_truthful_worker_storage_snapshots() {
        let dedicated = RuntimeBuilder::new()
            .inspect_browser_execution_ladder_for_probe(BrowserExecutionProbe::dedicated_worker());

        assert!(
            dedicated.capabilities.storage.has_indexed_db,
            "dedicated-worker probe should surface IndexedDB availability"
        );
        assert!(
            !dedicated.capabilities.storage.has_local_storage,
            "dedicated-worker probe should keep localStorage unavailable"
        );
    }

    #[test]
    fn browser_execution_ladder_keeps_missing_webassembly_visible_in_candidates() {
        let diagnostics = build_browser_execution_ladder_from_probe(
            None,
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                false,
            ),
        );

        assert_eq!(
            diagnostics.selected_lane,
            BrowserExecutionLane::Unsupported,
            "missing WebAssembly must fail closed to the unsupported lane"
        );
        assert_eq!(
            diagnostics.reason_code,
            BrowserExecutionReasonCode::MissingWebAssembly,
            "selected reason should preserve the real missing-prerequisite failure"
        );
        let direct_candidate = diagnostics
            .candidates
            .iter()
            .find(|candidate| {
                candidate.lane_id == BrowserExecutionLane::BrowserMainThreadDirectRuntime
            })
            .expect("main-thread candidate");
        assert_eq!(
            direct_candidate.reason_code,
            BrowserExecutionReasonCode::CandidatePrerequisiteMissing,
            "direct lane candidate should remain a prerequisite-missing rejection"
        );
    }

    #[test]
    fn browser_runtime_builder_selection_constructs_runtime_for_supported_probe() {
        let selection = build_browser_runtime_selection_from_probe(
            None,
            None,
            WasmAbortPropagationMode::Bidirectional,
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                true,
            ),
        );

        assert!(
            selection.runtime_available(),
            "supported probe should construct a preview browser runtime"
        );
        assert_eq!(
            selection.execution_ladder.selected_lane,
            BrowserExecutionLane::BrowserMainThreadDirectRuntime,
            "supported probe should stay on the truthful main-thread lane"
        );
        let runtime = selection.runtime.expect("supported runtime");
        let scope = runtime
            .enter_scope(Some("browser-runtime-selection-smoke"))
            .expect("scope should open");
        let scope_close = runtime
            .close_scope(&scope)
            .expect("scope close should succeed");
        assert!(
            matches!(scope_close, WasmAbiOutcomeEnvelope::Ok { .. }),
            "scope close should return an ok outcome"
        );
        let runtime_close = runtime.close().expect("runtime close should succeed");
        assert!(
            matches!(runtime_close, WasmAbiOutcomeEnvelope::Ok { .. }),
            "runtime close should return an ok outcome"
        );
        assert!(
            runtime.dispatcher_diagnostics().is_clean(),
            "dispatcher should be clean after full runtime teardown"
        );
    }

    #[test]
    fn browser_runtime_builder_selection_preserves_truthful_lane_under_mismatch() {
        let selection = build_browser_runtime_selection_from_probe(
            Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime),
            None,
            WasmAbortPropagationMode::Bidirectional,
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                true,
            ),
        );

        assert!(
            selection.runtime_available(),
            "preferred-lane mismatch should still construct a runtime when a truthful lane exists"
        );
        assert_eq!(
            selection.execution_ladder.selected_lane,
            BrowserExecutionLane::BrowserMainThreadDirectRuntime,
            "preferred-lane mismatch must preserve the truthful selected lane"
        );
        assert_eq!(
            selection.execution_ladder.preferred_lane,
            Some(BrowserExecutionLane::DedicatedWorkerDirectRuntime),
            "selection should retain the requested preferred lane for diagnostics"
        );
    }

    #[test]
    fn browser_runtime_builder_selection_fail_closes_when_webassembly_missing() {
        let selection = build_browser_runtime_selection_from_probe(
            None,
            None,
            WasmAbortPropagationMode::Bidirectional,
            browser_probe(
                BrowserExecutionHostRole::BrowserMainThread,
                BrowserRuntimeContext::BrowserMainThread,
                true,
                true,
                false,
            ),
        );

        assert!(
            !selection.runtime_available(),
            "missing WebAssembly must fail close instead of constructing a runtime"
        );
        let error = selection.error.expect("structured unsupported error");
        assert!(matches!(
            error,
            BrowserRuntimeBuildError::Unsupported { .. }
        ));
        assert_eq!(
            error.execution_ladder().reason_code,
            BrowserExecutionReasonCode::MissingWebAssembly,
            "structured unsupported error must preserve the real missing-prerequisite reason"
        );
    }

    #[test]
    fn browser_runtime_builder_build_returns_structured_unsupported_error() {
        let error = BrowserRuntimeBuilder::new().build().expect_err(
            "native test host should fail-close instead of constructing a browser runtime",
        );

        assert!(matches!(
            error,
            BrowserRuntimeBuildError::Unsupported { .. }
        ));
        assert_eq!(
            error.execution_ladder().selected_lane,
            BrowserExecutionLane::Unsupported,
            "native host should fail-close to lane.unsupported"
        );
    }

    #[test]
    fn runtime_builder_routes_native_startup_through_host_services_seam() {
        init_test_logging();

        let host_services = Arc::new(RecordingNativeHostServices::default());
        let seam: Arc<dyn RuntimeHostServices> = host_services.clone();
        let mut builder = RuntimeBuilder::current_thread();
        builder.host_services = seam;

        let runtime = builder.build().expect("runtime build");
        let result = runtime.block_on(runtime.handle().spawn(async { 7u32 }));

        assert_eq!(result, 7, "runtime should remain usable through the seam");
        assert_eq!(
            host_services.worker_bootstrap_calls.load(Ordering::SeqCst),
            1,
            "worker startup should route through the host-services seam"
        );
        assert_eq!(
            host_services.deadline_monitor_calls.load(Ordering::SeqCst),
            1,
            "deadline-monitor startup should route through the host-services seam"
        );
    }

    #[test]
    fn native_deadline_monitor_releases_runtime_state_before_warning_callback() {
        init_test_logging();

        let state = Arc::new(crate::sync::ContendedMutex::new(
            "runtime-state",
            RuntimeState::new(),
        ));
        {
            let mut guard = state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let region = guard.create_root_region(Budget::INFINITE);
            guard.now = Time::from_secs(100);
            let budget = Budget::new().with_deadline(Time::from_secs(110));
            let idx = guard.insert_task_with(|idx| {
                let task_id = crate::types::TaskId::from_arena(idx);
                let mut record = TaskRecord::new_with_time(task_id, region, budget, Time::ZERO);
                let mut inner = CxInner::new(region, task_id, budget);
                inner.checkpoint_state.last_checkpoint = Some(Time::ZERO);
                inner.checkpoint_state.checkpoint_count = 1;
                record.set_cx_inner(Arc::new(RwLock::new(inner)));
                record
            });
            let task_id = crate::types::TaskId::from_arena(idx);
            guard
                .regions
                .get(region.arena_index())
                .expect("root region exists")
                .add_task(task_id)
                .expect("task admission succeeds");
        }

        let (tx, rx) = std::sync::mpsc::channel();
        let state_for_handler = Arc::clone(&state);
        let mut config = RuntimeConfig::default();
        config.thread_name_prefix = "deadline-monitor-test".to_string();
        config.deadline_monitor = Some(MonitorConfig {
            check_interval: Duration::from_millis(1),
            warning_threshold_fraction: 0.2,
            checkpoint_timeout: Duration::from_millis(1),
            adaptive: AdaptiveDeadlineConfig::default(),
            enabled: true,
        });
        config.deadline_warning_handler = Some(Arc::new(move |_| {
            let reacquired = state_for_handler.try_lock().is_ok();
            let _ = tx.send(reacquired);
        }));

        let service = NativeThreadHostServices::start_deadline_monitor(&config, &state);
        let reacquired = rx
            .recv_timeout(Duration::from_secs(1))
            .expect("deadline warning callback should fire");

        if let Some(shutdown) = service.shutdown.as_ref() {
            shutdown.store(true, Ordering::Relaxed);
        }
        if let Some(thread) = service.thread {
            thread.join().expect("deadline monitor thread should stop");
        }

        assert!(
            reacquired,
            "warning callback must run after dropping the runtime-state lock"
        );
    }

    #[test]
    fn runtime_handle_spawn_completes_via_scheduler() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(2)
            .build()
            .expect("runtime build");

        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = Arc::clone(&flag);

        let handle = runtime.handle().spawn(async move {
            flag_clone.store(true, Ordering::SeqCst);
            42u32
        });

        let result = runtime.block_on(handle);
        assert_eq!(result, 42);
        assert!(flag.load(Ordering::SeqCst));
    }

    #[test]
    fn runtime_spawn_blocking_executes_on_pool() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(1)
            .blocking_threads(1, 2)
            .build()
            .expect("runtime build");

        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = Arc::clone(&flag);

        // Spawn blocking task via runtime
        let handle = runtime
            .spawn_blocking(move || {
                flag_clone.store(true, Ordering::SeqCst);
            })
            .expect("blocking pool configured");

        // Wait for completion
        handle.wait();
        assert!(flag.load(Ordering::SeqCst), "blocking task should have run");
    }

    #[test]
    fn runtime_without_blocking_pool_returns_none() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(1)
            .blocking_threads(0, 0)
            .build()
            .expect("runtime build");

        let handle = runtime.spawn_blocking(|| {});
        assert!(
            handle.is_none(),
            "spawn_blocking should return None when pool is not configured"
        );
        assert!(
            runtime.blocking_handle().is_none(),
            "blocking_handle should return None"
        );
    }

    #[test]
    fn runtime_builder_platform_seams_propagate_into_task_contexts() {
        init_test_logging();

        let io_driver = IoDriverHandle::new(Arc::new(LabReactor::new()));
        {
            let mut driver = io_driver.lock();
            let _ = driver.register_waker(noop_waker());
        }

        let virtual_clock = Arc::new(crate::time::VirtualClock::starting_at(Time::from_secs(42)));
        let timer_driver = TimerDriverHandle::with_virtual_clock(virtual_clock);

        let runtime = RuntimeBuilder::current_thread()
            .with_io_driver(io_driver)
            .with_timer_driver(timer_driver)
            .with_entropy_source(Arc::new(crate::util::DetEntropy::new(1234)))
            .build()
            .expect("runtime build");

        let (io_present, timer_now, entropy_source) =
            runtime.block_on(runtime.handle().spawn(async {
                let cx = Cx::current().expect("task context");
                (
                    cx.io_driver_handle().is_some(),
                    cx.timer_driver().map(|driver| driver.now()),
                    cx.entropy().source_id(),
                )
            }));
        assert!(io_present, "injected io driver should be visible in Cx");
        assert_eq!(
            timer_now,
            Some(Time::from_secs(42)),
            "injected virtual timer should be visible in Cx"
        );
        assert_eq!(
            entropy_source, "deterministic",
            "injected entropy source should flow through Cx"
        );

        let guard = runtime
            .inner
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let state_io = guard.io_driver_handle().expect("runtime io driver");
        assert_eq!(
            state_io.waker_count(),
            1,
            "runtime should retain the injected io driver instance"
        );
        let state_timer = guard.timer_driver_handle().expect("runtime timer driver");
        assert_eq!(
            state_timer.now(),
            Time::from_secs(42),
            "runtime should retain the injected timer driver instance"
        );
        drop(guard);
    }

    #[test]
    fn runtime_builder_platform_seams_override_reactor_defaults() {
        init_test_logging();

        let custom_driver = IoDriverHandle::new(Arc::new(LabReactor::new()));
        {
            let mut driver = custom_driver.lock();
            let _ = driver.register_waker(noop_waker());
        }
        let custom_timer = TimerDriverHandle::with_virtual_clock(Arc::new(
            crate::time::VirtualClock::starting_at(Time::from_secs(7)),
        ));

        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(Arc::new(LabReactor::new()))
            .with_io_driver(custom_driver)
            .with_timer_driver(custom_timer)
            .build()
            .expect("runtime build");

        let guard = runtime
            .inner
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let io = guard.io_driver_handle().expect("io driver");
        assert_eq!(
            io.waker_count(),
            1,
            "explicit io driver should override default reactor wiring"
        );
        let timer = guard.timer_driver_handle().expect("timer driver");
        assert_eq!(
            timer.now(),
            Time::from_secs(7),
            "explicit timer driver should override wall-clock default"
        );
        drop(guard);
    }

    #[test]
    fn runtime_builder_browser_worker_offload_policy_round_trips() {
        init_test_logging();

        let runtime = RuntimeBuilder::current_thread()
            .browser_worker_offload_enabled(true)
            .browser_worker_offload_limits(2048, 4)
            .browser_worker_transfer_mode(
                crate::runtime::config::WorkerTransferMode::CloneStructured,
            )
            .browser_worker_cancellation_mode(
                crate::runtime::config::WorkerCancellationMode::BestEffortAbort,
            )
            .build()
            .expect("runtime build");

        let offload = runtime.config().browser_worker_offload;
        assert!(offload.enabled, "offload policy should be enabled");
        assert_eq!(
            offload.min_task_cost, 2048,
            "min task cost should round-trip"
        );
        assert_eq!(
            offload.max_in_flight, 4,
            "in-flight limit should round-trip"
        );
        assert_eq!(
            offload.transfer_mode,
            crate::runtime::config::WorkerTransferMode::CloneStructured,
            "transfer mode should round-trip"
        );
        assert_eq!(
            offload.cancellation_mode,
            crate::runtime::config::WorkerCancellationMode::BestEffortAbort,
            "cancellation mode should round-trip"
        );
    }

    #[cfg(target_arch = "wasm32")]
    #[test]
    fn runtime_builder_fail_closes_browser_bootstrap_on_wasm() {
        let err = RuntimeBuilder::current_thread()
            .build()
            .expect_err("public browser bootstrap must fail closed on wasm");
        assert_eq!(
            err.kind(),
            crate::error::ErrorKind::ConfigError,
            "unsupported wasm browser bootstrap must surface as ConfigError"
        );
        let message = err.to_string();
        assert!(
            message.contains("browser bootstrap")
                && message.contains("RuntimeHostServices seam")
                && message.contains("threadless startup"),
            "error should explain why wasm browser bootstrap is still unsupported: {message}"
        );
    }

    #[derive(Debug, PartialEq, Eq)]
    struct TraceCounts {
        region_created: usize,
        spawn: usize,
        complete: usize,
        timer_scheduled: usize,
        timer_fired: usize,
        timer_cancelled: usize,
        io_requested: usize,
        io_ready: usize,
        cancel_request: usize,
    }

    fn parity_counts(events: Vec<TraceEvent>) -> TraceCounts {
        let mut counts = TraceCounts {
            region_created: 0,
            spawn: 0,
            complete: 0,
            timer_scheduled: 0,
            timer_fired: 0,
            timer_cancelled: 0,
            io_requested: 0,
            io_ready: 0,
            cancel_request: 0,
        };

        for event in events {
            match event.kind {
                TraceEventKind::RegionCreated => counts.region_created += 1,
                TraceEventKind::Spawn => counts.spawn += 1,
                TraceEventKind::Complete => counts.complete += 1,
                TraceEventKind::TimerScheduled => counts.timer_scheduled += 1,
                TraceEventKind::TimerFired => counts.timer_fired += 1,
                TraceEventKind::TimerCancelled => counts.timer_cancelled += 1,
                TraceEventKind::IoRequested => counts.io_requested += 1,
                TraceEventKind::IoReady => counts.io_ready += 1,
                TraceEventKind::CancelRequest => counts.cancel_request += 1,
                _ => {}
            }
        }

        counts
    }

    fn wait_for_runtime_quiescent(runtime: &Runtime) {
        for i in 0..2000 {
            let live_tasks = runtime
                .inner
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .live_task_count();
            if live_tasks == 0 {
                return;
            }
            if i < 100 {
                std::thread::yield_now();
            } else {
                std::thread::sleep(std::time::Duration::from_millis(1));
            }
        }
        unreachable!("runtime failed to reach quiescence after waiting");
    }

    #[cfg(unix)]
    struct TestFdSource;

    #[cfg(unix)]
    impl std::os::fd::AsRawFd for TestFdSource {
        fn as_raw_fd(&self) -> std::os::fd::RawFd {
            0
        }
    }

    #[test]
    fn lab_runtime_matches_prod_trace_for_basic_spawn() {
        init_test_logging();

        let mut lab = LabRuntime::new(LabConfig::new(7).trace_capacity(1024));
        let lab_region = lab.state.create_root_region(Budget::INFINITE);
        for _ in 0..2 {
            let (task_id, _handle) = lab
                .state
                .create_task(lab_region, Budget::INFINITE, async { 1_u8 })
                .expect("lab task spawn");
            lab.scheduler
                .lock()
                .schedule(task_id, Budget::INFINITE.priority);
            lab.run_until_quiescent();
        }

        let lab_counts = parity_counts(lab.trace().snapshot());
        assert_eq!(
            lab_counts.spawn, lab_counts.complete,
            "lab trace should complete every spawned task"
        );

        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("runtime build");
        for _ in 0..2 {
            let handle = runtime.handle().spawn(async { 1_u8 });
            let _ = runtime.block_on(handle);
        }
        wait_for_runtime_quiescent(&runtime);

        let runtime_counts = {
            let guard = runtime
                .inner
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            parity_counts(guard.trace.snapshot())
        };
        assert_eq!(
            runtime_counts.spawn, runtime_counts.complete,
            "runtime trace should complete every spawned task"
        );

        assert_eq!(lab_counts, runtime_counts);
    }

    async fn sleep_once() {
        let now = Cx::current()
            .and_then(|cx| cx.timer_driver())
            .map_or(Time::ZERO, |driver| driver.now());
        sleep(now, Duration::from_millis(1)).await;
    }

    #[test]
    #[ignore = "block_on parks thread on Pending; current-thread runtime cannot drive timers"]
    fn lab_runtime_matches_prod_trace_for_timer_sleep() {
        init_test_logging();

        let mut lab = LabRuntime::new(LabConfig::new(7).trace_capacity(1024));
        let lab_region = lab.state.create_root_region(Budget::INFINITE);
        let (task_id, _handle) = lab
            .state
            .create_task(lab_region, Budget::INFINITE, sleep_once())
            .expect("lab sleep task spawn");
        lab.scheduler
            .lock()
            .schedule(task_id, Budget::INFINITE.priority);

        lab.step_for_test(); // register timer
        lab.advance_time(1_000_000);
        lab.run_until_quiescent();

        let lab_counts = parity_counts(lab.trace().snapshot());
        assert!(
            lab_counts.timer_scheduled > 0,
            "lab trace should record timer scheduling"
        );
        assert_eq!(
            lab_counts.timer_scheduled, lab_counts.timer_fired,
            "lab trace should fire every scheduled timer"
        );

        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("runtime build");
        let handle = runtime.handle().spawn(sleep_once());
        runtime.block_on(handle);
        wait_for_runtime_quiescent(&runtime);

        let runtime_counts = {
            let guard = runtime
                .inner
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            parity_counts(guard.trace.snapshot())
        };
        assert!(
            runtime_counts.timer_scheduled > 0,
            "runtime trace should record timer scheduling"
        );
        assert_eq!(
            runtime_counts.timer_scheduled, runtime_counts.timer_fired,
            "runtime trace should fire every scheduled timer"
        );

        assert_eq!(lab_counts, runtime_counts);
    }

    #[test]
    fn lab_runtime_matches_prod_trace_for_cancel_request() {
        init_test_logging();

        let mut lab = LabRuntime::new(LabConfig::new(7).trace_capacity(1024));
        let lab_region = lab.state.create_root_region(Budget::INFINITE);
        let _ = lab
            .state
            .create_task(lab_region, Budget::INFINITE, async {
                std::future::pending::<()>().await;
            })
            .expect("lab task spawn");
        let _ = lab
            .state
            .cancel_request(lab_region, &CancelReason::user("stop"), None);
        let lab_counts = parity_counts(lab.trace().snapshot());
        assert!(
            lab_counts.cancel_request > 0,
            "lab trace should record cancel request"
        );

        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("runtime build");
        {
            let mut guard = runtime
                .inner
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let region = runtime.inner.root_region;
            let _ = guard
                .create_task(region, Budget::INFINITE, async {
                    std::future::pending::<()>().await;
                })
                .expect("runtime task spawn");
            let _ = guard.cancel_request(region, &CancelReason::user("stop"), None);
        }
        let runtime_counts = {
            let guard = runtime
                .inner
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            parity_counts(guard.trace.snapshot())
        };
        assert!(
            runtime_counts.cancel_request > 0,
            "runtime trace should record cancel request"
        );

        assert_eq!(lab_counts, runtime_counts);
    }

    #[cfg(unix)]
    #[test]
    fn lab_runtime_matches_prod_trace_for_io_ready() {
        init_test_logging();

        let mut lab = LabRuntime::new(LabConfig::new(7).trace_capacity(1024));
        let handle = lab.state.io_driver_handle().expect("lab io driver");
        let registration = handle
            .register(&TestFdSource, Interest::READABLE, noop_waker())
            .expect("lab register source");
        let io_key = registration.token();
        lab.lab_reactor()
            .inject_event(io_key, Event::readable(io_key), Duration::ZERO);
        lab.step_for_test();
        let lab_counts = parity_counts(lab.trace().snapshot());
        assert!(
            lab_counts.io_requested > 0,
            "lab trace should record io requested"
        );
        assert_eq!(
            lab_counts.io_requested, lab_counts.io_ready,
            "lab trace should record ready after request"
        );

        let reactor = Arc::new(LabReactor::new());
        let reactor_handle: Arc<dyn Reactor> = reactor.clone();
        let state = RuntimeState::with_reactor(reactor_handle);
        let driver = state.io_driver_handle().expect("runtime state io driver");
        let registration = driver
            .register(&TestFdSource, Interest::READABLE, noop_waker())
            .expect("runtime state register source");
        let io_key = registration.token();
        reactor.inject_event(io_key, Event::readable(io_key), Duration::ZERO);
        let trace = state.trace_handle();
        let now = Time::ZERO;
        let mut seen = HashSet::new();
        let _ = driver.turn_with(Some(Duration::ZERO), |event, interest| {
            let io_key = event.token.0 as u64;
            let interest_bits = interest.unwrap_or(event.ready).bits();
            if seen.insert(io_key) {
                trace.record_event(|seq| TraceEvent::io_requested(seq, now, io_key, interest_bits));
            }
            trace.record_event(|seq| TraceEvent::io_ready(seq, now, io_key, event.ready.bits()));
        });

        let runtime_counts = parity_counts(state.trace.snapshot());
        assert!(
            runtime_counts.io_requested > 0,
            "runtime trace should record io requested"
        );
        assert_eq!(
            runtime_counts.io_requested, runtime_counts.io_ready,
            "runtime trace should record ready after request"
        );

        assert_eq!(lab_counts.io_requested, runtime_counts.io_requested);
        assert_eq!(lab_counts.io_ready, runtime_counts.io_ready);
    }

    fn with_clean_env<F, R>(f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let _guard = crate::test_utils::env_lock();
        clean_env_locked();
        f()
    }

    /// Helper: set env vars for a closure, then clean up.
    fn with_envs<F, R>(vars: &[(&str, &str)], f: F) -> R
    where
        F: FnOnce() -> R,
    {
        with_clean_env(|| {
            for (k, v) in vars {
                // SAFETY: test helpers guard environment mutation with env_lock.
                unsafe { std::env::set_var(k, v) };
            }
            let result = f();
            for (k, _) in vars {
                // SAFETY: test helpers guard environment mutation with env_lock.
                unsafe { std::env::remove_var(k) };
            }
            result
        })
    }

    fn clean_env_locked() {
        use crate::runtime::env_config::*;
        for var in &[
            ENV_WORKER_THREADS,
            ENV_TASK_QUEUE_DEPTH,
            ENV_THREAD_STACK_SIZE,
            ENV_THREAD_NAME_PREFIX,
            ENV_STEAL_BATCH_SIZE,
            ENV_CANCEL_LANE_MAX_STREAK,
            ENV_ENABLE_GOVERNOR,
            ENV_GOVERNOR_INTERVAL,
            ENV_ENABLE_ADAPTIVE_CANCEL_STREAK,
            ENV_ADAPTIVE_CANCEL_EPOCH_STEPS,
            ENV_BLOCKING_MIN_THREADS,
            ENV_BLOCKING_MAX_THREADS,
            ENV_ENABLE_PARKING,
            ENV_POLL_BUDGET,
        ] {
            // SAFETY: test helpers guard environment mutation with env_lock.
            unsafe { std::env::remove_var(var) };
        }
    }

    #[test]
    fn with_env_overrides_applies_env_vars() {
        use crate::runtime::env_config::*;
        with_envs(
            &[(ENV_WORKER_THREADS, "4"), (ENV_POLL_BUDGET, "64")],
            || {
                let runtime = RuntimeBuilder::new()
                    .with_env_overrides()
                    .expect("env overrides")
                    .build()
                    .expect("runtime build");
                assert_eq!(runtime.config().worker_threads, 4);
                assert_eq!(runtime.config().poll_budget, 64);
            },
        );
    }

    #[test]
    fn programmatic_overrides_env_vars() {
        use crate::runtime::env_config::*;
        with_envs(&[(ENV_WORKER_THREADS, "8")], || {
            // Env says 8, but programmatic says 2 — programmatic wins.
            let runtime = RuntimeBuilder::new()
                .with_env_overrides()
                .expect("env overrides")
                .worker_threads(2)
                .build()
                .expect("runtime build");
            assert_eq!(runtime.config().worker_threads, 2);
        });
    }

    #[test]
    fn with_env_overrides_invalid_var_returns_error() {
        use crate::runtime::env_config::*;
        with_envs(&[(ENV_WORKER_THREADS, "not_a_number")], || {
            let result = RuntimeBuilder::new().with_env_overrides();
            assert!(result.is_err());
        });
    }

    #[test]
    fn with_env_overrides_no_vars_uses_defaults() {
        with_clean_env(|| {
            let defaults = RuntimeConfig::default();
            let runtime = RuntimeBuilder::new()
                .with_env_overrides()
                .expect("env overrides")
                .build()
                .expect("runtime build");
            assert_eq!(
                runtime.config().cancel_lane_max_streak,
                defaults.cancel_lane_max_streak
            );
            assert_eq!(runtime.config().enable_governor, defaults.enable_governor);
            assert_eq!(
                runtime.config().governor_interval,
                defaults.governor_interval
            );
            assert_eq!(
                runtime.config().enable_adaptive_cancel_streak,
                defaults.enable_adaptive_cancel_streak
            );
            assert_eq!(
                runtime.config().adaptive_cancel_streak_epoch_steps,
                defaults.adaptive_cancel_streak_epoch_steps
            );
            assert_eq!(runtime.config().poll_budget, defaults.poll_budget);
        });
    }

    #[test]
    fn with_env_overrides_applies_governor_settings() {
        use crate::runtime::env_config::*;
        with_envs(
            &[(ENV_ENABLE_GOVERNOR, "true"), (ENV_GOVERNOR_INTERVAL, "41")],
            || {
                let runtime = RuntimeBuilder::new()
                    .with_env_overrides()
                    .expect("env overrides")
                    .build()
                    .expect("runtime build");
                assert!(runtime.config().enable_governor);
                assert_eq!(runtime.config().governor_interval, 41);
            },
        );
    }

    #[cfg(feature = "config-file")]
    #[test]
    fn from_toml_str_builds_runtime() {
        let toml = r"
[scheduler]
worker_threads = 2
poll_budget = 32
";
        let runtime = RuntimeBuilder::from_toml_str(toml)
            .expect("from_toml_str")
            .build()
            .expect("runtime build");
        assert_eq!(runtime.config().worker_threads, 2);
        assert_eq!(runtime.config().poll_budget, 32);
    }

    #[cfg(feature = "config-file")]
    #[test]
    fn from_toml_str_applies_governor_settings() {
        let toml = r"
[scheduler]
enable_governor = true
governor_interval = 80
";
        let runtime = RuntimeBuilder::from_toml_str(toml)
            .expect("from_toml_str")
            .build()
            .expect("runtime build");
        assert!(runtime.config().enable_governor);
        assert_eq!(runtime.config().governor_interval, 80);
    }

    #[cfg(feature = "config-file")]
    #[test]
    fn from_toml_str_with_programmatic_override() {
        let toml = r"
[scheduler]
worker_threads = 8
";
        let runtime = RuntimeBuilder::from_toml_str(toml)
            .expect("from_toml_str")
            .worker_threads(2) // programmatic override
            .build()
            .expect("runtime build");
        assert_eq!(runtime.config().worker_threads, 2);
    }

    #[cfg(feature = "config-file")]
    #[test]
    fn from_toml_str_invalid_returns_error() {
        let result = RuntimeBuilder::from_toml_str("not valid {{{{");
        assert!(result.is_err());
    }

    #[cfg(feature = "config-file")]
    #[test]
    fn precedence_programmatic_over_env_over_toml() {
        use crate::runtime::env_config::*;
        // TOML says 16, env says 8, programmatic says 2.
        with_envs(&[(ENV_WORKER_THREADS, "8")], || {
            let toml = r"
[scheduler]
worker_threads = 16
";
            let runtime = RuntimeBuilder::from_toml_str(toml)
                .expect("from_toml_str")
                .with_env_overrides()
                .expect("env overrides")
                .worker_threads(2) // programmatic: highest priority
                .build()
                .expect("runtime build");
            assert_eq!(runtime.config().worker_threads, 2);
        });
    }

    #[cfg(feature = "config-file")]
    #[test]
    fn precedence_env_over_toml() {
        use crate::runtime::env_config::*;
        // TOML says 16, env says 8.
        with_envs(&[(ENV_WORKER_THREADS, "8")], || {
            let toml = r"
[scheduler]
worker_threads = 16
";
            let runtime = RuntimeBuilder::from_toml_str(toml)
                .expect("from_toml_str")
                .with_env_overrides()
                .expect("env overrides")
                .build()
                .expect("runtime build");
            assert_eq!(runtime.config().worker_threads, 8);
        });
    }

    // -----------------------------------------------------------------------
    // Issue #21: Thread-local RuntimeHandle from block_on
    // -----------------------------------------------------------------------

    #[test]
    fn current_handle_available_inside_block_on() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(1)
            .build()
            .expect("runtime build");

        runtime.block_on(async {
            let handle = Runtime::current_handle();
            assert!(
                handle.is_some(),
                "current_handle should be Some inside block_on"
            );
        });
    }

    #[test]
    fn current_handle_none_outside_block_on() {
        init_test_logging();
        assert!(
            Runtime::current_handle().is_none(),
            "current_handle should be None outside block_on"
        );
    }

    #[test]
    fn current_handle_spawn_completes_on_scheduler() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(2)
            .build()
            .expect("runtime build");

        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = Arc::clone(&flag);

        let result = runtime.block_on(async move {
            let handle = Runtime::current_handle().expect("inside block_on");
            let join = handle.spawn(async move {
                flag_clone.store(true, Ordering::SeqCst);
                99u32
            });
            join.await
        });

        assert_eq!(result, 99);
        assert!(flag.load(Ordering::SeqCst), "spawned task should have run");
    }

    #[test]
    fn current_handle_available_inside_spawned_task() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(2)
            .build()
            .expect("runtime build");

        let outer = runtime.handle().spawn(async {
            let handle = Runtime::current_handle().expect("spawned task should see runtime handle");
            handle.spawn(async { 42u32 }).await
        });

        assert_eq!(runtime.block_on(outer), 42);
    }

    #[test]
    fn current_handle_restored_after_block_on() {
        init_test_logging();
        // Before block_on: None.
        assert!(Runtime::current_handle().is_none());

        let runtime = RuntimeBuilder::new()
            .worker_threads(1)
            .build()
            .expect("runtime build");

        runtime.block_on(async {
            assert!(Runtime::current_handle().is_some());
        });

        // After block_on: restored to None.
        assert!(Runtime::current_handle().is_none());
    }

    #[test]
    fn current_handle_returns_none_during_thread_local_teardown() {
        init_test_logging();
        CURRENT_HANDLE_DTOR_STATE.store(0, Ordering::SeqCst);

        let join = std::thread::spawn(|| {
            // Initialize the probe first so its destructor runs after the
            // runtime handle TLS and can exercise the teardown path.
            CURRENT_HANDLE_DTOR_PROBE.with(|_| {});

            let runtime = RuntimeBuilder::current_thread()
                .build()
                .expect("runtime build");
            runtime.block_on(async {
                assert!(
                    Runtime::current_handle().is_some(),
                    "runtime handle should be installed inside block_on"
                );
            });
        });

        join.join()
            .expect("thread-local teardown should not panic when reading runtime handle");
        assert_eq!(
            CURRENT_HANDLE_DTOR_STATE.load(Ordering::SeqCst),
            3,
            "Runtime::current_handle() should fail closed once TLS is unavailable"
        );
    }

    #[test]
    fn weak_current_handle_try_spawn_returns_runtime_unavailable_after_drop() {
        init_test_logging();
        let runtime = RuntimeBuilder::new()
            .worker_threads(1)
            .build()
            .expect("runtime build");

        let weak_handle = runtime.block_on(runtime.handle().spawn(async {
            Runtime::current_handle().expect("spawned task should see runtime handle")
        }));
        assert!(
            matches!(weak_handle.inner, RuntimeHandleRef::Weak(_)),
            "worker-thread current_handle should remain weak to avoid runtime cycles"
        );

        drop(runtime);

        let result = weak_handle.try_spawn(async { 42u8 });
        assert!(
            matches!(result, Err(SpawnError::RuntimeUnavailable)),
            "stale weak handle should return RuntimeUnavailable instead of panicking"
        );
        assert!(
            weak_handle.spawn_blocking(|| {}).is_none(),
            "stale weak handle should not expose a blocking pool"
        );
        assert!(
            weak_handle.blocking_handle().is_none(),
            "stale weak handle should not yield a blocking handle"
        );
    }

    #[test]
    fn thread_callbacks_do_not_fire_for_block_on_caller() {
        init_test_logging();
        let started = Arc::new(AtomicUsize::new(0));
        let stopped = Arc::new(AtomicUsize::new(0));
        let started_for_callback = Arc::clone(&started);
        let stopped_for_callback = Arc::clone(&stopped);

        let runtime = RuntimeBuilder::new()
            .worker_threads(1)
            .on_thread_start(move || {
                started_for_callback.fetch_add(1, Ordering::SeqCst);
            })
            .on_thread_stop(move || {
                stopped_for_callback.fetch_add(1, Ordering::SeqCst);
            })
            .build()
            .expect("runtime build");

        let join = runtime.handle().spawn(async { 7u8 });
        assert_eq!(runtime.block_on(join), 7);
        assert_eq!(
            started.load(Ordering::SeqCst),
            1,
            "only the worker thread should trigger on_thread_start"
        );

        drop(runtime);

        assert_eq!(
            stopped.load(Ordering::SeqCst),
            1,
            "only the worker thread should trigger on_thread_stop"
        );
    }

    #[test]
    fn join_handle_second_poll_panics_after_success_and_stays_finished() {
        init_test_logging();

        let state = Arc::new(Mutex::new(JoinState::new()));
        complete_task(&state, Ok(7_u8));

        let mut join = std::pin::pin!(JoinHandle::new(Arc::clone(&state)));
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);

        let first = join.as_mut().poll(&mut cx);
        assert!(matches!(first, Poll::Ready(7)));
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should remain finished after consuming the result"
        );

        let second = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = join.as_mut().poll(&mut cx);
        }));
        let message =
            panic_payload_to_string(second.expect_err("second poll must fail closed by panicking"));
        assert!(
            message.contains("runtime::JoinHandle polled after completion"),
            "second poll should panic with completion misuse message, got {message}"
        );
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should remain finished after post-completion misuse"
        );
    }

    #[test]
    fn join_handle_pending_then_completion_then_repoll_panics_and_stays_finished() {
        init_test_logging();

        let state = Arc::new(Mutex::new(JoinState::new()));
        let mut join = std::pin::pin!(JoinHandle::new(Arc::clone(&state)));
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);

        let first = join.as_mut().poll(&mut cx);
        assert!(matches!(first, Poll::Pending));
        assert!(
            !join.as_ref().get_ref().is_finished(),
            "join handle should not be finished while task is still pending"
        );

        complete_task(&state, Ok(11_u8));

        let second = join.as_mut().poll(&mut cx);
        assert!(matches!(second, Poll::Ready(11)));
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should become finished after ready output is observed"
        );

        let third = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = join.as_mut().poll(&mut cx);
        }));
        let message =
            panic_payload_to_string(third.expect_err("third poll must fail closed by panicking"));
        assert!(
            message.contains("runtime::JoinHandle polled after completion"),
            "post-completion repoll should panic with completion misuse message, got {message}"
        );
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should remain finished after post-completion misuse"
        );
    }

    #[test]
    fn join_handle_second_poll_panics_after_task_panic_and_stays_finished() {
        init_test_logging();

        let state = Arc::new(Mutex::new(JoinState::<u8>::new()));
        complete_task(&state, Err(Box::new("join-handle boom")));

        let mut join = std::pin::pin!(JoinHandle::new(Arc::clone(&state)));
        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);

        let first = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = join.as_mut().poll(&mut cx);
        }));
        let first_message =
            panic_payload_to_string(first.expect_err("first poll should resume the task panic"));
        assert!(
            first_message.contains("join-handle boom"),
            "first poll should preserve the original task panic, got {first_message}"
        );
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should remain finished after propagating a task panic"
        );

        let second = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = join.as_mut().poll(&mut cx);
        }));
        let second_message =
            panic_payload_to_string(second.expect_err("second poll must fail closed by panicking"));
        assert!(
            second_message.contains("runtime::JoinHandle polled after completion"),
            "second poll should panic with completion misuse message, got {second_message}"
        );
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should remain finished after post-completion misuse"
        );
    }

    #[test]
    fn join_handle_is_finished_after_executor_side_disappears() {
        init_test_logging();

        let state = Arc::new(Mutex::new(JoinState::<u8>::new()));
        let mut join = std::pin::pin!(JoinHandle::new(Arc::clone(&state)));
        drop(state);

        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should report terminal dropped-task state as finished"
        );

        let waker = noop_waker();
        let mut cx = Context::from_waker(&waker);
        let poll_after_drop = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = join.as_mut().poll(&mut cx);
        }));
        let message = panic_payload_to_string(
            poll_after_drop.expect_err("poll after executor-side disappearance must panic"),
        );
        assert!(
            message.contains("task was dropped or cancelled before completion"),
            "poll after executor-side disappearance should preserve dropped-task panic, got {message}"
        );
        assert!(
            join.as_ref().get_ref().is_finished(),
            "join handle should remain finished after the terminal dropped-task poll"
        );
    }
}