asupersync 0.3.0

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
#![allow(clippy::all)]
//! Comprehensive test logging infrastructure for Asupersync.
//!
//! This module provides detailed logging for tests that captures all I/O events,
//! reactor operations, waker dispatches, and timing information to enable thorough
//! debugging.
//!
//! # Overview
//!
//! The test logging infrastructure consists of:
//!
//! - [`TestLogLevel`]: Configurable verbosity levels
//! - [`TestEvent`]: Typed events for all runtime operations
//! - [`TestLogger`]: Captures and reports events with timestamps
//!
//! # Example
//!
//! ```ignore
//! use asupersync::test_logging::{TestLogger, TestLogLevel, TestEvent};
//!
//! let logger = TestLogger::new(TestLogLevel::Debug);
//! logger.log(TestEvent::TaskSpawn { task_id: 1, name: Some("worker".into()) });
//!
//! // On test completion, print the report
//! println!("{}", logger.report());
//! ```

use crate::lab::{DualRunScenarioIdentity, ReplayMetadata, SeedLineageRecord};
use parking_lot::Mutex;
use std::fmt::Write as _;
use std::time::{Duration, Instant};

// ============================================================================
// TestLogLevel
// ============================================================================

/// Logging verbosity level for tests.
///
/// Levels are ordered from least to most verbose:
/// `Error < Warn < Info < Debug < Trace`
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum TestLogLevel {
    /// Only errors and failures.
    Error,
    /// Warnings and above.
    Warn,
    /// General test progress.
    #[default]
    Info,
    /// Detailed I/O operations.
    Debug,
    /// All events including waker dispatch, polls, syscalls.
    Trace,
}

impl TestLogLevel {
    /// Returns a human-readable name for the level.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Error => "ERROR",
            Self::Warn => "WARN",
            Self::Info => "INFO",
            Self::Debug => "DEBUG",
            Self::Trace => "TRACE",
        }
    }

    /// Returns the level from the `TEST_LOG_LEVEL` environment variable.
    #[must_use]
    pub fn from_env() -> Self {
        std::env::var("TEST_LOG_LEVEL")
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or_default()
    }
}

impl std::fmt::Display for TestLogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl std::str::FromStr for TestLogLevel {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "error" => Ok(Self::Error),
            "warn" | "warning" => Ok(Self::Warn),
            "info" => Ok(Self::Info),
            "debug" => Ok(Self::Debug),
            "trace" => Ok(Self::Trace),
            _ => Err(()),
        }
    }
}

/// Stable adapter token for the Phase 1 live current-thread runner.
pub const LIVE_CURRENT_THREAD_ADAPTER: &str = "live.current_thread";

// ============================================================================
// Interest flags (for reactor events)
// ============================================================================

/// I/O interest flags for reactor registration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Interest {
    /// Interested in read readiness.
    pub readable: bool,
    /// Interested in write readiness.
    pub writable: bool,
}

impl Interest {
    /// Interest in readable events only.
    pub const READABLE: Self = Self {
        readable: true,
        writable: false,
    };

    /// Interest in writable events only.
    pub const WRITABLE: Self = Self {
        readable: false,
        writable: true,
    };

    /// Interest in both readable and writable events.
    pub const BOTH: Self = Self {
        readable: true,
        writable: true,
    };
}

impl std::fmt::Display for Interest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match (self.readable, self.writable) {
            (true, true) => write!(f, "RW"),
            (true, false) => write!(f, "R"),
            (false, true) => write!(f, "W"),
            (false, false) => write!(f, "-"),
        }
    }
}

// ============================================================================
// TestEvent
// ============================================================================

/// A typed event captured by the test logger.
///
/// Events cover all aspects of runtime operation:
/// - Reactor events (poll, wake, register, deregister)
/// - I/O events (read, write, connect, accept)
/// - Waker events (wake, clone, drop)
/// - Task events (poll, spawn, complete)
/// - Timer events (scheduled, fired)
/// - Custom events for test-specific logging
#[derive(Debug, Clone)]
pub enum TestEvent {
    // ========================================================================
    // Reactor events
    // ========================================================================
    /// Reactor poll completed.
    ReactorPoll {
        /// Timeout passed to poll.
        timeout: Option<Duration>,
        /// Number of events returned.
        events_returned: usize,
        /// How long the poll took.
        duration: Duration,
    },

    /// Reactor was woken externally.
    ReactorWake {
        /// Source of the wake (e.g., "waker", "timeout", "signal").
        source: &'static str,
    },

    /// I/O source registered with reactor.
    ReactorRegister {
        /// Token assigned to the registration.
        token: usize,
        /// Interest flags.
        interest: Interest,
        /// Type of source (e.g., "tcp", "unix", "pipe").
        source_type: &'static str,
    },

    /// I/O source deregistered from reactor.
    ReactorDeregister {
        /// Token that was deregistered.
        token: usize,
    },

    // ========================================================================
    // I/O events
    // ========================================================================
    /// Read operation completed.
    IoRead {
        /// Token of the I/O source.
        token: usize,
        /// Bytes read (0 if would_block).
        bytes: usize,
        /// Whether the operation would block.
        would_block: bool,
    },

    /// Write operation completed.
    IoWrite {
        /// Token of the I/O source.
        token: usize,
        /// Bytes written (0 if would_block).
        bytes: usize,
        /// Whether the operation would block.
        would_block: bool,
    },

    /// Connection attempt completed.
    IoConnect {
        /// Address being connected to.
        addr: String,
        /// Result description ("success", "refused", "timeout", etc.).
        result: &'static str,
    },

    /// Connection accepted.
    IoAccept {
        /// Local address.
        local: String,
        /// Peer address.
        peer: String,
    },

    // ========================================================================
    // Waker events
    // ========================================================================
    /// Waker was invoked.
    WakerWake {
        /// Token associated with the waker.
        token: usize,
        /// Task ID being woken.
        task_id: usize,
    },

    /// Waker was cloned.
    WakerClone {
        /// Token of the waker.
        token: usize,
    },

    /// Waker was dropped.
    WakerDrop {
        /// Token of the waker.
        token: usize,
    },

    // ========================================================================
    // Task events
    // ========================================================================
    /// Task was polled.
    TaskPoll {
        /// ID of the task.
        task_id: usize,
        /// Result of the poll ("ready", "pending").
        result: &'static str,
    },

    /// Task was spawned.
    TaskSpawn {
        /// ID of the new task.
        task_id: usize,
        /// Optional name for debugging.
        name: Option<String>,
    },

    /// Task completed.
    TaskComplete {
        /// ID of the completed task.
        task_id: usize,
        /// Outcome description ("ok", "err", "cancelled", "panicked").
        outcome: &'static str,
    },

    // ========================================================================
    // Timer events
    // ========================================================================
    /// Timer was scheduled.
    TimerScheduled {
        /// Deadline relative to start.
        deadline: Duration,
        /// Task to wake.
        task_id: usize,
    },

    /// Timer fired.
    TimerFired {
        /// Task that was woken.
        task_id: usize,
    },

    // ========================================================================
    // Region events
    // ========================================================================
    /// Region was created.
    RegionCreate {
        /// ID of the new region.
        region_id: usize,
        /// Parent region ID (if any).
        parent_id: Option<usize>,
    },

    /// Region state changed.
    RegionStateChange {
        /// ID of the region.
        region_id: usize,
        /// Previous state name.
        from_state: &'static str,
        /// New state name.
        to_state: &'static str,
    },

    /// Region closed.
    RegionClose {
        /// ID of the region.
        region_id: usize,
        /// Number of tasks that were in the region.
        task_count: usize,
        /// Duration the region was open.
        duration: Duration,
    },

    // ========================================================================
    // Obligation events
    // ========================================================================
    /// Obligation was created.
    ObligationCreate {
        /// ID of the obligation.
        obligation_id: usize,
        /// Kind of obligation ("permit", "ack", "lease", "io").
        kind: &'static str,
        /// Holding task.
        holder_id: usize,
    },

    /// Obligation was resolved.
    ObligationResolve {
        /// ID of the obligation.
        obligation_id: usize,
        /// Resolution type ("commit", "abort").
        resolution: &'static str,
    },

    // ========================================================================
    // Custom events
    // ========================================================================
    /// Custom event for test-specific logging.
    Custom {
        /// Category for filtering.
        category: &'static str,
        /// Human-readable message.
        message: String,
    },

    /// Error event.
    Error {
        /// Error category.
        category: &'static str,
        /// Error message.
        message: String,
    },

    /// Warning event.
    Warn {
        /// Warning category.
        category: &'static str,
        /// Warning message.
        message: String,
    },
}

impl TestEvent {
    /// Returns the minimum log level required to display this event.
    #[must_use]
    pub fn level(&self) -> TestLogLevel {
        match self {
            Self::Error { .. } => TestLogLevel::Error,
            Self::Warn { .. } => TestLogLevel::Warn,
            Self::TaskSpawn { .. }
            | Self::TaskComplete { .. }
            | Self::RegionCreate { .. }
            | Self::RegionClose { .. } => TestLogLevel::Info,
            Self::IoRead { .. }
            | Self::IoWrite { .. }
            | Self::IoConnect { .. }
            | Self::IoAccept { .. }
            | Self::ReactorRegister { .. }
            | Self::ReactorDeregister { .. }
            | Self::ObligationCreate { .. }
            | Self::ObligationResolve { .. }
            | Self::Custom { .. } => TestLogLevel::Debug,
            Self::ReactorPoll { .. }
            | Self::ReactorWake { .. }
            | Self::WakerWake { .. }
            | Self::WakerClone { .. }
            | Self::WakerDrop { .. }
            | Self::TaskPoll { .. }
            | Self::TimerScheduled { .. }
            | Self::TimerFired { .. }
            | Self::RegionStateChange { .. } => TestLogLevel::Trace,
        }
    }

    /// Returns a short category name for the event.
    #[must_use]
    pub fn category(&self) -> &'static str {
        match self {
            Self::ReactorPoll { .. }
            | Self::ReactorWake { .. }
            | Self::ReactorRegister { .. }
            | Self::ReactorDeregister { .. } => "reactor",
            Self::IoRead { .. }
            | Self::IoWrite { .. }
            | Self::IoConnect { .. }
            | Self::IoAccept { .. } => "io",
            Self::WakerWake { .. } | Self::WakerClone { .. } | Self::WakerDrop { .. } => "waker",
            Self::TaskPoll { .. } | Self::TaskSpawn { .. } | Self::TaskComplete { .. } => "task",
            Self::TimerScheduled { .. } | Self::TimerFired { .. } => "timer",
            Self::RegionCreate { .. }
            | Self::RegionStateChange { .. }
            | Self::RegionClose { .. } => "region",
            Self::ObligationCreate { .. } | Self::ObligationResolve { .. } => "obligation",
            Self::Custom { category, .. }
            | Self::Error { category, .. }
            | Self::Warn { category, .. } => category,
        }
    }
}

#[allow(clippy::too_many_lines)]
impl std::fmt::Display for TestEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ReactorPoll {
                timeout,
                events_returned,
                duration,
            } => {
                write!(
                    f,
                    "reactor poll: timeout={timeout:?} events={events_returned} duration={duration:?}",
                )
            }
            Self::ReactorWake { source } => write!(f, "reactor wake: source={source}"),
            Self::ReactorRegister {
                token,
                interest,
                source_type,
            } => {
                write!(
                    f,
                    "reactor register: token={token} interest={interest} type={source_type}"
                )
            }
            Self::ReactorDeregister { token } => write!(f, "reactor deregister: token={token}"),
            Self::IoRead {
                token,
                bytes,
                would_block,
            } => {
                if *would_block {
                    write!(f, "io read: token={token} WOULD_BLOCK")
                } else {
                    write!(f, "io read: token={token} bytes={bytes}")
                }
            }
            Self::IoWrite {
                token,
                bytes,
                would_block,
            } => {
                if *would_block {
                    write!(f, "io write: token={token} WOULD_BLOCK")
                } else {
                    write!(f, "io write: token={token} bytes={bytes}")
                }
            }
            Self::IoConnect { addr, result } => {
                write!(f, "io connect: addr={addr} result={result}")
            }
            Self::IoAccept { local, peer } => write!(f, "io accept: local={local} peer={peer}"),
            Self::WakerWake { token, task_id } => {
                write!(f, "waker wake: token={token} task={task_id}")
            }
            Self::WakerClone { token } => write!(f, "waker clone: token={token}"),
            Self::WakerDrop { token } => write!(f, "waker drop: token={token}"),
            Self::TaskPoll { task_id, result } => write!(f, "task poll: task={task_id} {result}"),
            Self::TaskSpawn { task_id, name } => {
                if let Some(n) = name {
                    write!(f, "task spawn: task={task_id} name=\"{n}\"")
                } else {
                    write!(f, "task spawn: task={task_id}")
                }
            }
            Self::TaskComplete { task_id, outcome } => {
                write!(f, "task complete: task={task_id} outcome={outcome}")
            }
            Self::TimerScheduled { deadline, task_id } => {
                write!(f, "timer scheduled: deadline={deadline:?} task={task_id}")
            }
            Self::TimerFired { task_id } => write!(f, "timer fired: task={task_id}"),
            Self::RegionCreate {
                region_id,
                parent_id,
            } => {
                if let Some(p) = parent_id {
                    write!(f, "region create: region={region_id} parent={p}")
                } else {
                    write!(f, "region create: region={region_id} (root)")
                }
            }
            Self::RegionStateChange {
                region_id,
                from_state,
                to_state,
            } => {
                write!(
                    f,
                    "region state: region={region_id} {from_state} -> {to_state}"
                )
            }
            Self::RegionClose {
                region_id,
                task_count,
                duration,
            } => {
                write!(
                    f,
                    "region close: region={region_id} tasks={task_count} duration={duration:?}"
                )
            }
            Self::ObligationCreate {
                obligation_id,
                kind,
                holder_id,
            } => {
                write!(
                    f,
                    "obligation create: id={obligation_id} kind={kind} holder={holder_id}"
                )
            }
            Self::ObligationResolve {
                obligation_id,
                resolution,
            } => {
                write!(
                    f,
                    "obligation resolve: id={obligation_id} resolution={resolution}"
                )
            }
            Self::Custom { category, message } => write!(f, "[{category}] {message}"),
            Self::Error { category, message } => write!(f, "ERROR [{category}] {message}"),
            Self::Warn { category, message } => write!(f, "WARN [{category}] {message}"),
        }
    }
}

// ============================================================================
// TestLogger
// ============================================================================

/// A timestamped event record.
#[derive(Debug, Clone)]
pub struct LogRecord {
    /// Time since logger creation.
    pub elapsed: Duration,
    /// The event that occurred.
    pub event: TestEvent,
}

/// Comprehensive test logger that captures typed events with timestamps.
///
/// # Example
///
/// ```ignore
/// let logger = TestLogger::new(TestLogLevel::Debug);
///
/// // Log events during test
/// logger.log(TestEvent::TaskSpawn { task_id: 1, name: None });
/// logger.log(TestEvent::TaskComplete { task_id: 1, outcome: "ok" });
///
/// // Generate report
/// println!("{}", logger.report());
///
/// // Assert no busy loops
/// logger.assert_no_busy_loop(5);
/// ```
#[derive(Debug)]
pub struct TestLogger {
    /// Minimum level to capture.
    level: TestLogLevel,
    /// Captured events.
    events: Mutex<Vec<LogRecord>>,
    /// Start time for elapsed calculation.
    start_time: Instant,
    /// Whether to print events immediately.
    verbose: bool,
}

impl TestLogger {
    /// Creates a new logger with the specified level.
    #[must_use]
    pub fn new(level: TestLogLevel) -> Self {
        Self {
            level,
            events: Mutex::new(Vec::new()),
            start_time: Instant::now(),
            verbose: false,
        }
    }

    /// Creates a logger using the `TEST_LOG_LEVEL` environment variable.
    #[must_use]
    pub fn from_env() -> Self {
        Self::new(TestLogLevel::from_env())
    }

    /// Sets whether to print events immediately.
    #[must_use]
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Returns the configured log level.
    #[must_use]
    pub fn level(&self) -> TestLogLevel {
        self.level
    }

    /// Returns the elapsed time since logger creation.
    #[must_use]
    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Returns whether the logger should capture events at the given level.
    #[must_use]
    pub fn should_log(&self, level: TestLogLevel) -> bool {
        level <= self.level
    }

    /// Logs an event if it meets the configured level.
    pub fn log(&self, event: TestEvent) {
        let event_level = event.level();
        if !self.should_log(event_level) {
            return;
        }

        let elapsed = self.start_time.elapsed();

        // Print immediately if verbose
        if self.verbose {
            eprintln!(
                "[{:>10.3}ms] [{:>5}] {}",
                elapsed.as_secs_f64() * 1000.0,
                event_level.name(),
                &event
            );
        }

        let record = LogRecord { elapsed, event };
        self.events.lock().push(record);
    }

    /// Logs a custom event.
    pub fn custom(&self, category: &'static str, message: impl Into<String>) {
        self.log(TestEvent::Custom {
            category,
            message: message.into(),
        });
    }

    /// Logs an error event.
    pub fn error(&self, category: &'static str, message: impl Into<String>) {
        self.log(TestEvent::Error {
            category,
            message: message.into(),
        });
    }

    /// Logs a warning event.
    pub fn warn(&self, category: &'static str, message: impl Into<String>) {
        self.log(TestEvent::Warn {
            category,
            message: message.into(),
        });
    }

    /// Returns the number of captured events.
    #[must_use]
    pub fn event_count(&self) -> usize {
        self.events.lock().len()
    }

    /// Returns a snapshot of all captured events.
    #[must_use]
    pub fn events(&self) -> Vec<LogRecord> {
        self.events.lock().clone()
    }

    /// Generates a detailed report of all captured events.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    #[allow(clippy::significant_drop_tightening)]
    pub fn report(&self) -> String {
        let events = self.events.lock();
        let mut report = String::new();

        let _ = writeln!(report, "=== Test Event Log ({} events) ===", events.len());
        let _ = writeln!(report);

        for record in events.iter() {
            let _ = writeln!(
                report,
                "[{:>10.3}ms] [{:>5}] {:>10} | {}",
                record.elapsed.as_secs_f64() * 1000.0,
                record.event.level().name(),
                record.event.category(),
                record.event
            );
        }

        // Statistics
        let _ = writeln!(report);
        let _ = writeln!(report, "=== Statistics ===");

        let polls = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::ReactorPoll { .. }))
            .count();
        let reads = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::IoRead { .. }))
            .count();
        let writes = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::IoWrite { .. }))
            .count();
        let wakes = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::WakerWake { .. }))
            .count();
        let task_polls = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::TaskPoll { .. }))
            .count();
        let task_spawns = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::TaskSpawn { .. }))
            .count();
        let errors = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::Error { .. }))
            .count();
        let warnings = events
            .iter()
            .filter(|r| matches!(r.event, TestEvent::Warn { .. }))
            .count();

        let _ = writeln!(report, "Reactor polls: {polls}");
        let _ = writeln!(report, "I/O reads: {reads}");
        let _ = writeln!(report, "I/O writes: {writes}");
        let _ = writeln!(report, "Waker wakes: {wakes}");
        let _ = writeln!(report, "Task polls: {task_polls}");
        let _ = writeln!(report, "Task spawns: {task_spawns}");
        let _ = writeln!(report, "Errors: {errors}");
        let _ = writeln!(report, "Warnings: {warnings}");

        // Calculate empty polls
        let empty_polls = events
            .iter()
            .filter(|r| {
                matches!(
                    r.event,
                    TestEvent::ReactorPoll {
                        events_returned: 0,
                        ..
                    }
                )
            })
            .count();

        if polls > 0 {
            let _ = writeln!(
                report,
                "Empty polls: {empty_polls} ({:.1}%)",
                (empty_polls as f64 / polls as f64) * 100.0
            );
        }

        // Total duration
        if let Some(last) = events.last() {
            let _ = writeln!(report, "Total duration: {:?}", last.elapsed);
        }

        report
    }

    /// Asserts that the test did not have excessive empty reactor polls (busy loops).
    ///
    /// # Panics
    ///
    /// Panics if the number of empty polls exceeds `max_empty_polls`.
    pub fn assert_no_busy_loop(&self, max_empty_polls: usize) {
        let empty_polls = {
            let events = self.events.lock();
            events
                .iter()
                .filter(|r| {
                    matches!(
                        r.event,
                        TestEvent::ReactorPoll {
                            events_returned: 0,
                            ..
                        }
                    )
                })
                .count()
        };

        assert!(
            empty_polls <= max_empty_polls,
            "Busy loop detected: {} empty polls (max {})\n{}",
            empty_polls,
            max_empty_polls,
            self.report()
        );
    }

    /// Asserts that no errors were logged.
    ///
    /// # Panics
    ///
    /// Panics if any error events were logged.
    pub fn assert_no_errors(&self) {
        let error_messages: Vec<String> = {
            let events = self.events.lock();
            events
                .iter()
                .filter(|r| matches!(r.event, TestEvent::Error { .. }))
                .map(|r| format!("  - {}", r.event))
                .collect()
        };

        assert!(
            error_messages.is_empty(),
            "Test logged {} errors:\n{}\n\nFull log:\n{}",
            error_messages.len(),
            error_messages.join("\n"),
            self.report()
        );
    }

    /// Asserts that all spawned tasks completed.
    ///
    /// # Panics
    ///
    /// Panics if any spawned task did not have a corresponding completion event.
    pub fn assert_all_tasks_completed(&self) {
        let leaked: Vec<usize> = {
            let events = self.events.lock();

            let spawned: std::collections::HashSet<_> = events
                .iter()
                .filter_map(|r| {
                    if let TestEvent::TaskSpawn { task_id, .. } = r.event {
                        Some(task_id)
                    } else {
                        None
                    }
                })
                .collect();

            let completed: std::collections::HashSet<_> = events
                .iter()
                .filter_map(|r| {
                    if let TestEvent::TaskComplete { task_id, .. } = r.event {
                        Some(task_id)
                    } else {
                        None
                    }
                })
                .collect();

            drop(events);
            spawned.difference(&completed).copied().collect()
        };

        assert!(
            leaked.is_empty(),
            "Task leak detected: {} tasks spawned but not completed: {:?}\n\nFull log:\n{}",
            leaked.len(),
            leaked,
            self.report()
        );
    }

    /// Clears all captured events.
    pub fn clear(&self) {
        self.events.lock().clear();
    }
}

impl Default for TestLogger {
    fn default() -> Self {
        Self::new(TestLogLevel::Info)
    }
}

// ============================================================================
// Macros
// ============================================================================

/// Log a custom event to a test logger.
///
/// # Example
///
/// ```ignore
/// test_log!(logger, "setup", "Creating listener on port {}", port);
/// test_log!(logger, "test", "Sending {} bytes", data.len());
/// ```
#[macro_export]
macro_rules! test_log {
    ($logger:expr, $cat:literal, $($arg:tt)*) => {
        $logger.log($crate::test_logging::TestEvent::Custom {
            category: $cat,
            message: format!($($arg)*),
        });
    };
}

/// Log an error event to a test logger.
///
/// # Example
///
/// ```ignore
/// test_error!(logger, "io", "Connection refused: {}", err);
/// ```
#[macro_export]
macro_rules! test_error {
    ($logger:expr, $cat:literal, $($arg:tt)*) => {
        $logger.log($crate::test_logging::TestEvent::Error {
            category: $cat,
            message: format!($($arg)*),
        });
    };
}

/// Log a warning event to a test logger.
///
/// # Example
///
/// ```ignore
/// test_warn!(logger, "timeout", "Operation took {}ms", elapsed);
/// ```
#[macro_export]
macro_rules! test_warn {
    ($logger:expr, $cat:literal, $($arg:tt)*) => {
        $logger.log($crate::test_logging::TestEvent::Warn {
            category: $cat,
            message: format!($($arg)*),
        });
    };
}

/// Assert a condition, printing the full log on failure.
///
/// # Example
///
/// ```ignore
/// assert_log!(logger, result.is_ok(), "Expected success, got {:?}", result);
/// ```
#[macro_export]
macro_rules! assert_log {
    ($logger:expr, $cond:expr) => {
        if !$cond {
            tracing::error!(report = %$logger.report(), "assertion failed: {}", stringify!($cond));
            panic!("assertion failed: {}", stringify!($cond));
        }
    };
    ($logger:expr, $cond:expr, $($arg:tt)*) => {
        if !$cond {
            tracing::error!(report = %$logger.report(), "assertion failed: {}", format_args!($($arg)*));
            panic!($($arg)*);
        }
    };
}

/// Assert equality, printing the full log on failure.
///
/// # Example
///
/// ```ignore
/// assert_eq_log!(logger, actual, expected, "Values should match");
/// ```
#[macro_export]
macro_rules! assert_eq_log {
    ($logger:expr, $left:expr, $right:expr) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                if *left_val != *right_val {
                    tracing::error!(report = %$logger.report(), "assertion failed: left == right");
                    panic!(
                        "assertion failed: `(left == right)`\n  left: {:?}\n right: {:?}",
                        left_val, right_val
                    );
                }
            }
        }
    };
    ($logger:expr, $left:expr, $right:expr, $($arg:tt)*) => {
        match (&$left, &$right) {
            (left_val, right_val) => {
                if *left_val != *right_val {
                    tracing::error!(
                        report = %$logger.report(),
                        "assertion failed: {}",
                        format_args!($($arg)*)
                    );
                    panic!(
                        "assertion failed: `(left == right)`\n  left: {:?}\n right: {:?}\n{}",
                        left_val, right_val, format!($($arg)*)
                    );
                }
            }
        }
    };
}

// ============================================================================
// TestHarness — Hierarchical E2E Test Framework
// ============================================================================

/// Result of a single assertion within a test.
#[derive(Debug, Clone, serde::Serialize)]
pub struct AssertionRecord {
    /// Description of what was asserted.
    pub description: String,
    /// Whether the assertion passed.
    pub passed: bool,
    /// Expected value (stringified).
    pub expected: String,
    /// Actual value (stringified).
    pub actual: String,
    /// Phase path at time of assertion (e.g. "setup > connect").
    pub phase_path: String,
    /// Elapsed time since harness creation.
    pub elapsed_ms: f64,
}

/// A hierarchical phase node in the test execution tree.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PhaseNode {
    /// Name of this phase/section/step.
    pub name: String,
    /// Depth level (0 = top-level phase, 1 = section, 2 = step, ...).
    pub depth: usize,
    /// Start time relative to harness creation.
    pub start_ms: f64,
    /// End time relative to harness creation (None if still open).
    pub end_ms: Option<f64>,
    /// Assertions recorded within this phase.
    pub assertions: Vec<AssertionRecord>,
    /// Child phases.
    pub children: Vec<Self>,
}

// ============================================================================
// TestContext — Standardized metadata for structured test logging
// ============================================================================

/// Standardized metadata carried through a test for structured logging.
///
/// Every test should create a `TestContext` to ensure consistent, machine-parseable
/// log fields across all unit, integration, and E2E tests.
///
/// # Standard Fields
///
/// | Field | Purpose | Example |
/// |-------|---------|---------|
/// | `test_id` | Unique identifier for the test run | `"cancel_drain_001"` |
/// | `seed` | Deterministic RNG seed for reproducibility | `0xDEAD_BEEF` |
/// | `subsystem` | Runtime subsystem under test | `"scheduler"`, `"raptorq"` |
/// | `invariant` | Core invariant being verified | `"no_obligation_leaks"` |
///
/// # Example
///
/// ```ignore
/// use asupersync::test_logging::TestContext;
///
/// let ctx = TestContext::new("cancel_drain_001", 0xDEAD_BEEF)
///     .with_subsystem("cancellation")
///     .with_invariant("losers_drained");
///
/// // Use with TestHarness
/// let harness = TestHarness::with_context("my_test", ctx);
/// ```
#[derive(Debug, Clone, serde::Serialize)]
pub struct TestContext {
    /// Unique test identifier for log correlation.
    pub test_id: String,
    /// Deterministic seed for reproducibility.
    pub seed: u64,
    /// Runtime subsystem under test (e.g., "scheduler", "raptorq", "obligation").
    pub subsystem: Option<String>,
    /// Core invariant being verified (e.g., "no_obligation_leaks", "quiescence").
    pub invariant: Option<String>,
    /// Adapter identity for dual-run provenance.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter: Option<String>,
    /// Rich replay/provenance metadata for the execution, when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replay_metadata: Option<ReplayMetadata>,
    /// Stable seed lineage record for audit/mismatch artifacts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed_lineage: Option<SeedLineageRecord>,
}

impl TestContext {
    /// Create a new context with required fields.
    #[must_use]
    pub fn new(test_id: &str, seed: u64) -> Self {
        Self {
            test_id: test_id.to_string(),
            seed,
            subsystem: None,
            invariant: None,
            adapter: None,
            replay_metadata: None,
            seed_lineage: None,
        }
    }

    /// Set the subsystem under test.
    #[must_use]
    pub fn with_subsystem(mut self, subsystem: &str) -> Self {
        self.subsystem = Some(subsystem.to_string());
        self
    }

    /// Set the invariant being verified.
    #[must_use]
    pub fn with_invariant(mut self, invariant: &str) -> Self {
        self.invariant = Some(invariant.to_string());
        self
    }

    /// Attach replay provenance captured from a dual-run execution surface.
    #[must_use]
    pub fn with_replay_provenance(
        mut self,
        adapter: impl Into<String>,
        replay_metadata: ReplayMetadata,
        seed_lineage: SeedLineageRecord,
    ) -> Self {
        self.test_id.clone_from(&replay_metadata.family.id);
        self.seed = replay_metadata.effective_seed;
        self.adapter = Some(adapter.into());
        self.replay_metadata = Some(replay_metadata);
        self.seed_lineage = Some(seed_lineage);
        self
    }

    /// Build a current-thread live test context from a dual-run identity.
    #[must_use]
    pub fn from_live_dual_run(identity: &DualRunScenarioIdentity) -> Self {
        Self::new(
            &identity.scenario_id,
            identity.seed_plan.effective_live_seed(),
        )
        .with_replay_provenance(
            LIVE_CURRENT_THREAD_ADAPTER,
            identity.live_replay_metadata(),
            identity.seed_lineage(),
        )
    }

    /// Surface identifier, when dual-run provenance is attached.
    #[must_use]
    pub fn surface_id(&self) -> Option<&str> {
        self.replay_metadata
            .as_ref()
            .map(|metadata| metadata.family.surface_id.as_str())
    }

    /// Surface contract version, when dual-run provenance is attached.
    #[must_use]
    pub fn surface_contract_version(&self) -> Option<&str> {
        self.replay_metadata
            .as_ref()
            .map(|metadata| metadata.family.surface_contract_version.as_str())
    }

    /// Stable seed lineage identifier, when dual-run provenance is attached.
    #[must_use]
    pub fn seed_lineage_id(&self) -> Option<&str> {
        self.seed_lineage
            .as_ref()
            .map(|lineage| lineage.seed_lineage_id.as_str())
    }

    /// Concrete execution-instance identifier, when dual-run provenance is attached.
    #[must_use]
    pub fn execution_instance_id(&self) -> Option<String> {
        self.replay_metadata
            .as_ref()
            .map(|metadata| metadata.instance.key())
    }

    /// Emit a tracing info event with all context fields.
    pub fn log_start(&self) {
        tracing::info!(
            test_id = %self.test_id,
            seed = %format_args!("0x{:X}", self.seed),
            subsystem = self.subsystem.as_deref().unwrap_or("-"),
            invariant = self.invariant.as_deref().unwrap_or("-"),
            surface_id = self.surface_id().unwrap_or("-"),
            surface_contract_version = self.surface_contract_version().unwrap_or("-"),
            adapter = self.adapter.as_deref().unwrap_or("-"),
            seed_lineage_id = self.seed_lineage_id().unwrap_or("-"),
            execution_instance_id = self.execution_instance_id().as_deref().unwrap_or("-"),
            "TEST START"
        );
    }

    /// Emit a tracing info event for test completion with all context fields.
    pub fn log_end(&self, passed: bool) {
        tracing::info!(
            test_id = %self.test_id,
            seed = %format_args!("0x{:X}", self.seed),
            subsystem = self.subsystem.as_deref().unwrap_or("-"),
            invariant = self.invariant.as_deref().unwrap_or("-"),
            surface_id = self.surface_id().unwrap_or("-"),
            surface_contract_version = self.surface_contract_version().unwrap_or("-"),
            adapter = self.adapter.as_deref().unwrap_or("-"),
            seed_lineage_id = self.seed_lineage_id().unwrap_or("-"),
            execution_instance_id = self.execution_instance_id().as_deref().unwrap_or("-"),
            passed = passed,
            "TEST END"
        );
    }

    /// Derive a component-specific seed from this context's root seed.
    #[must_use]
    pub fn component_seed(&self, component: &str) -> u64 {
        derive_component_seed(self.seed, component)
    }

    /// Derive a scenario-specific seed from this context's root seed.
    #[must_use]
    pub fn scenario_seed(&self, scenario: &str) -> u64 {
        derive_scenario_seed(self.seed, scenario)
    }

    /// Derive an entropy seed for a given iteration index.
    #[must_use]
    pub fn entropy_seed(&self, index: u64) -> u64 {
        derive_entropy_seed(self.seed, index)
    }

    /// Emit a structured error dump with full context for failure triage.
    pub fn log_failure(&self, reason: &str) {
        tracing::error!(
            test_id = %self.test_id,
            seed = %format_args!("0x{:X}", self.seed),
            subsystem = self.subsystem.as_deref().unwrap_or("-"),
            invariant = self.invariant.as_deref().unwrap_or("-"),
            surface_id = self.surface_id().unwrap_or("-"),
            surface_contract_version = self.surface_contract_version().unwrap_or("-"),
            adapter = self.adapter.as_deref().unwrap_or("-"),
            seed_lineage_id = self.seed_lineage_id().unwrap_or("-"),
            execution_instance_id = self.execution_instance_id().as_deref().unwrap_or("-"),
            reason = %reason,
            "TEST FAILURE — reproduce with seed 0x{:X}",
            self.seed
        );
    }
}

impl std::fmt::Display for TestContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "test_id={} seed=0x{:X} subsystem={} invariant={} surface={} contract={} adapter={}",
            self.test_id,
            self.seed,
            self.subsystem.as_deref().unwrap_or("-"),
            self.invariant.as_deref().unwrap_or("-"),
            self.surface_id().unwrap_or("-"),
            self.surface_contract_version().unwrap_or("-"),
            self.adapter.as_deref().unwrap_or("-"),
        )
    }
}

// ============================================================================
// Seed Derivation — Canonical taxonomy and propagation rules
// ============================================================================
//
// Seed taxonomy (all seeds derive from a single root):
//
//   root_seed                         — top-level test seed (from env, CLI, or hardcoded)
//     ├── scenario_seed(root, name)   — per-scenario derivation (deterministic)
//     ├── component_seed(root, comp)  — per-subsystem (scheduler, io, rng, etc.)
//     └── entropy_seed(root, idx)     — per-iteration for property/fuzz tests
//
// Derivation formula:
//   derived = FNV-1a(root ⊕ tag_bytes)
//
// This avoids DefaultHasher (which is randomized per-process on some targets)
// and ensures cross-platform determinism.

/// Derive a deterministic seed for a named component from a root seed.
///
/// Uses FNV-1a hashing for cross-platform determinism.
#[must_use]
pub fn derive_component_seed(root: u64, component: &str) -> u64 {
    fnv1a_mix(root, component.as_bytes())
}

/// Derive a deterministic seed for a named scenario from a root seed.
#[must_use]
pub fn derive_scenario_seed(root: u64, scenario: &str) -> u64 {
    let tag = format!("scenario:{scenario}");
    fnv1a_mix(root, tag.as_bytes())
}

/// Derive a deterministic entropy seed for a given iteration index.
#[must_use]
pub fn derive_entropy_seed(root: u64, index: u64) -> u64 {
    fnv1a_mix(root, &index.to_le_bytes())
}

/// FNV-1a-based deterministic mixing function.
fn fnv1a_mix(root: u64, tag: &[u8]) -> u64 {
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0100_0000_01b3;

    let mut hash = FNV_OFFSET;
    for byte in root.to_le_bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    for &byte in tag {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash
}

// ============================================================================
// Artifact Schema — Versioned, deterministic test artifacts
// ============================================================================

/// Current artifact schema version.
pub const ARTIFACT_SCHEMA_VERSION: u32 = 1;
/// Stable identifier for the canonical repro-manifest schema.
pub const REPRO_MANIFEST_SCHEMA_ID: &str = "repro-manifest.v1";
/// Required contract fields for deterministic CI/C5 consumption.
pub const REPRO_MANIFEST_REQUIRED_FIELDS: [&str; 7] = [
    "scenario_id",
    "invariant_ids",
    "seed",
    "trace_fingerprint",
    "replay_command",
    "failure_class",
    "artifact_paths",
];

const FAILURE_CLASS_PASSED: &str = "passed";
const FAILURE_CLASS_ASSERTION_FAILURE: &str = "assertion_failure";

fn default_trace_fingerprint(seed: u64, scenario_id: &str) -> String {
    format!("pending:{scenario_id}:{seed:016x}")
}

fn default_replay_command(seed: u64, scenario_id: &str) -> String {
    format!("ASUPERSYNC_SEED=0x{seed:X} rch exec -- cargo test {scenario_id} -- --nocapture")
}

fn normalize_string_ids(ids: impl IntoIterator<Item = String>) -> Vec<String> {
    let mut normalized = ids
        .into_iter()
        .map(|id| id.trim().to_string())
        .filter(|id| !id.is_empty())
        .collect::<Vec<_>>();
    normalized.sort_unstable();
    normalized.dedup();
    normalized
}

/// A reproducibility manifest for a test failure or notable execution.
///
/// # Artifact Layouts
///
/// - **Harness failures**: `$ASUPERSYNC_TEST_ARTIFACTS_DIR/<scenario_id>/repro_manifest.json`
///   alongside `event_log.txt` and `failed_assertions.json`.
/// - **Explicit dumps**: `<base>/<scenario_id>/<seed>/manifest.json` via
///   [`ReproManifest::write_to_dir`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ReproManifest {
    /// Schema version for forward compatibility.
    pub schema_version: u32,
    /// Root seed used for the test execution.
    pub seed: u64,
    /// Scenario identifier (test name or scenario tag).
    pub scenario_id: String,
    /// Canonical invariant identifiers validated by this execution.
    #[serde(default)]
    pub invariant_ids: Vec<String>,
    /// Entropy seed derived from root.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entropy_seed: Option<u64>,
    /// Hash of the test configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config_hash: Option<String>,
    /// Fingerprint of the execution trace.
    pub trace_fingerprint: String,
    /// Deterministic replay command for direct repro.
    pub replay_command: String,
    /// Failure class for routing/triage.
    pub failure_class: String,
    /// Artifact paths produced by this run.
    #[serde(default)]
    pub artifact_paths: Vec<String>,
    /// Digest of the test input data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_digest: Option<String>,
    /// Oracle violations detected during the execution.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub oracle_violations: Vec<String>,
    /// Whether the execution passed or failed.
    pub passed: bool,
    /// Subsystem under test.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subsystem: Option<String>,
    /// Invariant being verified.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invariant: Option<String>,
    /// Relative path to the trace file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_file: Option<String>,
    /// Relative path to the failing input file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_file: Option<String>,
    /// Captured environment variables relevant for reproducibility.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub env_snapshot: Vec<(String, String)>,
    /// Phases/steps executed before the failure.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub phases_executed: Vec<String>,
    /// Failure reason or assertion message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failure_reason: Option<String>,
    /// Adapter identity for the execution surface.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter: Option<String>,
    /// Rich replay/provenance metadata for the execution surface.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub replay_metadata: Option<ReplayMetadata>,
    /// Stable seed lineage record for reruns and mismatch bundles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed_lineage: Option<SeedLineageRecord>,
}

impl ReproManifest {
    /// Create a new manifest with required fields.
    #[must_use]
    pub fn new(seed: u64, scenario_id: &str, passed: bool) -> Self {
        Self {
            schema_version: ARTIFACT_SCHEMA_VERSION,
            seed,
            scenario_id: scenario_id.to_string(),
            invariant_ids: Vec::new(),
            entropy_seed: None,
            config_hash: None,
            trace_fingerprint: default_trace_fingerprint(seed, scenario_id),
            replay_command: default_replay_command(seed, scenario_id),
            failure_class: if passed {
                FAILURE_CLASS_PASSED.to_string()
            } else {
                FAILURE_CLASS_ASSERTION_FAILURE.to_string()
            },
            artifact_paths: Vec::new(),
            input_digest: None,
            oracle_violations: Vec::new(),
            passed,
            subsystem: None,
            invariant: None,
            trace_file: None,
            input_file: None,
            env_snapshot: Vec::new(),
            phases_executed: Vec::new(),
            failure_reason: None,
            adapter: None,
            replay_metadata: None,
            seed_lineage: None,
        }
    }

    /// Create a manifest from a [`TestContext`] and pass/fail status.
    #[must_use]
    pub fn from_context(ctx: &TestContext, passed: bool) -> Self {
        let replay_command = ctx
            .replay_metadata
            .as_ref()
            .and_then(|metadata| metadata.repro_command.clone())
            .unwrap_or_else(|| default_replay_command(ctx.seed, &ctx.test_id));
        Self {
            schema_version: ARTIFACT_SCHEMA_VERSION,
            seed: ctx.seed,
            scenario_id: ctx.test_id.clone(),
            invariant_ids: ctx
                .invariant
                .as_ref()
                .map_or_else(Vec::new, |invariant| vec![invariant.clone()]),
            entropy_seed: None,
            config_hash: None,
            trace_fingerprint: default_trace_fingerprint(ctx.seed, &ctx.test_id),
            replay_command,
            failure_class: if passed {
                FAILURE_CLASS_PASSED.to_string()
            } else {
                FAILURE_CLASS_ASSERTION_FAILURE.to_string()
            },
            artifact_paths: Vec::new(),
            input_digest: None,
            oracle_violations: Vec::new(),
            passed,
            subsystem: ctx.subsystem.clone(),
            invariant: ctx.invariant.clone(),
            trace_file: None,
            input_file: None,
            env_snapshot: Vec::new(),
            phases_executed: Vec::new(),
            failure_reason: None,
            adapter: ctx.adapter.clone(),
            replay_metadata: ctx.replay_metadata.clone(),
            seed_lineage: ctx.seed_lineage.clone(),
        }
    }

    /// Capture a snapshot of test-relevant environment variables.
    #[must_use]
    pub fn with_env_snapshot(mut self) -> Self {
        self.env_snapshot = capture_test_env();
        self
    }

    /// Set the phases executed during the test.
    #[must_use]
    pub fn with_phases(mut self, phases: Vec<String>) -> Self {
        self.phases_executed = phases;
        self
    }

    /// Set the failure reason.
    #[must_use]
    pub fn with_failure_reason(mut self, reason: &str) -> Self {
        self.failure_reason = Some(reason.to_string());
        if self.failure_class == FAILURE_CLASS_PASSED {
            self.failure_class = FAILURE_CLASS_ASSERTION_FAILURE.to_string();
        }
        self
    }

    /// Set the entropy seed derived from the root seed.
    #[must_use]
    pub fn with_entropy_seed(mut self, entropy_seed: u64) -> Self {
        self.entropy_seed = Some(entropy_seed);
        if let Some(ref mut replay_metadata) = self.replay_metadata {
            replay_metadata.effective_entropy_seed = entropy_seed;
        }
        self
    }

    /// Set the configuration hash used for this run.
    #[must_use]
    pub fn with_config_hash(mut self, config_hash: &str) -> Self {
        self.config_hash = Some(config_hash.to_string());
        if let Some(ref mut replay_metadata) = self.replay_metadata {
            replay_metadata.config_hash = Some(config_hash.to_string());
        }
        self
    }

    /// Set the trace fingerprint for this run.
    #[must_use]
    pub fn with_trace_fingerprint(mut self, trace_fingerprint: &str) -> Self {
        self.trace_fingerprint = trace_fingerprint.to_string();
        self
    }

    /// Set the deterministic replay command.
    #[must_use]
    pub fn with_replay_command(mut self, replay_command: &str) -> Self {
        self.replay_command = replay_command.to_string();
        if let Some(ref mut replay_metadata) = self.replay_metadata {
            replay_metadata.repro_command = Some(replay_command.to_string());
        }
        self
    }

    /// Set the failure class.
    #[must_use]
    pub fn with_failure_class(mut self, failure_class: &str) -> Self {
        self.failure_class = failure_class.to_string();
        self
    }

    /// Set the input digest for this run.
    #[must_use]
    pub fn with_input_digest(mut self, input_digest: &str) -> Self {
        self.input_digest = Some(input_digest.to_string());
        self
    }

    /// Set oracle violations recorded during this run.
    #[must_use]
    pub fn with_oracle_violations<I, S>(mut self, violations: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.oracle_violations = violations.into_iter().map(Into::into).collect();
        self
    }

    /// Set the subsystem under test.
    #[must_use]
    pub fn with_subsystem(mut self, subsystem: &str) -> Self {
        self.subsystem = Some(subsystem.to_string());
        self
    }

    /// Set the invariant under test.
    #[must_use]
    pub fn with_invariant(mut self, invariant: &str) -> Self {
        self.invariant = Some(invariant.to_string());
        self.invariant_ids = normalize_string_ids(vec![invariant.to_string()]);
        self
    }

    /// Set canonical invariant IDs; values are normalized (trimmed/sorted/deduped).
    #[must_use]
    pub fn with_invariant_ids<I, S>(mut self, invariant_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.invariant_ids = normalize_string_ids(invariant_ids.into_iter().map(Into::into));
        self
    }

    /// Set the relative path to the trace file.
    #[must_use]
    pub fn with_trace_file(mut self, trace_file: &str) -> Self {
        self.trace_file = Some(trace_file.to_string());
        self
    }

    /// Set the relative path to the input file.
    #[must_use]
    pub fn with_input_file(mut self, input_file: &str) -> Self {
        self.input_file = Some(input_file.to_string());
        self
    }

    /// Set artifact paths; values are normalized (trimmed/sorted/deduped).
    #[must_use]
    pub fn with_artifact_paths<I, S>(mut self, artifact_paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.artifact_paths = normalize_string_ids(artifact_paths.into_iter().map(Into::into));
        self
    }

    /// Add a single artifact path.
    #[must_use]
    pub fn with_artifact_path(mut self, artifact_path: &str) -> Self {
        self.artifact_paths.push(artifact_path.to_string());
        self.artifact_paths = normalize_string_ids(self.artifact_paths);
        self
    }

    /// Validate the canonical v1 contract used by CI and C5 gates.
    pub fn validate_contract_v1(&self) -> Result<(), String> {
        if self.schema_version != ARTIFACT_SCHEMA_VERSION {
            return Err(format!(
                "schema_version must be {}, got {}",
                ARTIFACT_SCHEMA_VERSION, self.schema_version
            ));
        }
        if self.scenario_id.trim().is_empty() {
            return Err("scenario_id must be non-empty".to_string());
        }
        if self.replay_command.trim().is_empty() {
            return Err("replay_command must be non-empty".to_string());
        }
        if self.failure_class.trim().is_empty() {
            return Err("failure_class must be non-empty".to_string());
        }
        if self.trace_fingerprint.trim().is_empty() {
            return Err("trace_fingerprint must be non-empty".to_string());
        }
        if self.invariant_ids.iter().any(|id| id.trim().is_empty()) {
            return Err("invariant_ids cannot contain empty values".to_string());
        }
        if self
            .artifact_paths
            .iter()
            .any(|path| path.trim().is_empty())
        {
            return Err("artifact_paths cannot contain empty values".to_string());
        }
        if let Some(ref adapter) = self.adapter {
            if adapter.trim().is_empty() {
                return Err("adapter cannot be empty when present".to_string());
            }
        }
        if let Some(ref replay_metadata) = self.replay_metadata {
            if replay_metadata.family.id != self.scenario_id {
                return Err("replay_metadata.family.id must match scenario_id".to_string());
            }
            if replay_metadata.effective_seed != self.seed {
                return Err("replay_metadata.effective_seed must match seed".to_string());
            }
            if let Some(ref seed_lineage) = self.seed_lineage {
                if seed_lineage.seed_lineage_id != replay_metadata.seed_plan.seed_lineage_id {
                    return Err(
                        "seed_lineage.seed_lineage_id must match replay_metadata.seed_plan.seed_lineage_id"
                            .to_string(),
                    );
                }
            }
        }

        let normalized_invariants = normalize_string_ids(self.invariant_ids.clone());
        if normalized_invariants != self.invariant_ids {
            return Err("invariant_ids must be sorted and deduplicated".to_string());
        }
        let normalized_artifacts = normalize_string_ids(self.artifact_paths.clone());
        if normalized_artifacts != self.artifact_paths {
            return Err("artifact_paths must be sorted and deduplicated".to_string());
        }

        Ok(())
    }

    /// Serialize to pretty-printed JSON.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Write this manifest to `<base>/<scenario_id>/<seed>/manifest.json`.
    ///
    /// Note: the test harness writes `repro_manifest.json` under
    /// `$ASUPERSYNC_TEST_ARTIFACTS_DIR/<scenario_id>/`.
    pub fn write_to_dir(&self, base_dir: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
        let dir = base_dir
            .join(&self.scenario_id)
            .join(format!("0x{:X}", self.seed));
        std::fs::create_dir_all(&dir)?;
        let path = dir.join("manifest.json");
        let json = self
            .to_json()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(&path, json)?;
        tracing::info!(
            path = %path.display(),
            scenario = %self.scenario_id,
            seed = %format_args!("0x{:X}", self.seed),
            "wrote repro manifest"
        );
        Ok(path)
    }
}

/// Load a [`ReproManifest`] from a JSON file.
pub fn load_repro_manifest(path: &std::path::Path) -> Result<ReproManifest, std::io::Error> {
    let content = std::fs::read_to_string(path)?;
    serde_json::from_str(&content)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}

/// Capture a snapshot of test-relevant environment variables.
///
/// Only includes `ASUPERSYNC_*` and `RUST_LOG` variables.
/// Sorted by key for deterministic output.
#[must_use]
pub fn capture_test_env() -> Vec<(String, String)> {
    let mut env: Vec<(String, String)> = std::env::vars()
        .filter(|(k, _)| k.starts_with("ASUPERSYNC_") || k == "RUST_LOG")
        .collect();
    env.sort_by(|a, b| a.0.cmp(&b.0));
    env
}

/// Create a [`TestContext`] from a [`ReproManifest`] for replay.
#[must_use]
pub fn replay_context_from_manifest(manifest: &ReproManifest) -> TestContext {
    let mut ctx = TestContext::new(&manifest.scenario_id, manifest.seed);
    if let Some(ref subsystem) = manifest.subsystem {
        ctx = ctx.with_subsystem(subsystem);
    }
    if let Some(ref invariant) = manifest.invariant {
        ctx = ctx.with_invariant(invariant);
    } else if let Some(first_invariant_id) = manifest.invariant_ids.first() {
        ctx = ctx.with_invariant(first_invariant_id);
    }
    if let Some(replay_metadata) = manifest.replay_metadata.clone() {
        let seed_lineage = manifest
            .seed_lineage
            .clone()
            .unwrap_or_else(|| SeedLineageRecord::from_plan(&replay_metadata.seed_plan));
        ctx = ctx.with_replay_provenance(
            manifest
                .adapter
                .clone()
                .unwrap_or_else(|| LIVE_CURRENT_THREAD_ADAPTER.to_string()),
            replay_metadata,
            seed_lineage,
        );
    } else if let Some(ref adapter) = manifest.adapter {
        ctx.adapter = Some(adapter.clone());
    }
    ctx
}

// ============================================================================
// E2E Environment Orchestration
// ============================================================================

/// An OS-assigned ephemeral port with a label for identification.
#[derive(Debug, Clone, serde::Serialize)]
pub struct AllocatedPort {
    /// Human-readable label.
    pub label: String,
    /// The allocated port number.
    pub port: u16,
}

/// Manages allocation of OS-assigned ephemeral ports for test isolation.
#[derive(Debug)]
pub struct PortAllocator {
    entries: Vec<PortEntry>,
}

#[derive(Debug)]
struct PortEntry {
    label: String,
    port: u16,
    listener: Option<std::net::TcpListener>,
}

impl PortAllocator {
    /// Create a new, empty allocator.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Allocate a single ephemeral port with a label.
    pub fn allocate(&mut self, label: &str) -> std::io::Result<u16> {
        let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
        let port = listener.local_addr()?.port();
        tracing::debug!(label = %label, port = port, "allocated ephemeral port");
        self.entries.push(PortEntry {
            label: label.to_string(),
            port,
            listener: Some(listener),
        });
        Ok(port)
    }

    /// Allocate `count` ephemeral ports with a shared label prefix.
    pub fn allocate_n(&mut self, label: &str, count: usize) -> std::io::Result<Vec<u16>> {
        let mut ports = Vec::with_capacity(count);
        for i in 0..count {
            let suffixed = format!("{label}_{i}");
            ports.push(self.allocate(&suffixed)?);
        }
        Ok(ports)
    }

    /// Release all held ports.
    pub fn release_all(&mut self) {
        for entry in &mut self.entries {
            entry.listener = None;
        }
        tracing::debug!(count = self.entries.len(), "released all held ports");
    }

    /// Returns the list of allocated ports with their labels.
    #[must_use]
    pub fn allocated_ports(&self) -> Vec<AllocatedPort> {
        self.entries
            .iter()
            .map(|e| AllocatedPort {
                label: e.label.clone(),
                port: e.port,
            })
            .collect()
    }

    /// Look up a port by label.
    #[must_use]
    pub fn port_for(&self, label: &str) -> Option<u16> {
        self.entries
            .iter()
            .find(|e| e.label == label)
            .map(|e| e.port)
    }

    /// Returns the number of currently allocated ports.
    #[must_use]
    pub fn count(&self) -> usize {
        self.entries.len()
    }
}

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

/// Trait for deterministic fixture services in E2E tests.
pub trait FixtureService: std::fmt::Debug {
    /// Returns the service name.
    fn name(&self) -> &str;
    /// Start the service.
    fn start(&mut self) -> Result<(), Box<dyn std::error::Error>>;
    /// Stop the service.
    fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>>;
    /// Returns `true` if the service is healthy.
    fn is_healthy(&self) -> bool;
}

#[derive(Debug)]
struct ServiceEntry {
    service: Box<dyn FixtureService>,
    started_at: Instant,
}

/// Structured metadata about the test environment.
#[derive(Debug, Clone, serde::Serialize)]
pub struct EnvironmentMetadata {
    /// Operating system.
    pub os: &'static str,
    /// CPU architecture.
    pub arch: &'static str,
    /// Pointer width in bits.
    pub pointer_width: u32,
    /// Test identifier.
    pub test_id: String,
    /// Root seed.
    pub seed: u64,
    /// Allocated ports with labels.
    pub ports: Vec<AllocatedPort>,
    /// Names of registered fixture services.
    pub services: Vec<String>,
}

impl EnvironmentMetadata {
    /// Emit all metadata fields as a structured tracing event.
    pub fn log(&self) {
        tracing::info!(
            test_id = %self.test_id,
            seed = %format_args!("0x{:X}", self.seed),
            os = %self.os,
            arch = %self.arch,
            pointer_width = self.pointer_width,
            port_count = self.ports.len(),
            service_count = self.services.len(),
            "E2E ENVIRONMENT METADATA"
        );
    }

    /// Serialize to pretty-printed JSON.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Write metadata to a file alongside other test artifacts.
    pub fn write_to_dir(&self, base_dir: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
        let safe_id = self.test_id.replace(|c: char| !c.is_alphanumeric(), "_");
        let dir = base_dir.join(&safe_id);
        std::fs::create_dir_all(&dir)?;
        let path = dir.join("environment.json");
        let json = self
            .to_json()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(&path, json)?;
        tracing::info!(path = %path.display(), test_id = %self.test_id, "wrote environment metadata");
        Ok(path)
    }
}

impl std::fmt::Display for EnvironmentMetadata {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "env[test_id={} seed=0x{:X} os={} arch={} ports={} services={}]",
            self.test_id,
            self.seed,
            self.os,
            self.arch,
            self.ports.len(),
            self.services.len(),
        )
    }
}

/// Hermetic E2E test environment with managed services, ports, and metadata.
pub struct TestEnvironment {
    context: TestContext,
    ports: PortAllocator,
    services: Vec<ServiceEntry>,
    cleanup_fns: Vec<Box<dyn FnOnce()>>,
    torn_down: bool,
}

impl std::fmt::Debug for TestEnvironment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TestEnvironment")
            .field("context", &self.context)
            .field("ports", &self.ports)
            .field("services", &self.services)
            .field(
                "cleanup_fns",
                &format_args!("[{} fns]", self.cleanup_fns.len()),
            )
            .field("torn_down", &self.torn_down)
            .finish()
    }
}

impl TestEnvironment {
    /// Create a new test environment from a [`TestContext`].
    #[must_use]
    pub fn new(context: TestContext) -> Self {
        context.log_start();
        tracing::info!(
            test_id = %context.test_id,
            seed = %format_args!("0x{:X}", context.seed),
            "E2E environment created"
        );
        Self {
            context,
            ports: PortAllocator::new(),
            services: Vec::new(),
            cleanup_fns: Vec::new(),
            torn_down: false,
        }
    }

    /// Returns a reference to the underlying [`TestContext`].
    #[must_use]
    pub fn context(&self) -> &TestContext {
        &self.context
    }

    /// Returns a reference to the [`PortAllocator`].
    #[must_use]
    pub fn ports(&self) -> &PortAllocator {
        &self.ports
    }

    /// Allocate a single ephemeral port with a label.
    pub fn allocate_port(&mut self, label: &str) -> std::io::Result<u16> {
        self.ports.allocate(label)
    }

    /// Allocate multiple ephemeral ports with a shared label prefix.
    pub fn allocate_ports(&mut self, label: &str, count: usize) -> std::io::Result<Vec<u16>> {
        self.ports.allocate_n(label, count)
    }

    /// Look up a previously allocated port by label.
    #[must_use]
    pub fn port_for(&self, label: &str) -> Option<u16> {
        self.ports.port_for(label)
    }

    /// Register a fixture service (does not start it).
    pub fn register_service(&mut self, service: Box<dyn FixtureService>) {
        tracing::debug!(service = %service.name(), "registered fixture service");
        self.services.push(ServiceEntry {
            service,
            started_at: Instant::now(),
        });
    }

    /// Start all registered services.
    pub fn start_all_services(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        for entry in &mut self.services {
            tracing::info!(service = %entry.service.name(), "starting fixture service");
            entry.service.start()?;
            entry.started_at = Instant::now();
        }
        Ok(())
    }

    /// Check health of all services.
    #[must_use]
    pub fn health_check(&self) -> Vec<(&str, bool)> {
        self.services
            .iter()
            .map(|e| (e.service.name(), e.service.is_healthy()))
            .collect()
    }

    /// Register a cleanup function to run during teardown.
    pub fn on_teardown<F: FnOnce() + 'static>(&mut self, f: F) {
        self.cleanup_fns.push(Box::new(f));
    }

    /// Build the current [`EnvironmentMetadata`] snapshot.
    #[must_use]
    pub fn metadata(&self) -> EnvironmentMetadata {
        EnvironmentMetadata {
            os: std::env::consts::OS,
            arch: std::env::consts::ARCH,
            pointer_width: (std::mem::size_of::<usize>() * 8) as u32,
            test_id: self.context.test_id.clone(),
            seed: self.context.seed,
            ports: self.ports.allocated_ports(),
            services: self
                .services
                .iter()
                .map(|e| e.service.name().to_string())
                .collect(),
        }
    }

    /// Emit environment metadata to structured logs.
    pub fn emit_metadata(&self) {
        self.metadata().log();
    }

    /// Write environment metadata to the artifact directory (if configured).
    #[must_use]
    pub fn write_metadata_artifact(&self) -> Option<std::io::Result<std::path::PathBuf>> {
        artifact_dir_from_env().map(|dir| self.metadata().write_to_dir(&dir))
    }

    /// Perform explicit teardown: stop services, release ports, run cleanup fns.
    pub fn teardown(&mut self) {
        if self.torn_down {
            return;
        }
        self.torn_down = true;
        tracing::info!(test_id = %self.context.test_id, "E2E environment teardown");

        for entry in self.services.iter_mut().rev() {
            let elapsed = entry.started_at.elapsed();
            tracing::debug!(
                service = %entry.service.name(),
                elapsed_ms = elapsed.as_millis().min(u128::from(u64::MAX)) as u64,
                "stopping fixture service"
            );
            if let Err(e) = entry.service.stop() {
                tracing::warn!(service = %entry.service.name(), error = %e, "fixture service stop failed");
            }
        }
        self.ports.release_all();
        let fns: Vec<_> = self.cleanup_fns.drain(..).collect();
        for f in fns.into_iter().rev() {
            f();
        }
        tracing::info!(test_id = %self.context.test_id, "E2E environment teardown complete");
    }
}

impl Drop for TestEnvironment {
    fn drop(&mut self) {
        self.teardown();
    }
}

/// A no-op fixture service for testing the environment orchestration itself.
#[derive(Debug)]
pub struct NoOpFixtureService {
    name: String,
    started: bool,
}

impl NoOpFixtureService {
    /// Create a no-op service with the given name.
    #[must_use]
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            started: false,
        }
    }
}

impl FixtureService for NoOpFixtureService {
    fn name(&self) -> &str {
        &self.name
    }

    fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.started = true;
        Ok(())
    }

    fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.started = false;
        Ok(())
    }

    fn is_healthy(&self) -> bool {
        self.started
    }
}

// ============================================================================
// Concrete Fixture Services (bd-76y5)
// ============================================================================

/// Poll a [`FixtureService`] until `is_healthy()` returns `true`, with
/// exponential backoff. Returns an error if `timeout` elapses first.
pub fn wait_until_healthy(
    service: &dyn FixtureService,
    timeout: Duration,
) -> Result<Duration, Box<dyn std::error::Error>> {
    let start = Instant::now();
    let mut interval = Duration::from_millis(50);
    let max_interval = Duration::from_millis(500);

    loop {
        if service.is_healthy() {
            let elapsed = start.elapsed();
            tracing::info!(
                service = %service.name(),
                elapsed_ms = elapsed.as_millis().min(u128::from(u64::MAX)) as u64,
                "service healthy"
            );
            return Ok(elapsed);
        }

        if start.elapsed() >= timeout {
            return Err(format!(
                "service '{}' not healthy after {:?}",
                service.name(),
                timeout
            )
            .into());
        }

        std::thread::sleep(interval);
        interval = (interval * 2).min(max_interval);
    }
}

/// A fixture service backed by a Docker container.
///
/// Launches a container with `docker run`, removes it on stop, and health
/// checks via a configurable command (defaults to checking if the container
/// is in `running` state).
///
/// # Example
///
/// ```ignore
/// let mut redis = DockerFixtureService::new("redis", "redis:7-alpine")
///     .with_port_map(port, 6379)
///     .with_health_cmd(vec!["redis-cli", "ping"]);
/// redis.start()?;
/// wait_until_healthy(&redis, Duration::from_secs(10))?;
/// ```
#[derive(Debug)]
pub struct DockerFixtureService {
    service_name: String,
    image: String,
    container_name: String,
    port_maps: Vec<(u16, u16)>,
    env_vars: Vec<(String, String)>,
    health_cmd: Option<Vec<String>>,
    started: bool,
}

impl DockerFixtureService {
    /// Create a new Docker fixture with a service name and image.
    ///
    /// A unique container name is generated from the service name and process
    /// ID to avoid collisions between parallel test runs.
    #[must_use]
    pub fn new(service_name: &str, image: &str) -> Self {
        let container_name = format!("asupersync-test-{}-{}", service_name, std::process::id());
        Self {
            service_name: service_name.to_string(),
            image: image.to_string(),
            container_name,
            port_maps: Vec::new(),
            env_vars: Vec::new(),
            health_cmd: None,
            started: false,
        }
    }

    /// Map a host port to a container port.
    #[must_use]
    pub fn with_port_map(mut self, host_port: u16, container_port: u16) -> Self {
        self.port_maps.push((host_port, container_port));
        self
    }

    /// Set an environment variable in the container.
    #[must_use]
    pub fn with_env(mut self, key: &str, value: &str) -> Self {
        self.env_vars.push((key.to_string(), value.to_string()));
        self
    }

    /// Set a custom health check command to run inside the container via
    /// `docker exec`.
    #[must_use]
    pub fn with_health_cmd(mut self, cmd: Vec<&str>) -> Self {
        self.health_cmd = Some(cmd.into_iter().map(String::from).collect());
        self
    }

    /// Returns the container name.
    #[must_use]
    pub fn container_name(&self) -> &str {
        &self.container_name
    }

    fn run_docker_cmd(args: &[&str]) -> Result<std::process::Output, Box<dyn std::error::Error>> {
        let output = std::process::Command::new("docker").args(args).output()?;
        Ok(output)
    }
}

impl FixtureService for DockerFixtureService {
    fn name(&self) -> &str {
        &self.service_name
    }

    fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        // Remove any stale container with the same name.
        let _ = Self::run_docker_cmd(&["rm", "-f", &self.container_name]);

        let mut args = vec!["run", "-d", "--name", &self.container_name];

        let port_strings: Vec<String> = self
            .port_maps
            .iter()
            .map(|(h, c)| format!("127.0.0.1:{h}:{c}"))
            .collect();
        for ps in &port_strings {
            args.push("-p");
            args.push(ps);
        }

        let env_strings: Vec<String> = self
            .env_vars
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect();
        for es in &env_strings {
            args.push("-e");
            args.push(es);
        }

        args.push(&self.image);

        tracing::info!(
            container = %self.container_name,
            image = %self.image,
            "starting docker container"
        );

        let output = Self::run_docker_cmd(&args)?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(format!(
                "docker run failed for '{}': {}",
                self.container_name, stderr
            )
            .into());
        }

        self.started = true;
        Ok(())
    }

    fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if !self.started {
            return Ok(());
        }
        tracing::info!(container = %self.container_name, "stopping docker container");
        let output = Self::run_docker_cmd(&["rm", "-f", &self.container_name])?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            tracing::warn!(
                container = %self.container_name,
                error = %stderr,
                "docker rm failed"
            );
        }
        self.started = false;
        Ok(())
    }

    fn is_healthy(&self) -> bool {
        if !self.started {
            return false;
        }

        self.health_cmd.as_ref().map_or_else(
            || {
                // Fallback: check container state via docker inspect.
                match Self::run_docker_cmd(&[
                    "inspect",
                    "-f",
                    "{{.State.Running}}",
                    &self.container_name,
                ]) {
                    Ok(output) => {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        stdout.trim() == "true"
                    }
                    Err(_) => false,
                }
            },
            |cmd| {
                let mut args = vec!["exec", &self.container_name];
                let cmd_refs: Vec<&str> = cmd.iter().map(String::as_str).collect();
                args.extend(cmd_refs);
                match Self::run_docker_cmd(&args) {
                    Ok(output) => output.status.success(),
                    Err(_) => false,
                }
            },
        )
    }
}

/// Per-test temporary directory that is automatically cleaned up on drop.
///
/// Wraps [`tempfile::TempDir`] behind the [`FixtureService`] trait so it can
/// be managed by [`TestEnvironment`] alongside other fixtures.
#[derive(Debug)]
pub struct TempDirFixture {
    service_name: String,
    prefix: String,
    dir: Option<tempfile::TempDir>,
}

impl TempDirFixture {
    /// Create a new temp-dir fixture. The directory is created on `start()`.
    #[must_use]
    pub fn new(service_name: &str) -> Self {
        Self {
            service_name: service_name.to_string(),
            prefix: format!("asupersync-{service_name}-"),
            dir: None,
        }
    }

    /// Override the directory-name prefix (default: `asupersync-<name>-`).
    #[must_use]
    pub fn with_prefix(mut self, prefix: &str) -> Self {
        self.prefix = prefix.to_string();
        self
    }

    /// Returns the path if the directory has been created.
    #[must_use]
    pub fn path(&self) -> Option<&std::path::Path> {
        self.dir.as_ref().map(tempfile::TempDir::path)
    }
}

impl FixtureService for TempDirFixture {
    fn name(&self) -> &str {
        &self.service_name
    }

    fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::Builder::new().prefix(&self.prefix).tempdir()?;
        tracing::debug!(
            service = %self.service_name,
            path = %dir.path().display(),
            "created temp directory"
        );
        self.dir = Some(dir);
        Ok(())
    }

    fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(dir) = self.dir.take() {
            let path = dir.path().display().to_string();
            // TempDir::drop handles cleanup; we just log.
            drop(dir);
            tracing::debug!(service = %self.service_name, path = %path, "cleaned up temp directory");
        }
        Ok(())
    }

    fn is_healthy(&self) -> bool {
        self.dir.as_ref().is_some_and(|d| d.path().is_dir())
    }
}

/// Wraps a closure-based in-process service behind [`FixtureService`].
///
/// Use this for lightweight, in-process test servers (WebSocket echo, HTTP
/// mock, etc.) where a full Docker container is unnecessary.
///
/// The `start_fn` receives a mutable reference to `state` and should spawn
/// whatever background work is needed, storing handles in `state`.
/// The `stop_fn` receives the state and must shut everything down.
///
/// # Example
///
/// ```ignore
/// use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
///
/// let running = Arc::new(AtomicBool::new(false));
/// let r = running.clone();
/// let svc = InProcessService::new(
///     "echo_ws",
///     running,
///     move |state| { state.store(true, Ordering::SeqCst); Ok(()) },
///     |state| { state.store(false, Ordering::SeqCst); Ok(()) },
///     |state| state.load(Ordering::SeqCst),
/// );
/// ```
type InProcessResult = Result<(), Box<dyn std::error::Error>>;
type InProcessStartFn<S> = Box<dyn FnMut(&mut S) -> InProcessResult>;
type InProcessStopFn<S> = Box<dyn FnMut(&mut S) -> InProcessResult>;
type InProcessHealthFn<S> = Box<dyn Fn(&S) -> bool>;

/// In-process fixture service backed by user-provided start/stop closures.
pub struct InProcessService<S: std::fmt::Debug + 'static> {
    service_name: String,
    state: S,
    start_fn: InProcessStartFn<S>,
    stop_fn: InProcessStopFn<S>,
    health_fn: InProcessHealthFn<S>,
}

impl<S: std::fmt::Debug + 'static> std::fmt::Debug for InProcessService<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InProcessService")
            .field("service_name", &self.service_name)
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

impl<S: std::fmt::Debug + 'static> InProcessService<S> {
    /// Create a new in-process service.
    pub fn new(
        name: &str,
        state: S,
        start_fn: impl FnMut(&mut S) -> InProcessResult + 'static,
        stop_fn: impl FnMut(&mut S) -> InProcessResult + 'static,
        health_fn: impl Fn(&S) -> bool + 'static,
    ) -> Self {
        Self {
            service_name: name.to_string(),
            state,
            start_fn: Box::new(start_fn),
            stop_fn: Box::new(stop_fn),
            health_fn: Box::new(health_fn),
        }
    }

    /// Returns a reference to the service state.
    #[must_use]
    pub fn state(&self) -> &S {
        &self.state
    }
}

impl<S: std::fmt::Debug + 'static> FixtureService for InProcessService<S> {
    fn name(&self) -> &str {
        &self.service_name
    }

    fn start(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        (self.start_fn)(&mut self.state)
    }

    fn stop(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        (self.stop_fn)(&mut self.state)
    }

    fn is_healthy(&self) -> bool {
        (self.health_fn)(&self.state)
    }
}

/// Per-test JSON summary produced by [`TestHarness`].
#[derive(Debug, Clone, serde::Serialize)]
pub struct TestSummary {
    /// Name of the test.
    pub test_name: String,
    /// Whether the test passed overall.
    pub passed: bool,
    /// Total assertions.
    pub total_assertions: usize,
    /// Passed assertions.
    pub passed_assertions: usize,
    /// Failed assertions.
    pub failed_assertions: usize,
    /// Total duration in milliseconds.
    pub duration_ms: f64,
    /// Hierarchical phase tree.
    pub phases: Vec<PhaseNode>,
    /// Artifacts collected on failure (file paths).
    pub failure_artifacts: Vec<String>,
    /// Event log statistics.
    pub event_stats: EventStats,
    /// Structured test context (if provided).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<TestContext>,
}

/// Summary statistics from the event log.
#[derive(Debug, Clone, serde::Serialize)]
pub struct EventStats {
    /// Total events captured.
    pub total_events: usize,
    /// Task spawns.
    pub task_spawns: usize,
    /// Task completions.
    pub task_completions: usize,
    /// Reactor polls.
    pub reactor_polls: usize,
    /// Errors logged.
    pub errors: usize,
    /// Warnings logged.
    pub warnings: usize,
}

/// E2E test harness with hierarchical phase tracking, assertion capture,
/// and automatic failure artifact collection.
///
/// # Example
///
/// ```ignore
/// use asupersync::test_logging::TestHarness;
///
/// let mut harness = TestHarness::new("my_e2e_test");
/// harness.enter_phase("setup");
///   harness.enter_phase("create_listener");
///   harness.assert_eq("port bound", 8080, listener.port());
///   harness.exit_phase();
/// harness.exit_phase();
///
/// harness.enter_phase("exercise");
/// // ... test body ...
/// harness.exit_phase();
///
/// let summary = harness.finish();
/// println!("{}", serde_json::to_string_pretty(&summary).unwrap());
/// ```
#[derive(Debug)]
pub struct TestHarness {
    /// Test name.
    test_name: String,
    /// Underlying event logger.
    logger: TestLogger,
    /// Stack of open phase indices (indices into the flat phases vec).
    phase_stack: Vec<usize>,
    /// All phases (flat storage; tree structure via children indices).
    phases: Vec<PhaseNode>,
    /// All assertions recorded.
    assertions: Vec<AssertionRecord>,
    /// Artifact directory for failure dumps.
    artifact_dir: Option<std::path::PathBuf>,
    /// Collected artifact paths.
    artifacts: Vec<String>,
    /// Start instant.
    start: Instant,
    /// Structured test context for standardized logging.
    context: Option<TestContext>,
}

impl TestHarness {
    /// Create a new test harness.
    #[must_use]
    pub fn new(test_name: &str) -> Self {
        Self {
            test_name: test_name.to_string(),
            logger: TestLogger::new(TestLogLevel::from_env()),
            phase_stack: Vec::new(),
            phases: Vec::new(),
            assertions: Vec::new(),
            artifact_dir: artifact_dir_from_env(),
            artifacts: Vec::new(),
            start: Instant::now(),
            context: None,
        }
    }

    /// Create a harness with a specific log level.
    #[must_use]
    pub fn with_level(test_name: &str, level: TestLogLevel) -> Self {
        Self {
            test_name: test_name.to_string(),
            logger: TestLogger::new(level),
            phase_stack: Vec::new(),
            phases: Vec::new(),
            assertions: Vec::new(),
            artifact_dir: artifact_dir_from_env(),
            artifacts: Vec::new(),
            start: Instant::now(),
            context: None,
        }
    }

    /// Create a harness with a structured [`TestContext`] for standardized logging.
    ///
    /// The context fields (test_id, seed, subsystem, invariant) are included in
    /// the test summary and emitted in tracing events.
    #[must_use]
    pub fn with_context(test_name: &str, ctx: TestContext) -> Self {
        ctx.log_start();
        Self {
            test_name: test_name.to_string(),
            logger: TestLogger::new(TestLogLevel::from_env()),
            phase_stack: Vec::new(),
            phases: Vec::new(),
            assertions: Vec::new(),
            artifact_dir: artifact_dir_from_env(),
            artifacts: Vec::new(),
            start: Instant::now(),
            context: Some(ctx),
        }
    }

    /// Returns the test context, if one was provided.
    #[must_use]
    pub fn context(&self) -> Option<&TestContext> {
        self.context.as_ref()
    }

    /// Access the underlying [`TestLogger`].
    #[must_use]
    pub fn logger(&self) -> &TestLogger {
        &self.logger
    }

    /// Returns the current phase path as "phase > section > step".
    #[must_use]
    pub fn current_phase_path(&self) -> String {
        self.phase_stack
            .iter()
            .map(|&idx| self.phases[idx].name.as_str())
            .collect::<Vec<_>>()
            .join(" > ")
    }

    /// Enter a new phase (push onto the hierarchy stack).
    pub fn enter_phase(&mut self, name: &str) {
        let elapsed = self.start.elapsed().as_secs_f64() * 1000.0;
        let depth = self.phase_stack.len();
        let node = PhaseNode {
            name: name.to_string(),
            depth,
            start_ms: elapsed,
            end_ms: None,
            assertions: Vec::new(),
            children: Vec::new(),
        };
        let idx = self.phases.len();
        self.phases.push(node);

        // Link as child of current parent.
        if let Some(&parent_idx) = self.phase_stack.last() {
            self.phases[parent_idx].children.push(PhaseNode {
                name: String::new(),
                depth: 0,
                start_ms: 0.0,
                end_ms: None,
                assertions: Vec::new(),
                children: Vec::new(),
            });
            // We'll rebuild the tree in finish(); for now track indices.
        }

        self.phase_stack.push(idx);

        tracing::info!(
            phase = %name,
            depth = depth,
            path = %self.current_phase_path(),
            ">>> ENTER PHASE"
        );
    }

    /// Exit the current phase.
    pub fn exit_phase(&mut self) {
        let elapsed = self.start.elapsed().as_secs_f64() * 1000.0;
        if let Some(idx) = self.phase_stack.pop() {
            self.phases[idx].end_ms = Some(elapsed);
            tracing::info!(
                phase = %self.phases[idx].name,
                duration_ms = %(elapsed - self.phases[idx].start_ms),
                "<<< EXIT PHASE"
            );
        }
    }

    /// Record an assertion with context.
    pub fn record_assertion(
        &mut self,
        description: &str,
        passed: bool,
        expected: &str,
        actual: &str,
    ) {
        let elapsed = self.start.elapsed().as_secs_f64() * 1000.0;
        let phase_path = self.current_phase_path();

        let record = AssertionRecord {
            description: description.to_string(),
            passed,
            expected: expected.to_string(),
            actual: actual.to_string(),
            phase_path: phase_path.clone(),
            elapsed_ms: elapsed,
        };

        // Attach to current phase if one is open.
        if let Some(&idx) = self.phase_stack.last() {
            self.phases[idx].assertions.push(record.clone());
        }
        self.assertions.push(record);

        if passed {
            tracing::debug!(
                assertion = %description,
                phase = %phase_path,
                "PASS"
            );
        } else {
            tracing::error!(
                assertion = %description,
                expected = %expected,
                actual = %actual,
                phase = %phase_path,
                "FAIL"
            );
        }
    }

    /// Assert equality and record the result.
    ///
    /// Returns whether the assertion passed.
    pub fn assert_eq<T: std::fmt::Debug + PartialEq>(
        &mut self,
        description: &str,
        expected: &T,
        actual: &T,
    ) -> bool {
        let passed = expected == actual;
        self.record_assertion(
            description,
            passed,
            &format!("{expected:?}"),
            &format!("{actual:?}"),
        );
        passed
    }

    /// Assert a boolean condition and record the result.
    ///
    /// Returns whether the assertion passed.
    pub fn assert_true(&mut self, description: &str, condition: bool) -> bool {
        self.record_assertion(description, condition, "true", &format!("{condition}"));
        condition
    }

    /// Collect a failure artifact (writes content to artifact dir if configured).
    pub fn collect_artifact(&mut self, name: &str, content: &str) {
        if let Some(ref dir) = self.artifact_dir {
            let safe_test = self.test_name.replace(|c: char| !c.is_alphanumeric(), "_");
            let artifact_dir = dir.join(&safe_test);
            if std::fs::create_dir_all(&artifact_dir).is_ok() {
                let path = artifact_dir.join(name);
                if std::fs::write(&path, content).is_ok() {
                    self.artifacts.push(path.display().to_string());
                    tracing::info!(path = %path.display(), "collected failure artifact");
                }
            }
        }
    }

    /// Collect the phase names executed so far (flat list).
    #[must_use]
    pub fn phases_executed(&self) -> Vec<String> {
        self.phases.iter().map(|p| p.name.clone()).collect()
    }

    /// Generate a [`ReproManifest`] from the current harness state.
    #[must_use]
    pub fn repro_manifest(&self, passed: bool) -> ReproManifest {
        let mut manifest = self.context.as_ref().map_or_else(
            || ReproManifest::new(0, &self.test_name, passed),
            |ctx| ReproManifest::from_context(ctx, passed),
        );

        manifest = manifest
            .with_env_snapshot()
            .with_phases(self.phases_executed())
            .with_artifact_paths(self.artifacts.clone());

        if passed {
            manifest = manifest.with_failure_class(FAILURE_CLASS_PASSED);
        } else {
            if let Some(first_failure) = self.assertions.iter().find(|a| !a.passed) {
                manifest = manifest.with_failure_reason(&format!(
                    "{}: expected={}, actual={}",
                    first_failure.description, first_failure.expected, first_failure.actual,
                ));
            }
            manifest = manifest.with_failure_class(FAILURE_CLASS_ASSERTION_FAILURE);
        }

        manifest
    }

    /// Build the hierarchical phase tree from flat storage.
    ///
    /// Uses an index-path stack to avoid unsafe pointer aliasing.
    /// The stack tracks the index path from root to the current parent,
    /// allowing safe traversal via repeated indexing.
    fn build_phase_tree(&self) -> Vec<PhaseNode> {
        let mut roots: Vec<PhaseNode> = Vec::new();
        // Stack of (depth, child_index) pairs forming a path from roots
        // to the current insertion point.
        let mut path: Vec<(usize, usize)> = Vec::new();

        for phase in &self.phases {
            let node = PhaseNode {
                name: phase.name.clone(),
                depth: phase.depth,
                start_ms: phase.start_ms,
                end_ms: phase.end_ms,
                assertions: phase.assertions.clone(),
                children: Vec::new(),
            };

            if phase.depth == 0 {
                roots.push(node);
                let idx = roots.len() - 1;
                path.clear();
                path.push((0, idx));
            } else {
                // Pop stack until we find the parent depth.
                while path.len() > phase.depth {
                    path.pop();
                }

                // Navigate to the parent node via the index path and push.
                if !path.is_empty() {
                    // First index is into roots
                    let (_, root_idx) = path[0];
                    let mut current = &mut roots[root_idx];
                    for &(_, child_idx) in &path[1..] {
                        current = &mut current.children[child_idx];
                    }
                    current.children.push(node);
                    let child_idx = current.children.len() - 1;
                    path.push((phase.depth, child_idx));
                }
            }
        }

        roots
    }

    /// Compute event statistics from the logger.
    fn compute_event_stats(&self) -> EventStats {
        let events = self.logger.events();
        EventStats {
            total_events: events.len(),
            task_spawns: events
                .iter()
                .filter(|r| matches!(r.event, TestEvent::TaskSpawn { .. }))
                .count(),
            task_completions: events
                .iter()
                .filter(|r| matches!(r.event, TestEvent::TaskComplete { .. }))
                .count(),
            reactor_polls: events
                .iter()
                .filter(|r| matches!(r.event, TestEvent::ReactorPoll { .. }))
                .count(),
            errors: events
                .iter()
                .filter(|r| matches!(r.event, TestEvent::Error { .. }))
                .count(),
            warnings: events
                .iter()
                .filter(|r| matches!(r.event, TestEvent::Warn { .. }))
                .count(),
        }
    }

    /// Finish the test and produce a JSON-serializable summary.
    ///
    /// If the test failed and an artifact directory is configured, automatically
    /// collects the event log as an artifact.
    #[must_use]
    pub fn finish(mut self) -> TestSummary {
        // Close any unclosed phases.
        let elapsed = self.start.elapsed().as_secs_f64() * 1000.0;
        for &idx in self.phase_stack.iter().rev() {
            if self.phases[idx].end_ms.is_none() {
                self.phases[idx].end_ms = Some(elapsed);
            }
        }

        let total = self.assertions.len();
        let passed_count = self.assertions.iter().filter(|a| a.passed).count();
        let failed_count = total - passed_count;
        let overall_passed = failed_count == 0;

        // Auto-collect event log and repro manifest on failure.
        if !overall_passed {
            self.collect_artifact("event_log.txt", &self.logger.report());

            let failed_json = serde_json::to_string_pretty(
                &self
                    .assertions
                    .iter()
                    .filter(|a| !a.passed)
                    .collect::<Vec<_>>(),
            )
            .unwrap_or_default();
            self.collect_artifact("failed_assertions.json", &failed_json);

            let manifest = self.repro_manifest(false);
            if let Ok(manifest_json) = manifest.to_json() {
                self.collect_artifact("repro_manifest.json", &manifest_json);
            }
        }

        let phases = self.build_phase_tree();
        let event_stats = self.compute_event_stats();

        let summary = TestSummary {
            test_name: self.test_name.clone(),
            passed: overall_passed,
            total_assertions: total,
            passed_assertions: passed_count,
            failed_assertions: failed_count,
            duration_ms: elapsed,
            phases,
            failure_artifacts: self.artifacts.clone(),
            event_stats,
            context: self.context.clone(),
        };

        // Write JSON summary if artifact dir is configured.
        if let Some(ref dir) = self.artifact_dir {
            let safe_test = self.test_name.replace(|c: char| !c.is_alphanumeric(), "_");
            let summary_path = dir.join(format!("{safe_test}_summary.json"));
            if let Ok(json) = serde_json::to_string_pretty(&summary) {
                let _ = std::fs::create_dir_all(dir);
                let _ = std::fs::write(&summary_path, json);
            }
        }

        // Emit structured end event with context fields if available.
        if let Some(ref ctx) = self.context {
            ctx.log_end(overall_passed);
            if !overall_passed {
                ctx.log_failure("one or more assertions failed");
            }
        }

        tracing::info!(
            test = %self.test_name,
            passed = %overall_passed,
            assertions = total,
            passed_assertions = passed_count,
            failed_assertions = failed_count,
            duration_ms = %elapsed,
            "TEST SUMMARY"
        );

        summary
    }

    /// Produce the JSON string for the test summary.
    #[must_use]
    pub fn finish_json(self) -> String {
        let summary = self.finish();
        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
    }
}

/// Read the artifact directory from the environment.
fn artifact_dir_from_env() -> Option<std::path::PathBuf> {
    std::env::var("ASUPERSYNC_TEST_ARTIFACTS_DIR")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .map(std::path::PathBuf::from)
}

// ============================================================================
// TestReportAggregator — Coverage Matrix
// ============================================================================

/// Aggregates multiple [`TestSummary`] results into a coverage matrix.
#[derive(Debug, Default, serde::Serialize)]
pub struct TestReportAggregator {
    /// All collected summaries.
    pub summaries: Vec<TestSummary>,
}

/// Aggregated report with coverage matrix.
#[derive(Debug, serde::Serialize)]
pub struct AggregatedReport {
    /// Total tests run.
    pub total_tests: usize,
    /// Tests that passed.
    pub passed_tests: usize,
    /// Tests that failed.
    pub failed_tests: usize,
    /// Total assertions across all tests.
    pub total_assertions: usize,
    /// Passed assertions across all tests.
    pub passed_assertions: usize,
    /// Coverage matrix: test_name -> list of phase names exercised.
    pub coverage_matrix: Vec<CoverageMatrixRow>,
    /// Per-test summaries.
    pub tests: Vec<TestSummaryBrief>,
}

/// One row in the coverage matrix.
#[derive(Debug, serde::Serialize)]
pub struct CoverageMatrixRow {
    /// Test name.
    pub test_name: String,
    /// Whether it passed.
    pub passed: bool,
    /// Phase names exercised.
    pub phases_exercised: Vec<String>,
    /// Number of assertions.
    pub assertion_count: usize,
    /// Duration in ms.
    pub duration_ms: f64,
}

/// Brief per-test entry in the aggregated report.
#[derive(Debug, serde::Serialize)]
pub struct TestSummaryBrief {
    /// Test name.
    pub test_name: String,
    /// Pass/fail.
    pub passed: bool,
    /// Assertion counts.
    pub assertions: usize,
    /// Failed count.
    pub failures: usize,
    /// Duration.
    pub duration_ms: f64,
}

impl TestReportAggregator {
    /// Create a new empty aggregator.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a test summary.
    pub fn add(&mut self, summary: TestSummary) {
        self.summaries.push(summary);
    }

    /// Collect phase names from a phase tree (recursive).
    fn collect_phase_names(phases: &[PhaseNode], out: &mut Vec<String>) {
        for phase in phases {
            out.push(phase.name.clone());
            Self::collect_phase_names(&phase.children, out);
        }
    }

    /// Produce the aggregated report.
    #[must_use]
    pub fn report(&self) -> AggregatedReport {
        let total = self.summaries.len();
        let passed = self.summaries.iter().filter(|s| s.passed).count();

        let total_assertions: usize = self.summaries.iter().map(|s| s.total_assertions).sum();
        let passed_assertions: usize = self.summaries.iter().map(|s| s.passed_assertions).sum();

        let coverage_matrix: Vec<CoverageMatrixRow> = self
            .summaries
            .iter()
            .map(|s| {
                let mut phases = Vec::new();
                Self::collect_phase_names(&s.phases, &mut phases);
                CoverageMatrixRow {
                    test_name: s.test_name.clone(),
                    passed: s.passed,
                    phases_exercised: phases,
                    assertion_count: s.total_assertions,
                    duration_ms: s.duration_ms,
                }
            })
            .collect();

        let tests: Vec<TestSummaryBrief> = self
            .summaries
            .iter()
            .map(|s| TestSummaryBrief {
                test_name: s.test_name.clone(),
                passed: s.passed,
                assertions: s.total_assertions,
                failures: s.failed_assertions,
                duration_ms: s.duration_ms,
            })
            .collect();

        AggregatedReport {
            total_tests: total,
            passed_tests: passed,
            failed_tests: total - passed,
            total_assertions,
            passed_assertions,
            coverage_matrix,
            tests,
        }
    }

    /// Produce the aggregated report as a JSON string.
    #[must_use]
    pub fn report_json(&self) -> String {
        serde_json::to_string_pretty(&self.report()).unwrap_or_else(|_| "{}".to_string())
    }
}

// ============================================================================
// Harness Macros
// ============================================================================

/// Enter a hierarchical phase in a [`TestHarness`].
///
/// ```ignore
/// harness_phase!(harness, "setup");
/// // ... work ...
/// harness_phase_exit!(harness);
/// ```
#[macro_export]
macro_rules! harness_phase {
    ($harness:expr, $name:expr) => {
        $harness.enter_phase($name);
    };
}

/// Exit the current phase in a [`TestHarness`].
#[macro_export]
macro_rules! harness_phase_exit {
    ($harness:expr) => {
        $harness.exit_phase();
    };
}

/// Assert equality within a [`TestHarness`], recording the result.
///
/// Panics if the assertion fails.
#[macro_export]
macro_rules! harness_assert_eq {
    ($harness:expr, $desc:expr, $expected:expr, $actual:expr) => {
        match (&$expected, &$actual) {
            (expected_val, actual_val) => {
                if !$harness.assert_eq($desc, expected_val, actual_val) {
                    panic!(
                        "harness assertion failed: {}: expected {:?}, got {:?}",
                        $desc, expected_val, actual_val
                    );
                }
            }
        }
    };
}

/// Assert a condition within a [`TestHarness`], recording the result.
///
/// Panics if the assertion fails.
#[macro_export]
macro_rules! harness_assert {
    ($harness:expr, $desc:expr, $cond:expr) => {
        if !$harness.assert_true($desc, $cond) {
            panic!("harness assertion failed: {}", $desc);
        }
    };
}

// ============================================================================
// Structured Context Macros
// ============================================================================

/// Emit a structured tracing event with standard test context fields.
///
/// Includes `test_id`, `seed`, `subsystem`, and `invariant` from a [`TestContext`].
///
/// ```ignore
/// let ctx = TestContext::new("my_test", 0xDEAD_BEEF).with_subsystem("scheduler");
/// test_structured!(ctx, "task spawned", task_count = 5);
/// ```
#[macro_export]
macro_rules! test_structured {
    ($ctx:expr, $msg:expr) => {
        tracing::info!(
            test_id = %$ctx.test_id,
            seed = %format_args!("0x{:X}", $ctx.seed),
            subsystem = $ctx.subsystem.as_deref().unwrap_or("-"),
            invariant = $ctx.invariant.as_deref().unwrap_or("-"),
            $msg
        );
    };
    ($ctx:expr, $msg:expr, $($key:ident = $value:expr),+ $(,)?) => {
        tracing::info!(
            test_id = %$ctx.test_id,
            seed = %format_args!("0x{:X}", $ctx.seed),
            subsystem = $ctx.subsystem.as_deref().unwrap_or("-"),
            invariant = $ctx.invariant.as_deref().unwrap_or("-"),
            $($key = %$value,)+
            $msg
        );
    };
}

/// Emit a structured error dump with full context for failure triage.
///
/// Includes all context fields plus a reason string. Designed for use in
/// test failure paths to maximize reproducibility information.
///
/// ```ignore
/// let ctx = TestContext::new("my_test", 42).with_subsystem("obligation");
/// dump_test_failure!(ctx, "obligation leak detected", leaked_count = 3);
/// ```
#[macro_export]
macro_rules! dump_test_failure {
    ($ctx:expr, $reason:expr) => {
        tracing::error!(
            test_id = %$ctx.test_id,
            seed = %format_args!("0x{:X}", $ctx.seed),
            subsystem = $ctx.subsystem.as_deref().unwrap_or("-"),
            invariant = $ctx.invariant.as_deref().unwrap_or("-"),
            reason = %$reason,
            "TEST FAILURE — reproduce with seed 0x{:X}", $ctx.seed
        );
    };
    ($ctx:expr, $reason:expr, $($key:ident = $value:expr),+ $(,)?) => {
        tracing::error!(
            test_id = %$ctx.test_id,
            seed = %format_args!("0x{:X}", $ctx.seed),
            subsystem = $ctx.subsystem.as_deref().unwrap_or("-"),
            invariant = $ctx.invariant.as_deref().unwrap_or("-"),
            reason = %$reason,
            $($key = %$value,)+
            "TEST FAILURE — reproduce with seed 0x{:X}", $ctx.seed
        );
    };
}

/// Assert a condition and, on failure, emit a structured dump with full context.
///
/// ```ignore
/// let ctx = TestContext::new("my_test", 42).with_subsystem("scheduler");
/// assert_with_context!(ctx, task_count > 0, "expected at least one task");
/// ```
#[macro_export]
macro_rules! assert_with_context {
    ($ctx:expr, $cond:expr, $msg:expr) => {
        if !$cond {
            $crate::dump_test_failure!($ctx, $msg);
            panic!("assertion failed [{}]: {}", $ctx.test_id, $msg);
        }
    };
    ($ctx:expr, $cond:expr, $msg:expr, $($key:ident = $value:expr),+ $(,)?) => {
        if !$cond {
            $crate::dump_test_failure!($ctx, $msg, $($key = $value),+);
            panic!("assertion failed [{}]: {}", $ctx.test_id, $msg);
        }
    };
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[allow(unsafe_code)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    #[test]
    fn test_log_level_ordering() {
        init_test("test_log_level_ordering");
        let error_warn = TestLogLevel::Error < TestLogLevel::Warn;
        crate::assert_with_log!(error_warn, "error < warn", true, error_warn);
        let warn_info = TestLogLevel::Warn < TestLogLevel::Info;
        crate::assert_with_log!(warn_info, "warn < info", true, warn_info);
        let info_debug = TestLogLevel::Info < TestLogLevel::Debug;
        crate::assert_with_log!(info_debug, "info < debug", true, info_debug);
        let debug_trace = TestLogLevel::Debug < TestLogLevel::Trace;
        crate::assert_with_log!(debug_trace, "debug < trace", true, debug_trace);
        crate::test_complete!("test_log_level_ordering");
    }

    #[test]
    fn test_log_level_from_str() {
        init_test("test_log_level_from_str");
        let error = "error".parse();
        let ok = matches!(error, Ok(TestLogLevel::Error));
        crate::assert_with_log!(ok, "parse error", true, ok);
        let error_upper = "ERROR".parse();
        let ok = matches!(error_upper, Ok(TestLogLevel::Error));
        crate::assert_with_log!(ok, "parse ERROR", true, ok);
        let warn = "warn".parse();
        let ok = matches!(warn, Ok(TestLogLevel::Warn));
        crate::assert_with_log!(ok, "parse warn", true, ok);
        let warning = "warning".parse();
        let ok = matches!(warning, Ok(TestLogLevel::Warn));
        crate::assert_with_log!(ok, "parse warning", true, ok);
        let info = "info".parse();
        let ok = matches!(info, Ok(TestLogLevel::Info));
        crate::assert_with_log!(ok, "parse info", true, ok);
        let debug_level = "debug".parse();
        let ok = matches!(debug_level, Ok(TestLogLevel::Debug));
        crate::assert_with_log!(ok, "parse debug", true, ok);
        let trace = "trace".parse();
        let ok = matches!(trace, Ok(TestLogLevel::Trace));
        crate::assert_with_log!(ok, "parse trace", true, ok);
        let invalid: Result<TestLogLevel, ()> = "invalid".parse();
        let ok = invalid.is_err();
        crate::assert_with_log!(ok, "parse invalid", true, ok);
        crate::test_complete!("test_log_level_from_str");
    }

    #[test]
    fn test_logger_captures_events() {
        init_test("test_logger_captures_events");
        let logger = TestLogger::new(TestLogLevel::Trace);

        logger.log(TestEvent::TaskSpawn {
            task_id: 1,
            name: Some("worker".into()),
        });
        logger.log(TestEvent::TaskPoll {
            task_id: 1,
            result: "pending",
        });
        logger.log(TestEvent::TaskComplete {
            task_id: 1,
            outcome: "ok",
        });

        let count = logger.event_count();
        crate::assert_with_log!(count == 3, "event_count", 3, count);
        crate::test_complete!("test_logger_captures_events");
    }

    #[test]
    fn test_logger_trace_level_is_not_verbose_by_default() {
        init_test("test_logger_trace_level_is_not_verbose_by_default");
        let logger = TestLogger::new(TestLogLevel::Trace);
        crate::assert_with_log!(
            !logger.verbose,
            "trace level should not imply immediate stderr output",
            false,
            logger.verbose
        );
        crate::test_complete!("test_logger_trace_level_is_not_verbose_by_default");
    }

    #[test]
    fn test_logger_filters_by_level() {
        init_test("test_logger_filters_by_level");
        let logger = TestLogger::new(TestLogLevel::Info);

        // This should be captured (Info level)
        logger.log(TestEvent::TaskSpawn {
            task_id: 1,
            name: None,
        });

        // This should NOT be captured (Trace level)
        logger.log(TestEvent::TaskPoll {
            task_id: 1,
            result: "pending",
        });

        let count = logger.event_count();
        crate::assert_with_log!(count == 1, "event_count", 1, count);
        crate::test_complete!("test_logger_filters_by_level");
    }

    #[test]
    fn test_logger_report_includes_statistics() {
        init_test("test_logger_report_includes_statistics");
        let logger = TestLogger::new(TestLogLevel::Trace);

        logger.log(TestEvent::TaskSpawn {
            task_id: 1,
            name: None,
        });
        logger.log(TestEvent::TaskSpawn {
            task_id: 2,
            name: None,
        });
        logger.log(TestEvent::TaskComplete {
            task_id: 1,
            outcome: "ok",
        });

        let report = logger.report();
        let has_spawns = report.contains("Task spawns: 2");
        crate::assert_with_log!(has_spawns, "report contains task spawns", true, has_spawns);
        let has_events = report.contains("3 events");
        crate::assert_with_log!(has_events, "report contains events count", true, has_events);
        crate::test_complete!("test_logger_report_includes_statistics");
    }

    #[test]
    fn test_busy_loop_detection() {
        init_test("test_busy_loop_detection");
        let logger = TestLogger::new(TestLogLevel::Trace);

        // Log some empty polls
        for _ in 0..3 {
            logger.log(TestEvent::ReactorPoll {
                timeout: None,
                events_returned: 0,
                duration: Duration::from_micros(10),
            });
        }

        // This should pass (3 <= 5)
        logger.assert_no_busy_loop(5);
        crate::test_complete!("test_busy_loop_detection");
    }

    #[test]
    #[should_panic(expected = "Busy loop detected")]
    fn test_busy_loop_detection_fails() {
        init_test("test_busy_loop_detection_fails");
        let logger = TestLogger::new(TestLogLevel::Trace);

        // Log too many empty polls
        for _ in 0..10 {
            logger.log(TestEvent::ReactorPoll {
                timeout: None,
                events_returned: 0,
                duration: Duration::from_micros(10),
            });
        }

        // This should fail (10 > 5)
        logger.assert_no_busy_loop(5);
    }

    #[test]
    fn test_task_completion_check() {
        init_test("test_task_completion_check");
        let logger = TestLogger::new(TestLogLevel::Trace);

        logger.log(TestEvent::TaskSpawn {
            task_id: 1,
            name: None,
        });
        logger.log(TestEvent::TaskComplete {
            task_id: 1,
            outcome: "ok",
        });

        // Should pass
        logger.assert_all_tasks_completed();
        crate::test_complete!("test_task_completion_check");
    }

    #[test]
    #[should_panic(expected = "Task leak detected")]
    fn test_task_completion_check_fails() {
        init_test("test_task_completion_check_fails");
        let logger = TestLogger::new(TestLogLevel::Trace);

        logger.log(TestEvent::TaskSpawn {
            task_id: 1,
            name: None,
        });
        // No completion event

        logger.assert_all_tasks_completed();
    }

    #[test]
    fn test_macros() {
        init_test("test_macros");
        let logger = TestLogger::new(TestLogLevel::Debug);

        test_log!(logger, "test", "Message with arg: {}", 42);
        test_error!(logger, "io", "Error message");
        test_warn!(logger, "perf", "Warning message");

        let count = logger.event_count();
        crate::assert_with_log!(count == 3, "event_count", 3, count);
        crate::test_complete!("test_macros");
    }

    #[test]
    fn test_interest_display() {
        init_test("test_interest_display");
        let readable = format!("{}", Interest::READABLE);
        crate::assert_with_log!(readable == "R", "readable display", "R", readable);
        let writable = format!("{}", Interest::WRITABLE);
        crate::assert_with_log!(writable == "W", "writable display", "W", writable);
        let both = format!("{}", Interest::BOTH);
        crate::assert_with_log!(both == "RW", "both display", "RW", both);
        crate::test_complete!("test_interest_display");
    }

    #[test]
    fn test_event_display() {
        init_test("test_event_display");
        let event = TestEvent::TaskSpawn {
            task_id: 42,
            name: Some("worker".into()),
        };
        let rendered = format!("{event}");
        let has_task = rendered.contains("task=42");
        crate::assert_with_log!(has_task, "rendered task id", true, has_task);
        let has_worker = rendered.contains("worker");
        crate::assert_with_log!(has_worker, "rendered worker name", true, has_worker);
        crate::test_complete!("test_event_display");
    }

    // ====================================================================
    // TestHarness tests
    // ====================================================================

    #[test]
    fn test_harness_basic_flow() {
        init_test("test_harness_basic_flow");
        let mut harness = TestHarness::new("basic_flow");

        harness.enter_phase("setup");
        harness.assert_true("always true", true);
        harness.exit_phase();

        harness.enter_phase("exercise");
        harness.assert_eq("equality", &42, &42);
        harness.exit_phase();

        let summary = harness.finish();
        assert_eq!(summary.test_name, "basic_flow");
        assert!(summary.passed);
        assert_eq!(summary.total_assertions, 2);
        assert_eq!(summary.passed_assertions, 2);
        assert_eq!(summary.failed_assertions, 0);
        crate::test_complete!("test_harness_basic_flow");
    }

    #[test]
    fn test_harness_nested_phases() {
        init_test("test_harness_nested_phases");
        let mut harness = TestHarness::new("nested");

        harness.enter_phase("outer");
        harness.enter_phase("inner");
        assert_eq!(harness.current_phase_path(), "outer > inner");
        harness.exit_phase();
        harness.exit_phase();

        let summary = harness.finish();
        assert!(summary.passed);
        assert_eq!(summary.phases.len(), 1); // one root
        crate::test_complete!("test_harness_nested_phases");
    }

    #[test]
    fn test_harness_failed_assertion_recorded() {
        init_test("test_harness_failed_assertion_recorded");
        let mut harness = TestHarness::new("fail_test");

        harness.enter_phase("check");
        // Don't panic, just record
        let passed = harness.assert_eq("mismatch", &1, &2);
        assert!(!passed);
        harness.exit_phase();

        let summary = harness.finish();
        assert!(!summary.passed);
        assert_eq!(summary.failed_assertions, 1);
        crate::test_complete!("test_harness_failed_assertion_recorded");
    }

    #[test]
    fn test_harness_json_serialization() {
        init_test("test_harness_json_serialization");
        let mut harness = TestHarness::new("json_test");
        harness.assert_true("ok", true);
        let json = harness.finish_json();
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid json");
        assert_eq!(parsed["test_name"], "json_test");
        assert_eq!(parsed["passed"], true);
        crate::test_complete!("test_harness_json_serialization");
    }

    #[test]
    fn test_report_aggregator() {
        init_test("test_report_aggregator");
        let mut agg = TestReportAggregator::new();

        // Test 1: passing
        let mut h1 = TestHarness::new("test_a");
        h1.enter_phase("setup");
        h1.assert_true("ok", true);
        h1.exit_phase();
        agg.add(h1.finish());

        // Test 2: failing
        let mut h2 = TestHarness::new("test_b");
        h2.enter_phase("check");
        h2.assert_eq("bad", &1, &2);
        h2.exit_phase();
        agg.add(h2.finish());

        let report = agg.report();
        assert_eq!(report.total_tests, 2);
        assert_eq!(report.passed_tests, 1);
        assert_eq!(report.failed_tests, 1);
        assert_eq!(report.total_assertions, 2);
        assert_eq!(report.passed_assertions, 1);
        assert_eq!(report.coverage_matrix.len(), 2);
        assert_eq!(report.coverage_matrix[0].phases_exercised, vec!["setup"]);
        assert_eq!(report.coverage_matrix[1].phases_exercised, vec!["check"]);

        // Verify JSON round-trip
        let json = agg.report_json();
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid json");
        assert_eq!(parsed["total_tests"], 2);
        crate::test_complete!("test_report_aggregator");
    }

    #[test]
    fn test_harness_macros() {
        init_test("test_harness_macros");
        let mut harness = TestHarness::new("macro_test");
        harness_phase!(harness, "setup");
        harness_assert!(harness, "truthy", true);
        harness_assert_eq!(harness, "equal", 5, 5);
        harness_phase_exit!(harness);
        let summary = harness.finish();
        assert!(summary.passed);
        assert_eq!(summary.total_assertions, 2);
        crate::test_complete!("test_harness_macros");
    }

    #[test]
    fn test_assert_eq_log_macro_evaluates_operands_once_on_failure() {
        init_test("test_assert_eq_log_macro_evaluates_operands_once_on_failure");
        let logger = TestLogger::new(TestLogLevel::Info);
        let left_calls = Arc::new(AtomicUsize::new(0));
        let right_calls = Arc::new(AtomicUsize::new(0));
        let left_counter = Arc::clone(&left_calls);
        let right_counter = Arc::clone(&right_calls);

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            assert_eq_log!(
                logger,
                {
                    left_counter.fetch_add(1, Ordering::Relaxed);
                    1
                },
                {
                    right_counter.fetch_add(1, Ordering::Relaxed);
                    2
                }
            );
        }));

        assert!(result.is_err());
        assert_eq!(left_calls.load(Ordering::Relaxed), 1);
        assert_eq!(right_calls.load(Ordering::Relaxed), 1);
        crate::test_complete!("test_assert_eq_log_macro_evaluates_operands_once_on_failure");
    }

    #[test]
    fn test_harness_assert_eq_macro_evaluates_operands_once_on_failure() {
        init_test("test_harness_assert_eq_macro_evaluates_operands_once_on_failure");
        let expected_calls = Arc::new(AtomicUsize::new(0));
        let actual_calls = Arc::new(AtomicUsize::new(0));
        let expected_counter = Arc::clone(&expected_calls);
        let actual_counter = Arc::clone(&actual_calls);

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut harness = TestHarness::new("harness_macro_eval_once");
            harness_phase!(harness, "setup");
            harness_assert_eq!(
                harness,
                "mismatch",
                {
                    expected_counter.fetch_add(1, Ordering::Relaxed);
                    10
                },
                {
                    actual_counter.fetch_add(1, Ordering::Relaxed);
                    11
                }
            );
        }));

        assert!(result.is_err());
        assert_eq!(expected_calls.load(Ordering::Relaxed), 1);
        assert_eq!(actual_calls.load(Ordering::Relaxed), 1);
        crate::test_complete!("test_harness_assert_eq_macro_evaluates_operands_once_on_failure");
    }

    // ====================================================================
    // TestContext tests
    // ====================================================================

    #[test]
    fn test_context_creation() {
        init_test("test_context_creation");
        let ctx = TestContext::new("ctx_test", 0xCAFE)
            .with_subsystem("scheduler")
            .with_invariant("no_leaks");

        assert_eq!(ctx.test_id, "ctx_test");
        assert_eq!(ctx.seed, 0xCAFE);
        assert_eq!(ctx.subsystem.as_deref(), Some("scheduler"));
        assert_eq!(ctx.invariant.as_deref(), Some("no_leaks"));
        crate::test_complete!("test_context_creation");
    }

    #[test]
    fn test_context_display() {
        init_test("test_context_display");
        let ctx = TestContext::new("disp_test", 42).with_subsystem("raptorq");
        let rendered = format!("{ctx}");
        assert!(rendered.contains("test_id=disp_test"));
        assert!(rendered.contains("seed=0x2A"));
        assert!(rendered.contains("subsystem=raptorq"));
        crate::test_complete!("test_context_display");
    }

    #[test]
    fn test_context_serialization() {
        init_test("test_context_serialization");
        let ctx = TestContext::new("ser_test", 0xDEAD)
            .with_subsystem("obligation")
            .with_invariant("committed_or_aborted");

        let json = serde_json::to_string(&ctx).expect("serialize");
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("parse");
        assert_eq!(parsed["test_id"], "ser_test");
        assert_eq!(parsed["seed"], 0xDEAD);
        assert_eq!(parsed["subsystem"], "obligation");
        assert_eq!(parsed["invariant"], "committed_or_aborted");
        crate::test_complete!("test_context_serialization");
    }

    #[test]
    fn test_harness_with_context() {
        init_test("test_harness_with_context");
        let ctx = TestContext::new("harness_ctx", 0xBEEF)
            .with_subsystem("cancellation")
            .with_invariant("losers_drained");

        let mut harness = TestHarness::with_context("ctx_harness", ctx);
        assert!(harness.context().is_some());
        assert_eq!(harness.context().unwrap().test_id, "harness_ctx");

        harness.enter_phase("verify");
        harness.assert_true("context present", harness.context().is_some());
        harness.exit_phase();

        let summary = harness.finish();
        assert!(summary.passed);
        assert!(summary.context.is_some());
        assert_eq!(summary.context.unwrap().seed, 0xBEEF);
        crate::test_complete!("test_harness_with_context");
    }

    #[test]
    fn test_harness_without_context() {
        init_test("test_harness_without_context");
        let harness = TestHarness::new("no_ctx");
        assert!(harness.context().is_none());

        let summary = harness.finish();
        assert!(summary.context.is_none());
        crate::test_complete!("test_harness_without_context");
    }

    #[test]
    fn test_structured_macros() {
        init_test("test_structured_macros");
        let ctx = TestContext::new("macro_ctx", 0x42)
            .with_subsystem("sync")
            .with_invariant("no_deadlock");

        // These should compile and not panic.
        test_structured!(ctx, "simple message");
        test_structured!(ctx, "with fields", count = 5);
        test_structured!(ctx, "multi fields", count = 5, label = "test");
        crate::test_complete!("test_structured_macros");
    }

    // ----------------------------------------------------------------
    // Seed derivation tests
    // ----------------------------------------------------------------

    #[test]
    fn test_seed_derivation_deterministic() {
        init_test("test_seed_derivation_deterministic");
        let root = 0xDEAD_BEEF;
        assert_eq!(
            derive_component_seed(root, "scheduler"),
            derive_component_seed(root, "scheduler")
        );
        assert_eq!(
            derive_scenario_seed(root, "cancel"),
            derive_scenario_seed(root, "cancel")
        );
        assert_eq!(derive_entropy_seed(root, 0), derive_entropy_seed(root, 0));
        crate::test_complete!("test_seed_derivation_deterministic");
    }

    #[test]
    fn test_seed_derivation_unique() {
        init_test("test_seed_derivation_unique");
        let root = 0xDEAD_BEEF;
        assert_ne!(
            derive_component_seed(root, "scheduler"),
            derive_component_seed(root, "io")
        );
        assert_ne!(
            derive_scenario_seed(root, "cancel"),
            derive_scenario_seed(root, "join")
        );
        assert_ne!(derive_entropy_seed(root, 0), derive_entropy_seed(root, 1));
        // Component and scenario with same name differ due to prefix.
        assert_ne!(
            derive_component_seed(root, "cancel"),
            derive_scenario_seed(root, "cancel")
        );
        crate::test_complete!("test_seed_derivation_unique");
    }

    #[test]
    fn test_seed_derivation_cross_platform_stability() {
        init_test("test_seed_derivation_cross_platform_stability");
        // Pinned value for regression: FNV-1a of 0xDEAD_BEEF + "scheduler".
        let root = 0xDEAD_BEEF;
        let expected = 13_888_874_950_133_950_416;
        assert_eq!(
            derive_component_seed(root, "scheduler"),
            expected,
            "seed derivation must be platform-stable"
        );
        crate::test_complete!("test_seed_derivation_cross_platform_stability");
    }

    #[test]
    fn test_context_seed_methods() {
        init_test("test_context_seed_methods");
        let ctx = TestContext::new("seed_test", 0xCAFE);
        assert_eq!(
            ctx.component_seed("io"),
            derive_component_seed(0xCAFE, "io")
        );
        assert_eq!(
            ctx.scenario_seed("cancel"),
            derive_scenario_seed(0xCAFE, "cancel")
        );
        assert_eq!(ctx.entropy_seed(5), derive_entropy_seed(0xCAFE, 5));
        crate::test_complete!("test_context_seed_methods");
    }

    #[test]
    fn test_context_from_live_dual_run_preserves_identity() {
        init_test("test_context_from_live_dual_run_preserves_identity");
        let identity = DualRunScenarioIdentity::phase1(
            "phase1.cancel.race.one_loser",
            "cancel.race",
            "cancel.race.v1",
            "winner completes, loser drains",
            0xCAFE,
        );
        let ctx = TestContext::from_live_dual_run(&identity);

        assert_eq!(ctx.test_id, "phase1.cancel.race.one_loser");
        assert_eq!(ctx.seed, 0xCAFE);
        assert_eq!(ctx.adapter.as_deref(), Some(LIVE_CURRENT_THREAD_ADAPTER));
        assert_eq!(ctx.surface_id(), Some("cancel.race"));
        assert_eq!(ctx.surface_contract_version(), Some("cancel.race.v1"));
        assert_eq!(ctx.seed_lineage_id(), Some("phase1.cancel.race.one_loser"));
        assert!(ctx.execution_instance_id().is_some());

        crate::test_complete!("test_context_from_live_dual_run_preserves_identity");
    }

    // ----------------------------------------------------------------
    // ReproManifest tests
    // ----------------------------------------------------------------

    #[test]
    fn test_repro_manifest_from_context() {
        init_test("test_repro_manifest_from_context");
        let ctx = TestContext::new("obligation_leak", 42)
            .with_subsystem("obligation")
            .with_invariant("committed_or_aborted");
        let manifest = ReproManifest::from_context(&ctx, false);
        assert_eq!(manifest.seed, 42);
        assert_eq!(manifest.scenario_id, "obligation_leak");
        assert_eq!(
            manifest.invariant_ids,
            vec!["committed_or_aborted".to_string()]
        );
        assert_eq!(manifest.subsystem.as_deref(), Some("obligation"));
        assert_eq!(manifest.failure_class, FAILURE_CLASS_ASSERTION_FAILURE);
        assert!(
            manifest
                .replay_command
                .contains("rch exec -- cargo test obligation_leak -- --nocapture"),
            "default replay command should be deterministic"
        );
        assert!(!manifest.trace_fingerprint.is_empty());
        assert!(!manifest.passed);
        crate::test_complete!("test_repro_manifest_from_context");
    }

    #[test]
    fn test_repro_manifest_helper_setters() {
        init_test("test_repro_manifest_helper_setters");
        let manifest = ReproManifest::new(0xBEEF, "helper_test", false)
            .with_entropy_seed(0xCAFE)
            .with_config_hash("cfg_hash")
            .with_trace_fingerprint("trace_fp")
            .with_input_digest("input_digest")
            .with_oracle_violations(["oracle_a", "oracle_b"])
            .with_subsystem("scheduler")
            .with_invariant("no_leaks")
            .with_invariant_ids(["quiescence", "no_leaks", "quiescence"])
            .with_replay_command(
                "ASUPERSYNC_SEED=0xBEEF rch exec -- cargo test helper_test -- --nocapture",
            )
            .with_failure_class("assertion_failure")
            .with_artifact_paths(["b.json", "a.json", "b.json"])
            .with_trace_file("traces/run.jsonl")
            .with_input_file("inputs/failing.json");

        assert_eq!(manifest.entropy_seed, Some(0xCAFE));
        assert_eq!(manifest.config_hash.as_deref(), Some("cfg_hash"));
        assert_eq!(manifest.trace_fingerprint, "trace_fp");
        assert_eq!(manifest.input_digest.as_deref(), Some("input_digest"));
        assert_eq!(manifest.oracle_violations.len(), 2);
        assert_eq!(manifest.subsystem.as_deref(), Some("scheduler"));
        assert_eq!(manifest.invariant.as_deref(), Some("no_leaks"));
        assert_eq!(
            manifest.invariant_ids,
            vec!["no_leaks".to_string(), "quiescence".to_string()]
        );
        assert_eq!(manifest.failure_class, "assertion_failure");
        assert!(
            manifest
                .replay_command
                .contains("rch exec -- cargo test helper_test -- --nocapture")
        );
        assert_eq!(
            manifest.artifact_paths,
            vec!["a.json".to_string(), "b.json".to_string()]
        );
        assert_eq!(manifest.trace_file.as_deref(), Some("traces/run.jsonl"));
        assert_eq!(manifest.input_file.as_deref(), Some("inputs/failing.json"));
        crate::test_complete!("test_repro_manifest_helper_setters");
    }

    #[test]
    fn test_repro_manifest_json_roundtrip() {
        init_test("test_repro_manifest_json_roundtrip");
        let mut manifest = ReproManifest::new(0xCAFE, "roundtrip_test", true);
        manifest.entropy_seed = Some(0xBEEF);
        manifest.config_hash = Some("abc123".to_string());
        let json = manifest.to_json().expect("serialize");
        let parsed: ReproManifest = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(parsed.seed, manifest.seed);
        assert_eq!(parsed.scenario_id, manifest.scenario_id);
        assert_eq!(parsed.entropy_seed, manifest.entropy_seed);
        assert_eq!(parsed.schema_version, ARTIFACT_SCHEMA_VERSION);
        crate::test_complete!("test_repro_manifest_json_roundtrip");
    }

    #[test]
    fn test_repro_manifest_optional_fields_omitted() {
        init_test("test_repro_manifest_optional_fields_omitted");
        let manifest = ReproManifest::new(0, "minimal_test", true);
        let json = manifest.to_json().expect("serialize");
        assert!(!json.contains("entropy_seed"));
        assert!(!json.contains("config_hash"));
        assert!(!json.contains("oracle_violations"));
        assert!(json.contains("\"invariant_ids\": []"));
        assert!(json.contains("\"artifact_paths\": []"));
        assert!(json.contains("\"failure_class\": \"passed\""));
        assert!(json.contains("\"replay_command\":"));
        assert!(json.contains("\"trace_fingerprint\":"));
        crate::test_complete!("test_repro_manifest_optional_fields_omitted");
    }

    #[test]
    fn test_replay_context_from_manifest() {
        init_test("test_replay_context_from_manifest");
        let mut manifest = ReproManifest::new(0xDEAD, "replay_scenario", false);
        manifest.subsystem = Some("scheduler".to_string());
        manifest.invariant = Some("quiescence".to_string());
        let ctx = replay_context_from_manifest(&manifest);
        assert_eq!(ctx.test_id, "replay_scenario");
        assert_eq!(ctx.seed, 0xDEAD);
        assert_eq!(ctx.subsystem.as_deref(), Some("scheduler"));
        crate::test_complete!("test_replay_context_from_manifest");
    }

    #[test]
    fn test_replay_context_from_manifest_restores_dual_run_metadata() {
        init_test("test_replay_context_from_manifest_restores_dual_run_metadata");
        let identity = DualRunScenarioIdentity::phase1(
            "phase1.cancel.race.one_loser",
            "cancel.race",
            "cancel.race.v1",
            "winner completes, loser drains",
            0xDEAD,
        );
        let ctx = TestContext::from_live_dual_run(&identity);
        let manifest = ReproManifest::from_context(&ctx, false);
        let replay_ctx = replay_context_from_manifest(&manifest);

        assert_eq!(
            replay_ctx.adapter.as_deref(),
            Some(LIVE_CURRENT_THREAD_ADAPTER)
        );
        assert_eq!(replay_ctx.surface_id(), Some("cancel.race"));
        assert_eq!(
            replay_ctx.surface_contract_version(),
            Some("cancel.race.v1")
        );
        assert_eq!(
            replay_ctx.seed_lineage_id(),
            Some("phase1.cancel.race.one_loser")
        );
        assert!(replay_ctx.execution_instance_id().is_some());

        crate::test_complete!("test_replay_context_from_manifest_restores_dual_run_metadata");
    }

    // ----------------------------------------------------------------
    // ----------------------------------------------------------------
    // Failure Triage Pipeline tests (bd-1ex7)
    // ----------------------------------------------------------------

    #[test]
    fn test_repro_manifest_env_snapshot() {
        init_test("test_repro_manifest_env_snapshot");
        let env = capture_test_env();
        for (key, _) in &env {
            crate::assert_with_log!(
                key.starts_with("ASUPERSYNC_") || key == "RUST_LOG",
                "env key filtered",
                "ASUPERSYNC_* or RUST_LOG",
                key
            );
        }
        let keys: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
        let mut sorted = keys.clone();
        sorted.sort_unstable();
        crate::assert_with_log!(keys == sorted, "env keys sorted", true, keys == sorted);
        crate::test_complete!("test_repro_manifest_env_snapshot");
    }

    #[test]
    fn test_repro_manifest_with_phases_and_failure_reason() {
        init_test("test_repro_manifest_with_phases_and_failure_reason");
        let manifest = ReproManifest::new(0xBEEF, "phase_test", false)
            .with_phases(vec![
                "setup".to_string(),
                "exercise".to_string(),
                "verify".to_string(),
            ])
            .with_failure_reason("assertion failed: expected 5, got 3");

        crate::assert_with_log!(
            manifest.phases_executed.len() == 3,
            "three phases",
            3,
            manifest.phases_executed.len()
        );
        crate::assert_with_log!(
            manifest.failure_reason.is_some(),
            "failure reason set",
            true,
            manifest.failure_reason.is_some()
        );
        crate::assert_with_log!(
            manifest.failure_class == FAILURE_CLASS_ASSERTION_FAILURE,
            "failure class set on failure reason",
            FAILURE_CLASS_ASSERTION_FAILURE,
            manifest.failure_class
        );

        let json = manifest.to_json().expect("serialize");
        let parsed: ReproManifest = serde_json::from_str(&json).expect("deserialize");
        crate::assert_with_log!(
            parsed.phases_executed == manifest.phases_executed,
            "phases roundtrip",
            manifest.phases_executed.len(),
            parsed.phases_executed.len()
        );
        crate::assert_with_log!(
            parsed.failure_reason == manifest.failure_reason,
            "failure_reason roundtrip",
            manifest.failure_reason,
            parsed.failure_reason
        );
        crate::test_complete!("test_repro_manifest_with_phases_and_failure_reason");
    }

    #[test]
    fn test_repro_manifest_contract_validation_v1() {
        init_test("test_repro_manifest_contract_validation_v1");
        let manifest = ReproManifest::new(0x1234, "contract_ok", false)
            .with_trace_fingerprint("fp_1234")
            .with_invariant_ids(["cancel_protocol", "no_obligation_leaks"])
            .with_replay_command(
                "ASUPERSYNC_SEED=0x1234 rch exec -- cargo test contract_ok -- --nocapture",
            )
            .with_failure_class(FAILURE_CLASS_ASSERTION_FAILURE)
            .with_artifact_paths([
                "target/test-artifacts/contract_ok/event_log.txt",
                "target/test-artifacts/contract_ok/repro_manifest.json",
            ]);

        crate::assert_with_log!(
            manifest.validate_contract_v1().is_ok(),
            "manifest satisfies v1 contract",
            true,
            manifest.validate_contract_v1().is_ok()
        );
        crate::test_complete!("test_repro_manifest_contract_validation_v1");
    }

    #[test]
    fn test_repro_manifest_contract_validation_rejects_unsorted_ids() {
        init_test("test_repro_manifest_contract_validation_rejects_unsorted_ids");
        let mut manifest = ReproManifest::new(0x9999, "contract_bad", false)
            .with_trace_fingerprint("fp_9999")
            .with_replay_command(
                "ASUPERSYNC_SEED=0x9999 rch exec -- cargo test contract_bad -- --nocapture",
            )
            .with_failure_class(FAILURE_CLASS_ASSERTION_FAILURE)
            .with_artifact_paths([
                "target/test-artifacts/contract_bad/repro_manifest.json",
                "target/test-artifacts/contract_bad/event_log.txt",
            ]);
        manifest.invariant_ids = vec!["z_last".to_string(), "a_first".to_string()];

        let err = manifest
            .validate_contract_v1()
            .expect_err("unsorted invariant_ids should fail");
        crate::assert_with_log!(
            err.contains("invariant_ids must be sorted"),
            "contract rejects unsorted invariant_ids",
            true,
            err
        );
        crate::test_complete!("test_repro_manifest_contract_validation_rejects_unsorted_ids");
    }

    #[test]
    fn test_repro_manifest_empty_new_fields_omitted() {
        init_test("test_repro_manifest_empty_new_fields_omitted");
        let manifest = ReproManifest::new(42, "minimal", true);
        let json = manifest.to_json().expect("serialize");
        crate::assert_with_log!(
            !json.contains("phases_executed"),
            "empty phases omitted",
            true,
            !json.contains("phases_executed")
        );
        crate::assert_with_log!(
            !json.contains("env_snapshot"),
            "empty env omitted",
            true,
            !json.contains("env_snapshot")
        );
        crate::assert_with_log!(
            !json.contains("failure_reason"),
            "null failure_reason omitted",
            true,
            !json.contains("failure_reason")
        );
        crate::test_complete!("test_repro_manifest_empty_new_fields_omitted");
    }

    #[test]
    fn test_harness_repro_manifest_on_failure() {
        init_test("test_harness_repro_manifest_on_failure");
        let ctx = TestContext::new("harness_failure_test", 0xF00D)
            .with_subsystem("scheduler")
            .with_invariant("quiescence");
        let mut harness = TestHarness::with_context("harness_failure_test", ctx);

        harness.enter_phase("setup");
        harness.assert_true("always passes", true);
        harness.exit_phase();

        harness.enter_phase("exercise");
        harness.record_assertion("value check", false, "10", "5");
        harness.exit_phase();

        let manifest = harness.repro_manifest(false);
        crate::assert_with_log!(
            manifest.seed == 0xF00D,
            "seed from context",
            0xF00Du64,
            manifest.seed
        );
        crate::assert_with_log!(
            manifest.subsystem.as_deref() == Some("scheduler"),
            "subsystem from context",
            Some("scheduler"),
            manifest.subsystem.as_deref()
        );
        crate::assert_with_log!(
            manifest.phases_executed.len() == 2,
            "two phases captured",
            2,
            manifest.phases_executed.len()
        );
        crate::assert_with_log!(
            manifest.failure_reason.is_some(),
            "failure reason populated",
            true,
            manifest.failure_reason.is_some()
        );
        crate::assert_with_log!(
            manifest.failure_class == FAILURE_CLASS_ASSERTION_FAILURE,
            "failure class populated",
            FAILURE_CLASS_ASSERTION_FAILURE,
            manifest.failure_class
        );
        crate::assert_with_log!(
            manifest
                .replay_command
                .contains("rch exec -- cargo test harness_failure_test -- --nocapture"),
            "replay command populated",
            true,
            manifest
                .replay_command
                .contains("rch exec -- cargo test harness_failure_test -- --nocapture")
        );
        crate::test_complete!("test_harness_repro_manifest_on_failure");
    }

    #[test]
    fn test_harness_finish_auto_generates_manifest_on_failure() {
        init_test("test_harness_finish_auto_generates_manifest_on_failure");
        let _guard = crate::test_utils::env_lock();
        let tmp = std::env::temp_dir().join("asupersync_harness_manifest_test");
        let _ = std::fs::remove_dir_all(&tmp);

        // SAFETY: tests serialize env access with test_utils::env_lock.
        unsafe { std::env::set_var("ASUPERSYNC_TEST_ARTIFACTS_DIR", tmp.display().to_string()) };
        let ctx = TestContext::new("auto_manifest", 0xCAFE).with_subsystem("time");
        let mut harness = TestHarness::with_context("auto_manifest", ctx);

        harness.enter_phase("setup");
        harness.exit_phase();
        harness.enter_phase("verify");
        harness.record_assertion("fail_check", false, "true", "false");
        harness.exit_phase();

        let summary = harness.finish();

        let has_manifest = summary
            .failure_artifacts
            .iter()
            .any(|a| a.contains("repro_manifest.json"));
        crate::assert_with_log!(
            has_manifest,
            "repro_manifest.json in artifacts",
            true,
            has_manifest
        );

        if let Some(manifest_path) = summary
            .failure_artifacts
            .iter()
            .find(|a| a.contains("repro_manifest.json"))
        {
            let loaded = load_repro_manifest(std::path::Path::new(manifest_path))
                .expect("load auto-generated manifest");
            crate::assert_with_log!(
                loaded.seed == 0xCAFE,
                "manifest seed correct",
                0xCAFEu64,
                loaded.seed
            );
            crate::assert_with_log!(
                !loaded.passed,
                "manifest shows failure",
                false,
                loaded.passed
            );
            crate::assert_with_log!(
                loaded.phases_executed.len() == 2,
                "phases captured in manifest",
                2,
                loaded.phases_executed.len()
            );
            crate::assert_with_log!(
                loaded.failure_class == FAILURE_CLASS_ASSERTION_FAILURE,
                "failure class captured in manifest",
                FAILURE_CLASS_ASSERTION_FAILURE,
                loaded.failure_class
            );
        }

        // SAFETY: tests serialize env access with test_utils::env_lock.
        unsafe { std::env::remove_var("ASUPERSYNC_TEST_ARTIFACTS_DIR") };
        let _ = std::fs::remove_dir_all(&tmp);
        crate::test_complete!("test_harness_finish_auto_generates_manifest_on_failure");
    }

    #[test]
    fn test_capture_replay_manifest_roundtrip() {
        init_test("test_capture_replay_manifest_roundtrip");
        let ctx = TestContext::new("cancel_drain", 0xDEAD_CAFE)
            .with_subsystem("obligation")
            .with_invariant("no_leaks");
        let mut harness = TestHarness::with_context("cancel_drain", ctx);

        harness.enter_phase("setup_regions");
        harness.assert_true("region created", true);
        harness.exit_phase();
        harness.enter_phase("cancel_and_drain");
        harness.record_assertion("leak check", false, "0 leaks", "2 leaks");
        harness.exit_phase();

        let manifest = harness.repro_manifest(false);

        let tmp = std::env::temp_dir().join("asupersync_replay_roundtrip");
        let path = manifest.write_to_dir(&tmp).expect("write manifest");

        let loaded = load_repro_manifest(&path).expect("load manifest");
        let replay_ctx = replay_context_from_manifest(&loaded);

        crate::assert_with_log!(
            replay_ctx.seed == 0xDEAD_CAFE,
            "replay seed matches",
            0xDEAD_CAFEu64,
            replay_ctx.seed
        );
        crate::assert_with_log!(
            replay_ctx.test_id == "cancel_drain",
            "replay test_id matches",
            "cancel_drain",
            replay_ctx.test_id
        );
        crate::assert_with_log!(
            loaded.phases_executed.len() == 2,
            "phases preserved on disk",
            2,
            loaded.phases_executed.len()
        );
        crate::assert_with_log!(
            loaded.failure_reason.is_some(),
            "failure reason preserved on disk",
            true,
            loaded.failure_reason.is_some()
        );
        crate::assert_with_log!(
            loaded.validate_contract_v1().is_ok(),
            "manifest remains v1 contract-valid after disk roundtrip",
            true,
            loaded.validate_contract_v1().is_ok()
        );

        let _ = std::fs::remove_dir_all(tmp.join("cancel_drain"));
        crate::test_complete!("test_capture_replay_manifest_roundtrip");
    }

    // E2E Environment Orchestration tests
    // ----------------------------------------------------------------

    #[test]
    fn test_port_allocator_allocates_unique_ports() {
        init_test("test_port_allocator_allocates_unique_ports");
        let mut alloc = PortAllocator::new();
        let p1 = alloc.allocate("http").expect("allocate http");
        let p2 = alloc.allocate("ws").expect("allocate ws");
        let p3 = alloc.allocate("grpc").expect("allocate grpc");
        assert_ne!(p1, p2, "ports must be unique");
        assert_ne!(p2, p3, "ports must be unique");
        assert_ne!(p1, p3, "ports must be unique");
        assert!(p1 > 0);
        assert_eq!(alloc.count(), 3);
        crate::test_complete!("test_port_allocator_allocates_unique_ports");
    }

    #[test]
    fn test_port_allocator_lookup_by_label() {
        init_test("test_port_allocator_lookup_by_label");
        let mut alloc = PortAllocator::new();
        let port = alloc.allocate("my_service").expect("allocate");
        assert_eq!(alloc.port_for("my_service"), Some(port));
        assert_eq!(alloc.port_for("nonexistent"), None);
        crate::test_complete!("test_port_allocator_lookup_by_label");
    }

    #[test]
    fn test_port_allocator_allocate_n() {
        init_test("test_port_allocator_allocate_n");
        let mut alloc = PortAllocator::new();
        let ports = alloc.allocate_n("worker", 4).expect("allocate_n");
        assert_eq!(ports.len(), 4);
        let mut sorted = ports;
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), 4, "all ports must be unique");
        assert!(alloc.port_for("worker_0").is_some());
        assert!(alloc.port_for("worker_3").is_some());
        crate::test_complete!("test_port_allocator_allocate_n");
    }

    #[test]
    fn test_noop_fixture_service_lifecycle() {
        init_test("test_noop_fixture_service_lifecycle");
        let mut svc = NoOpFixtureService::new("test_echo");
        assert_eq!(svc.name(), "test_echo");
        assert!(!svc.is_healthy());
        svc.start().expect("start");
        assert!(svc.is_healthy());
        svc.stop().expect("stop");
        assert!(!svc.is_healthy());
        crate::test_complete!("test_noop_fixture_service_lifecycle");
    }

    #[test]
    fn test_environment_metadata_fields() {
        init_test("test_environment_metadata_fields");
        let ctx = TestContext::new("env_meta_test", 0xBEEF);
        let mut env = TestEnvironment::new(ctx);
        let _ = env.allocate_port("http").expect("allocate");
        env.register_service(Box::new(NoOpFixtureService::new("echo_svc")));
        let meta = env.metadata();
        assert_eq!(meta.test_id, "env_meta_test");
        assert_eq!(meta.seed, 0xBEEF);
        assert_eq!(meta.ports.len(), 1);
        assert_eq!(meta.services.len(), 1);
        crate::test_complete!("test_environment_metadata_fields");
    }

    #[test]
    fn test_environment_metadata_json_roundtrip() {
        init_test("test_environment_metadata_json_roundtrip");
        let ctx = TestContext::new("json_meta", 42);
        let env = TestEnvironment::new(ctx);
        let meta = env.metadata();
        let json = meta.to_json().expect("serialize");
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("parse");
        assert_eq!(parsed["test_id"], "json_meta");
        assert_eq!(parsed["seed"], 42);
        crate::test_complete!("test_environment_metadata_json_roundtrip");
    }

    #[test]
    fn test_environment_service_lifecycle() {
        init_test("test_environment_service_lifecycle");
        let ctx = TestContext::new("svc_lifecycle", 1);
        let mut env = TestEnvironment::new(ctx);
        env.register_service(Box::new(NoOpFixtureService::new("svc_a")));
        env.register_service(Box::new(NoOpFixtureService::new("svc_b")));
        let health = env.health_check();
        assert!(!health[0].1);
        assert!(!health[1].1);
        env.start_all_services().expect("start all");
        let health = env.health_check();
        assert!(health[0].1);
        assert!(health[1].1);
        env.teardown();
        let health = env.health_check();
        assert!(!health[0].1);
        assert!(!health[1].1);
        crate::test_complete!("test_environment_service_lifecycle");
    }

    #[test]
    fn test_environment_port_isolation() {
        init_test("test_environment_port_isolation");
        let mut env_a = TestEnvironment::new(TestContext::new("env_a", 1));
        let mut env_b = TestEnvironment::new(TestContext::new("env_b", 2));
        let port_a = env_a.allocate_port("http").expect("allocate a");
        let port_b = env_b.allocate_port("http").expect("allocate b");
        assert_ne!(
            port_a, port_b,
            "concurrent environments must get distinct ports"
        );
        crate::test_complete!("test_environment_port_isolation");
    }

    #[test]
    fn test_environment_teardown_idempotent() {
        init_test("test_environment_teardown_idempotent");
        let mut env = TestEnvironment::new(TestContext::new("idempotent", 0));
        env.register_service(Box::new(NoOpFixtureService::new("svc")));
        env.start_all_services().expect("start");
        env.teardown();
        env.teardown();
        env.teardown();
        crate::test_complete!("test_environment_teardown_idempotent");
    }

    #[test]
    fn test_environment_on_teardown_callbacks() {
        init_test("test_environment_on_teardown_callbacks");
        let counter = Arc::new(AtomicUsize::new(0));
        let c1 = counter.clone();
        let c2 = counter.clone();
        let mut env = TestEnvironment::new(TestContext::new("callbacks", 0));
        env.on_teardown(move || {
            c1.fetch_add(1, Ordering::SeqCst);
        });
        env.on_teardown(move || {
            c2.fetch_add(10, Ordering::SeqCst);
        });
        env.teardown();
        assert_eq!(counter.load(Ordering::SeqCst), 11, "both callbacks ran");
        crate::test_complete!("test_environment_on_teardown_callbacks");
    }

    #[test]
    fn test_environment_metadata_write_artifact() {
        init_test("test_environment_metadata_write_artifact");
        let mut env = TestEnvironment::new(TestContext::new("artifact_write", 0xABCD));
        let _ = env.allocate_port("tcp").expect("allocate");
        let tmp = std::env::temp_dir().join("asupersync_env_meta_test");
        let meta = env.metadata();
        let path = meta.write_to_dir(&tmp).expect("write metadata");
        let content = std::fs::read_to_string(&path).expect("read");
        let parsed: serde_json::Value = serde_json::from_str(&content).expect("parse");
        assert_eq!(parsed["test_id"], "artifact_write");
        assert_eq!(parsed["seed"], 0xABCD);
        let _ = std::fs::remove_dir_all(tmp.join("artifact_write"));
        crate::test_complete!("test_environment_metadata_write_artifact");
    }

    // =========================================================================
    // Tests for concrete fixture services (bd-76y5)
    // =========================================================================

    #[test]
    fn test_wait_until_healthy_immediate() {
        init_test("test_wait_until_healthy_immediate");
        let mut svc = NoOpFixtureService::new("fast_svc");
        svc.start().expect("start");
        let elapsed = wait_until_healthy(&svc, Duration::from_secs(1)).expect("healthy");
        assert!(elapsed < Duration::from_millis(100));
        crate::test_complete!("test_wait_until_healthy_immediate");
    }

    #[test]
    fn test_wait_until_healthy_timeout() {
        init_test("test_wait_until_healthy_timeout");
        let svc = NoOpFixtureService::new("never_starts");
        // Not started, so is_healthy() is always false.
        let result = wait_until_healthy(&svc, Duration::from_millis(200));
        assert!(result.is_err(), "should timeout");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not healthy"),
            "error should mention health: {err_msg}"
        );
        crate::test_complete!("test_wait_until_healthy_timeout");
    }

    #[test]
    fn test_temp_dir_fixture_lifecycle() {
        init_test("test_temp_dir_fixture_lifecycle");
        let mut fixture = TempDirFixture::new("scratch");
        assert!(!fixture.is_healthy());
        assert!(fixture.path().is_none());

        fixture.start().expect("start");
        assert!(fixture.is_healthy());
        let path = fixture.path().expect("path exists").to_owned();
        assert!(path.is_dir());
        assert!(
            path.to_string_lossy().contains("asupersync-scratch-"),
            "prefix should match: {path:?}"
        );

        fixture.stop().expect("stop");
        assert!(!fixture.is_healthy());
        assert!(!path.is_dir(), "temp dir should be cleaned up");

        crate::test_complete!("test_temp_dir_fixture_lifecycle");
    }

    #[test]
    fn test_temp_dir_fixture_custom_prefix() {
        init_test("test_temp_dir_fixture_custom_prefix");
        let mut fixture = TempDirFixture::new("custom").with_prefix("myprefix-");
        fixture.start().expect("start");
        let path = fixture.path().expect("path exists");
        assert!(
            path.to_string_lossy().contains("myprefix-"),
            "custom prefix should appear: {path:?}"
        );
        crate::test_complete!("test_temp_dir_fixture_custom_prefix");
    }

    #[test]
    fn test_in_process_service_lifecycle() {
        init_test("test_in_process_service_lifecycle");
        let running = Arc::new(AtomicBool::new(false));
        let mut svc = InProcessService::new(
            "echo",
            running.clone(),
            |state: &mut Arc<AtomicBool>| {
                state.store(true, Ordering::SeqCst);
                Ok(())
            },
            |state: &mut Arc<AtomicBool>| {
                state.store(false, Ordering::SeqCst);
                Ok(())
            },
            |state: &Arc<AtomicBool>| state.load(Ordering::SeqCst),
        );

        assert_eq!(svc.name(), "echo");
        assert!(!svc.is_healthy());

        svc.start().expect("start");
        assert!(svc.is_healthy());
        assert!(running.load(Ordering::SeqCst));

        svc.stop().expect("stop");
        assert!(!svc.is_healthy());
        assert!(!running.load(Ordering::SeqCst));

        crate::test_complete!("test_in_process_service_lifecycle");
    }

    #[test]
    fn test_docker_fixture_service_name_and_container() {
        init_test("test_docker_fixture_service_name_and_container");
        let svc = DockerFixtureService::new("redis", "redis:7-alpine")
            .with_port_map(16379, 6379)
            .with_env("REDIS_PASSWORD", "test")
            .with_health_cmd(vec!["redis-cli", "ping"]);

        assert_eq!(svc.name(), "redis");
        assert!(
            svc.container_name().starts_with("asupersync-test-redis-"),
            "container name format: {}",
            svc.container_name()
        );
        assert!(!svc.is_healthy(), "not started yet");
        crate::test_complete!("test_docker_fixture_service_name_and_container");
    }

    #[test]
    fn test_environment_with_temp_dir_fixture() {
        init_test("test_environment_with_temp_dir_fixture");
        let ctx = TestContext::new("env_tempdir", 0x1234);
        let mut env = TestEnvironment::new(ctx);

        let mut tmp = TempDirFixture::new("workdir");
        tmp.start().expect("start");
        assert!(tmp.is_healthy());
        let dir_path = tmp.path().expect("path").to_owned();

        env.register_service(Box::new(tmp));
        let meta = env.metadata();
        assert_eq!(meta.services.len(), 1);
        assert_eq!(meta.services[0], "workdir");

        env.teardown();
        // After teardown the temp dir should be cleaned up.
        assert!(!dir_path.is_dir(), "temp dir cleaned up after env teardown");
        crate::test_complete!("test_environment_with_temp_dir_fixture");
    }

    #[test]
    fn test_environment_with_in_process_service() {
        init_test("test_environment_with_in_process_service");
        let flag = Arc::new(AtomicBool::new(false));
        let svc = InProcessService::new(
            "mock_http",
            flag.clone(),
            |s: &mut Arc<AtomicBool>| {
                s.store(true, Ordering::SeqCst);
                Ok(())
            },
            |s: &mut Arc<AtomicBool>| {
                s.store(false, Ordering::SeqCst);
                Ok(())
            },
            |s: &Arc<AtomicBool>| s.load(Ordering::SeqCst),
        );

        let ctx = TestContext::new("env_inproc", 42);
        let mut env = TestEnvironment::new(ctx);
        env.register_service(Box::new(svc));
        env.start_all_services().expect("start all");

        let health = env.health_check();
        assert!(health[0].1, "in-process service should be healthy");
        assert!(flag.load(Ordering::SeqCst));

        env.teardown();
        assert!(!flag.load(Ordering::SeqCst), "stopped after teardown");
        crate::test_complete!("test_environment_with_in_process_service");
    }
}