wasm-rquickjs-cli 0.5.3

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
pub mod js_subtest_parser;
pub mod test_server;

use crate::common::WasmSource::Precompiled;
use anyhow::anyhow;
use bytes::Buf;
use camino::{Utf8Path, Utf8PathBuf};
use camino_tempfile::{NamedUtf8TempFile, Utf8TempDir};
use futures::FutureExt;
use heck::ToSnakeCase;
use http_body::{Body as HttpBody, Frame, SizeHint};
use http_body_util::BodyExt;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::io::{Read, Write};
use std::pin::Pin;
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::task::{Context, Poll};
use std::thread;
use std::time::{Duration, Instant, SystemTime};
use tokio::time::timeout;
use wac_graph::types::{Package, SubtypeChecker};
use wac_graph::{CompositionGraph, EncodeOptions, PackageId, PlugError};
use wasm_rquickjs::{EmbeddingMode, JsModuleSpec, generate_wrapper_crate};
use wasmtime::component::{
    Component, Func, HasSelf, Instance, Linker, Resource, ResourceAny, ResourceTable, ResourceType,
    Val,
};
use wasmtime::{Engine, Store, StoreContextMut, UpdateDeadline};
use wasmtime_wasi::cli::OutputFile;
use wasmtime_wasi::{FsPerms, WasiCtx, WasiCtxView, WasiView};
use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpView};

pub mod ws_mock_p3 {
    wasmtime::component::bindgen!({
        world: "golem-websocket",
        path: "crates/golem-websocket/wit-p3",
        imports: { default: async | trappable },
        with: {
            "golem:websocket/client.websocket-connection": super::WsMockConnection,
        },
    });
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsSentMessage {
    Text(String),
    Binary(Vec<u8>),
    Close(Option<u16>, Option<String>),
}

pub struct WsMockConnection;

impl ws_mock_p3::golem::websocket::client::Host for Host {}

impl ws_mock_p3::golem::websocket::client::HostWebsocketConnection for Host {
    async fn connect(
        &mut self,
        _url: String,
        _headers: Option<Vec<(String, String)>>,
        reconstruction_policy: Option<ws_mock_p3::golem::websocket::client::ReconstructionPolicy>,
    ) -> wasmtime::Result<
        Result<Resource<WsMockConnection>, ws_mock_p3::golem::websocket::client::Error>,
    > {
        assert!(reconstruction_policy.is_none());
        Ok(Ok(self.table.lock().unwrap().push(WsMockConnection)?))
    }

    async fn send(
        &mut self,
        _self_: Resource<WsMockConnection>,
        message: ws_mock_p3::golem::websocket::client::Message,
    ) -> wasmtime::Result<Result<(), ws_mock_p3::golem::websocket::client::Error>> {
        let message = match message {
            ws_mock_p3::golem::websocket::client::Message::Text(value) => {
                WsSentMessage::Text(value)
            }
            ws_mock_p3::golem::websocket::client::Message::Binary(value) => {
                WsSentMessage::Binary(value)
            }
        };
        self.ws_sent.lock().unwrap().push(message);
        Ok(Ok(()))
    }

    async fn close(
        &mut self,
        _self_: Resource<WsMockConnection>,
        code: Option<u16>,
        reason: Option<String>,
    ) -> wasmtime::Result<Result<(), ws_mock_p3::golem::websocket::client::Error>> {
        self.ws_sent
            .lock()
            .unwrap()
            .push(WsSentMessage::Close(code, reason));
        Ok(Ok(()))
    }

    async fn drop(&mut self, rep: Resource<WsMockConnection>) -> wasmtime::Result<()> {
        self.table.lock().unwrap().delete(rep)?;
        Ok(())
    }
}

impl ws_mock_p3::golem::websocket::client::HostWebsocketConnectionWithStore<Host>
    for HasSelf<Host>
{
    async fn receive(
        _store: &wasmtime::component::Accessor<Host, Self>,
        _self_: Resource<WsMockConnection>,
    ) -> wasmtime::Result<
        Result<
            ws_mock_p3::golem::websocket::client::Message,
            ws_mock_p3::golem::websocket::client::Error,
        >,
    > {
        // Keep the host import pending for one turn so receive/close ownership and
        // cancellation paths are exercised instead of always completing inline.
        tokio::task::yield_now().await;
        Ok(Err(ws_mock_p3::golem::websocket::client::Error::Closed(
            None,
        )))
    }

    async fn receive_with_timeout(
        _store: &wasmtime::component::Accessor<Host, Self>,
        _self_: Resource<WsMockConnection>,
        _timeout_ms: u64,
    ) -> wasmtime::Result<
        Result<
            Option<ws_mock_p3::golem::websocket::client::Message>,
            ws_mock_p3::golem::websocket::client::Error,
        >,
    > {
        Ok(Err(ws_mock_p3::golem::websocket::client::Error::Closed(
            None,
        )))
    }
}

/// Default timeout for node_compat tests (in seconds).
pub const DEFAULT_NODE_COMPAT_TEST_TIMEOUT_SECS: u64 = 120;

/// Build generated test components against the bridge sources in this checkout.
pub fn use_local_golem_websocket(root: &Utf8Path) -> anyhow::Result<()> {
    let manifest = root.join("Cargo.toml");
    let contents = fs::read_to_string(&manifest)?;
    let remote_patch = concat!(
        "golem-websocket = { git = \"https://github.com/golemcloud/wasm-rquickjs\", ",
        "branch = \"gol804-websocket-current-generator\" }"
    );
    let local_crate = Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("crates/golem-websocket");
    let local_patch = format!("golem-websocket = {{ path = \"{local_crate}\" }}");
    let updated = contents.replace(remote_patch, &local_patch);
    anyhow::ensure!(
        updated != contents,
        "generated Cargo.toml did not contain the expected golem-websocket branch patch"
    );
    fs::write(manifest, updated)?;
    // The copied skeleton lockfile still identifies the bridge by its Git source.
    let mut status = Command::new("cargo")
        .args(["update", "--offline", "-p", "golem-websocket"])
        .current_dir(root)
        .status()?;
    if !status.success() {
        status = Command::new("cargo")
            .args(["update", "-p", "golem-websocket"])
            .current_dir(root)
            .status()?;
    }
    anyhow::ensure!(
        status.success(),
        "failed to lock the local golem-websocket bridge"
    );
    Ok(())
}

const TEST_ARTIFACT_CACHE_ENV: &str = "WASM_RQUICKJS_TEST_ARTIFACT_CACHE";
const TEST_COMPONENT_PROFILE_ENV: &str = "WASM_RQUICKJS_TEST_COMPONENT_PROFILE";
const TEST_DROP_CACHE_ENV: &str = "WASM_RQUICKJS_TEST_DROP_CACHE";
const TEST_LOCKED_BUILDS_ENV: &str = "WASM_RQUICKJS_TEST_LOCKED_BUILDS";
const TEST_PREPARED_COMPONENT_CACHE_ENV: &str = "WASM_RQUICKJS_TEST_PREPARED_COMPONENT_CACHE";
const TEST_PRECOMPILE_COMPONENT_ENV: &str = "WASM_RQUICKJS_TEST_PRECOMPILE_COMPONENT";
const TEST_UNOPTIMIZED_ENV: &str = "WASM_RQUICKJS_TEST_UNOPTIMIZED";
const TEST_WASMTIME_CACHE_ENV: &str = "WASM_RQUICKJS_TEST_WASMTIME_CACHE";

/// In-memory buffer holding host-side tracing output so it can be attached to test failure
/// messages. On CI only the failure message itself is visible (in the ctrf report and the
/// GitHub annotations); anything the test runner captures — including output written via
/// `with_test_writer` — never appears in the logs. So the tracing output must travel inside
/// the error itself, like the guest stdout/stderr already does.
///
/// The buffer is shared by all tests in the process and capped, keeping the most recent output.
static HOST_TRACE: Mutex<Vec<u8>> = Mutex::new(Vec::new());
const HOST_TRACE_CAP: usize = 256 * 1024;
static NEXT_HTTP_TRACE_INVOCATION: AtomicUsize = AtomicUsize::new(1);
static NEXT_HTTP_TRACE_REQUEST: AtomicUsize = AtomicUsize::new(1);
static NEXT_HTTP_TRACE_CONNECTION: AtomicUsize = AtomicUsize::new(1);
static TEST_SERVER_HTTP_TRACE: OnceLock<HttpLifecycleTrace> = OnceLock::new();
const HTTP_LIFECYCLE_CAP: usize = 256;
const HTTP_LIFECYCLE_SEQUENCE_MASK: u64 = 0x00ff_ffff;
const HTTP_LIFECYCLE_SEQUENCE_HALF: u64 = 0x0080_0000;

#[repr(u8)]
#[derive(Clone, Copy)]
enum HttpLifecyclePhase {
    Submit = 1,
    Target = 2,
    RequestFirstData = 3,
    RequestFirstTrailers = 4,
    RequestEof = 5,
    RequestError = 6,
    RequestDrop = 7,
    ResponseHead = 8,
    ResponseFirstData = 9,
    ResponseFirstTrailers = 10,
    ResponseEof = 11,
    ResponseError = 12,
    ResponseDrop = 13,
    SendError = 14,
    ResponseIoOk = 15,
    ResponseIoError = 16,
    ServerArrival = 17,
    ServerRequestFirstData = 18,
    ServerRequestEof = 19,
    ServerRequestError = 20,
    ServerRequestDrop = 21,
    ServerResponseHead = 22,
    ServerResponseFirstData = 23,
    ServerResponseEof = 24,
    ServerResponseError = 25,
    ServerResponseDrop = 26,
    TargetPath = 27,
    ServerPort = 28,
    ServerConnectionAccept = 29,
    ServerRequestConnection = 30,
    ServerConnectionFirstRead = 31,
    ServerConnectionReadEof = 32,
    ServerConnectionReadError = 33,
    ServerConnectionFirstWrite = 34,
    ServerConnectionWriteError = 35,
    ServerConnectionFlushError = 36,
    ServerConnectionShutdown = 37,
    ServerConnectionShutdownError = 38,
    ServerConnectionDrop = 39,
    ServerResponseWriteAfterFrame = 40,
    ServerResponseWriteError = 41,
    ServerResponsePendingAtDrop = 42,
    ServerResponseCorrelationOverlap = 43,
    ServerResponseBodyExpectedBytes = 44,
    ServerResponseBodyExpectedUnknown = 45,
    ServerResponseBodyPolledBytes = 46,
    ServerResponseWritePartial = 47,
    ServerResponseWriteBoundaryBytes = 48,
    ServerResponseFlushBytes = 49,
    ServerResponseTerminalBytes = 50,
    ServerResponseByteCountOverflow = 51,
    ServerConnectionFlushPending = 52,
    ServerConnectionFlushOk = 53,
    ServerConnectionShutdownPending = 54,
    ServerResponseCorrelationBoundary = 55,
}

impl HttpLifecyclePhase {
    fn label(value: u8) -> &'static str {
        match value {
            1 => "submit",
            2 => "target-port",
            3 => "request-first-data",
            4 => "request-first-trailers",
            5 => "request-eof",
            6 => "request-error",
            7 => "request-drop-before-terminal",
            8 => "response-head",
            9 => "response-first-data",
            10 => "response-first-trailers",
            11 => "response-eof",
            12 => "response-error",
            13 => "response-drop-before-terminal",
            14 => "send-error",
            15 => "response-io-ok",
            16 => "response-io-error",
            17 => "server-arrival",
            18 => "server-request-first-data",
            19 => "server-request-eof",
            20 => "server-request-error",
            21 => "server-request-drop-before-terminal",
            22 => "server-response-head",
            23 => "server-response-first-data",
            24 => "server-response-eof",
            25 => "server-response-error",
            26 => "server-response-drop-before-terminal",
            27 => "target-path-hash",
            28 => "server-port",
            29 => "server-connection-accept",
            30 => "server-request-connection",
            31 => "server-connection-first-read",
            32 => "server-connection-read-eof",
            33 => "server-connection-read-error",
            34 => "server-connection-first-write",
            35 => "server-connection-write-error",
            36 => "server-connection-flush-error",
            37 => "server-connection-shutdown",
            38 => "server-connection-shutdown-error",
            39 => "server-connection-drop",
            40 => "server-response-write-after-frame",
            41 => "server-response-write-error",
            42 => "server-response-pending-at-drop",
            43 => "server-response-correlation-overlap",
            44 => "server-response-body-expected-bytes",
            45 => "server-response-body-expected-unknown",
            46 => "server-response-body-polled-bytes",
            47 => "server-response-write-partial",
            48 => "server-response-write-boundary-bytes",
            49 => "server-response-flush-bytes",
            50 => "server-response-terminal-bytes",
            51 => "server-response-byte-count-overflow",
            52 => "server-connection-flush-pending",
            53 => "server-connection-flush-ok",
            54 => "server-connection-shutdown-pending",
            55 => "server-response-correlation-boundary",
            _ => "unknown",
        }
    }
}

const HTTP_BYTE_COUNT_EXPECTED: u16 = 1;
const HTTP_BYTE_COUNT_POLLED: u16 = 2;
const HTTP_BYTE_COUNT_WRITE: u16 = 3;

fn record_http_byte_count(
    trace: &HttpLifecycleTrace,
    request: usize,
    phase: HttpLifecyclePhase,
    count: u64,
    overflow_kind: u16,
) {
    if count > u64::from(u16::MAX) {
        trace.record(
            request,
            HttpLifecyclePhase::ServerResponseByteCountOverflow,
            overflow_kind,
        );
    }
    trace.record(request, phase, count.min(u64::from(u16::MAX)) as u16);
}

struct HttpLifecycleJournal {
    next_event: AtomicUsize,
    slots: [std::sync::atomic::AtomicU64; HTTP_LIFECYCLE_CAP],
}

impl HttpLifecycleJournal {
    fn new() -> Self {
        Self {
            next_event: AtomicUsize::new(1),
            slots: std::array::from_fn(|_| std::sync::atomic::AtomicU64::new(0)),
        }
    }

    fn record(&self, request: usize, phase: HttpLifecyclePhase, detail: u16) {
        let sequence = self.next_event.fetch_add(1, Ordering::Relaxed);
        self.publish(sequence, request, phase, detail);
    }

    fn publish(&self, sequence: usize, request: usize, phase: HttpLifecyclePhase, detail: u16) {
        let encoded_sequence = sequence as u64 & HTTP_LIFECYCLE_SEQUENCE_MASK;
        let packed = (encoded_sequence << 40)
            | ((request as u64 & 0xffff) << 24)
            | ((phase as u64) << 16)
            | u64::from(detail);
        let slot = &self.slots[sequence % HTTP_LIFECYCLE_CAP];
        let mut current = slot.load(Ordering::Acquire);
        loop {
            let current_sequence = current >> 40;
            if current != 0 {
                let advance =
                    encoded_sequence.wrapping_sub(current_sequence) & HTTP_LIFECYCLE_SEQUENCE_MASK;
                if advance == 0 || advance >= HTTP_LIFECYCLE_SEQUENCE_HALF {
                    return;
                }
            }
            match slot.compare_exchange_weak(current, packed, Ordering::Release, Ordering::Acquire)
            {
                Ok(_) => return,
                Err(observed) => current = observed,
            }
        }
    }

    fn snapshot(&self, invocation: usize) -> String {
        let newest_full_sequence = self.next_event.load(Ordering::Acquire).saturating_sub(1);
        let newest_encoded_sequence = newest_full_sequence as u64 & HTTP_LIFECYCLE_SEQUENCE_MASK;
        let mut events = self
            .slots
            .iter()
            .map(|slot| slot.load(Ordering::Acquire))
            .filter(|event| *event != 0)
            .collect::<Vec<_>>();
        events.retain(|event| {
            let sequence = event >> 40;
            let age = newest_encoded_sequence.wrapping_sub(sequence) & HTTP_LIFECYCLE_SEQUENCE_MASK;
            age < HTTP_LIFECYCLE_SEQUENCE_HALF
        });
        events.sort_unstable_by_key(|event| {
            let sequence = event >> 40;
            std::cmp::Reverse(
                newest_encoded_sequence.wrapping_sub(sequence) & HTTP_LIFECYCLE_SEQUENCE_MASK,
            )
        });
        let mut result = format!("invocation={invocation}\n");
        for event in events {
            let encoded_sequence = event >> 40;
            let age = newest_encoded_sequence.wrapping_sub(encoded_sequence)
                & HTTP_LIFECYCLE_SEQUENCE_MASK;
            let sequence = newest_full_sequence.saturating_sub(age as usize);
            let request = (event >> 24) & 0xffff;
            let phase = ((event >> 16) & 0xff) as u8;
            let detail = event & 0xffff;
            use std::fmt::Write as _;
            let _ = writeln!(
                result,
                "seq={sequence} request={request} phase={} detail={detail}",
                HttpLifecyclePhase::label(phase)
            );
        }
        result
    }
}

/// Per-component correlation state for the test harness' outgoing HTTP lifecycle trace.
///
/// The trace is intentionally implemented in the host rather than the embedded skeleton: it is
/// test-only, covers both P2 and P3, and can observe the Wasmtime transport boundary without
/// changing a generated component. Events use a fixed atomic journal, so the hot path has no
/// locks, allocation, clocks, or output; the journal is formatted only after an invocation fails.
#[derive(Clone)]
struct HttpLifecycleTrace {
    invocation: usize,
    journal: Arc<HttpLifecycleJournal>,
}

impl HttpLifecycleTrace {
    fn new() -> Self {
        Self {
            invocation: NEXT_HTTP_TRACE_INVOCATION.fetch_add(1, Ordering::Relaxed),
            journal: Arc::new(HttpLifecycleJournal::new()),
        }
    }

    fn next_request(&self) -> usize {
        NEXT_HTTP_TRACE_REQUEST.fetch_add(1, Ordering::Relaxed)
    }

    fn record(&self, request: usize, phase: HttpLifecyclePhase, detail: u16) {
        self.journal.record(request, phase, detail);
    }

    fn record_submit(&self, request: usize, method: &http::Method, uri: &http::Uri) {
        let method = if method == http::Method::GET {
            1
        } else if method == http::Method::POST {
            2
        } else if method == http::Method::PUT {
            3
        } else if method == http::Method::DELETE {
            4
        } else if method == http::Method::HEAD {
            5
        } else {
            0
        };
        self.record(request, HttpLifecyclePhase::Submit, method);
        self.record(
            request,
            HttpLifecyclePhase::Target,
            uri.port_u16().unwrap_or_default(),
        );
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        uri.path_and_query().hash(&mut hasher);
        self.record(
            request,
            HttpLifecyclePhase::TargetPath,
            (hasher.finish() & 0xffff) as u16,
        );
    }

    fn snapshot(&self) -> String {
        self.journal.snapshot(self.invocation)
    }
}

fn test_server_http_trace() -> &'static HttpLifecycleTrace {
    TEST_SERVER_HTTP_TRACE.get_or_init(HttpLifecycleTrace::new)
}

fn record_http_submit<B>(trace: &HttpLifecycleTrace, request: &http::Request<B>) -> usize {
    let request_id = trace.next_request();
    trace.record_submit(request_id, request.method(), request.uri());
    request_id
}

fn next_test_server_http_request() -> usize {
    test_server_http_trace().next_request()
}

fn record_test_server_arrival(request_id: usize, port: u16, uri: &http::Uri) {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    uri.path_and_query().hash(&mut hasher);
    test_server_http_trace().record(
        request_id,
        HttpLifecyclePhase::ServerArrival,
        (hasher.finish() & 0xffff) as u16,
    );
    test_server_http_trace().record(request_id, HttpLifecyclePhase::ServerPort, port);
}

fn record_test_server_response_head(request_id: usize, status: http::StatusCode) {
    test_server_http_trace().record(
        request_id,
        HttpLifecyclePhase::ServerResponseHead,
        status.as_u16(),
    );
}

fn record_test_server_connection(
    request_id: usize,
    connection: Option<&TracedTestServerConnection>,
) {
    if let Some(connection) = connection {
        connection.state.trace.record(
            request_id,
            HttpLifecyclePhase::ServerRequestConnection,
            connection.state.connection,
        );
    }
}

pub(crate) fn traced_test_server_listener(
    listener: tokio::net::TcpListener,
) -> TracedTestServerListener {
    TracedTestServerListener {
        listener,
        trace: test_server_http_trace().clone(),
    }
}

pub(crate) struct TracedTestServerListener {
    listener: tokio::net::TcpListener,
    trace: HttpLifecycleTrace,
}

impl axum::serve::Listener for TracedTestServerListener {
    type Io = TracedTestServerIo<tokio::net::TcpStream>;
    type Addr = std::net::SocketAddr;

    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
        let (stream, peer) =
            <tokio::net::TcpListener as axum::serve::Listener>::accept(&mut self.listener).await;
        let connection = (NEXT_HTTP_TRACE_CONNECTION.fetch_add(1, Ordering::Relaxed)
            % usize::from(u16::MAX))
            + 1;
        let state = Arc::new(HttpConnectionState::new(
            self.trace.clone(),
            connection as u16,
        ));
        self.trace.record(
            connection,
            HttpLifecyclePhase::ServerConnectionAccept,
            peer.port(),
        );
        (TracedTestServerIo::new(stream, state), peer)
    }

    fn local_addr(&self) -> std::io::Result<Self::Addr> {
        self.listener.local_addr()
    }
}

#[derive(Clone)]
pub(crate) struct TracedTestServerConnection {
    state: Arc<HttpConnectionState>,
}

impl
    axum::extract::connect_info::Connected<
        axum::serve::IncomingStream<'_, TracedTestServerListener>,
    > for TracedTestServerConnection
{
    fn connect_info(target: axum::serve::IncomingStream<'_, TracedTestServerListener>) -> Self {
        Self {
            state: target.io().state.clone(),
        }
    }
}

struct HttpConnectionState {
    trace: HttpLifecycleTrace,
    connection: u16,
    pending_response: AtomicUsize,
}

impl HttpConnectionState {
    fn new(trace: HttpLifecycleTrace, connection: u16) -> Self {
        Self {
            trace,
            connection,
            pending_response: AtomicUsize::new(0),
        }
    }

    fn arm_response(&self, request_id: usize) {
        if let Err(pending_request) = self.pending_response.compare_exchange(
            0,
            request_id,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            self.trace.record(
                request_id,
                HttpLifecyclePhase::ServerResponseCorrelationOverlap,
                pending_request.min(usize::from(u16::MAX)) as u16,
            );
        }
    }

    fn take_pending_response(&self) -> Option<usize> {
        match self.pending_response.swap(0, Ordering::AcqRel) {
            0 => None,
            request_id => Some(request_id),
        }
    }
}

struct ActiveResponseWrite {
    request_id: usize,
    accepted_bytes: u64,
}

pub(crate) struct TracedTestServerIo<T> {
    inner: T,
    state: Arc<HttpConnectionState>,
    saw_read: bool,
    saw_write: bool,
    read_terminal: bool,
    write_terminal: bool,
    active_response: Option<ActiveResponseWrite>,
    flush_pending: bool,
    shutdown_pending: bool,
}

impl<T> TracedTestServerIo<T> {
    fn new(inner: T, state: Arc<HttpConnectionState>) -> Self {
        Self {
            inner,
            state,
            saw_read: false,
            saw_write: false,
            read_terminal: false,
            write_terminal: false,
            active_response: None,
            flush_pending: false,
            shutdown_pending: false,
        }
    }

    fn record_connection(&self, phase: HttpLifecyclePhase, detail: u16) {
        self.state
            .trace
            .record(usize::from(self.state.connection), phase, detail);
    }

    fn record_response_bytes(&self, request_id: usize, phase: HttpLifecyclePhase, bytes: u64) {
        record_http_byte_count(
            &self.state.trace,
            request_id,
            phase,
            bytes,
            HTTP_BYTE_COUNT_WRITE,
        );
    }

    fn activate_pending_response(&mut self, first_accepted_bytes: Option<usize>) -> Option<usize> {
        let pending = self.state.take_pending_response();
        if let Some(request_id) = pending {
            match self.active_response.take() {
                Some(active) if active.request_id != request_id => {
                    self.record_response_bytes(
                        active.request_id,
                        HttpLifecyclePhase::ServerResponseWriteBoundaryBytes,
                        active.accepted_bytes,
                    );
                    self.state.trace.record(
                        active.request_id,
                        HttpLifecyclePhase::ServerResponseCorrelationBoundary,
                        request_id.min(usize::from(u16::MAX)) as u16,
                    );
                }
                Some(active) => {
                    self.active_response = Some(active);
                    return Some(request_id);
                }
                None => {}
            }
            if let Some(first_accepted_bytes) = first_accepted_bytes {
                self.record_response_bytes(
                    request_id,
                    HttpLifecyclePhase::ServerResponseWriteAfterFrame,
                    first_accepted_bytes as u64,
                );
            }
            self.active_response = Some(ActiveResponseWrite {
                request_id,
                accepted_bytes: 0,
            });
        }
        self.active_response
            .as_ref()
            .map(|active| active.request_id)
    }

    fn snapshot_active_response(&mut self, phase: HttpLifecyclePhase) {
        if let Some(active) = self.active_response.take() {
            self.record_response_bytes(active.request_id, phase, active.accepted_bytes);
        }
    }

    fn record_pending_response(&self, phase: HttpLifecyclePhase) {
        if let Some(request_id) = self.state.take_pending_response() {
            self.state
                .trace
                .record(request_id, phase, self.state.connection);
        }
    }

    fn record_write_success(&mut self, offered: usize, accepted: usize) {
        if !self.saw_write {
            self.saw_write = true;
            self.record_connection(
                HttpLifecyclePhase::ServerConnectionFirstWrite,
                accepted.min(usize::from(u16::MAX)) as u16,
            );
        }
        if let Some(request_id) = self.activate_pending_response(Some(accepted)) {
            if let Some(active) = &mut self.active_response {
                active.accepted_bytes = active.accepted_bytes.saturating_add(accepted as u64);
            }
            if accepted < offered {
                self.record_response_bytes(
                    request_id,
                    HttpLifecyclePhase::ServerResponseWritePartial,
                    offered.saturating_sub(accepted) as u64,
                );
            }
        }
    }

    fn record_write_error(&mut self, error: &std::io::Error) {
        self.write_terminal = true;
        self.activate_pending_response(None);
        if let Some(request_id) = self
            .active_response
            .as_ref()
            .map(|active| active.request_id)
        {
            self.state.trace.record(
                request_id,
                HttpLifecyclePhase::ServerResponseWriteError,
                self.state.connection,
            );
        }
        self.snapshot_active_response(HttpLifecyclePhase::ServerResponseTerminalBytes);
        self.record_connection(
            HttpLifecyclePhase::ServerConnectionWriteError,
            error.raw_os_error().unwrap_or_default() as u16,
        );
    }
}

impl<T: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for TracedTestServerIo<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buffer: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        let filled_before = buffer.filled().len();
        match Pin::new(&mut self.inner).poll_read(cx, buffer) {
            Poll::Ready(Ok(())) => {
                let bytes = buffer.filled().len().saturating_sub(filled_before);
                if bytes != 0 && !self.saw_read {
                    self.saw_read = true;
                    self.record_connection(
                        HttpLifecyclePhase::ServerConnectionFirstRead,
                        bytes.min(usize::from(u16::MAX)) as u16,
                    );
                } else if bytes == 0 && !self.read_terminal {
                    self.read_terminal = true;
                    self.record_connection(HttpLifecyclePhase::ServerConnectionReadEof, 0);
                }
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(error)) => {
                self.read_terminal = true;
                self.record_connection(
                    HttpLifecyclePhase::ServerConnectionReadError,
                    error.raw_os_error().unwrap_or_default() as u16,
                );
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl<T: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for TracedTestServerIo<T> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buffer: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        match Pin::new(&mut self.inner).poll_write(cx, buffer) {
            Poll::Ready(Ok(bytes)) => {
                self.record_write_success(buffer.len(), bytes);
                Poll::Ready(Ok(bytes))
            }
            Poll::Ready(Err(error)) => {
                self.record_write_error(&error);
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buffers: &[std::io::IoSlice<'_>],
    ) -> Poll<std::io::Result<usize>> {
        match Pin::new(&mut self.inner).poll_write_vectored(cx, buffers) {
            Poll::Ready(Ok(bytes)) => {
                let offered = buffers
                    .iter()
                    .fold(0usize, |total, buffer| total.saturating_add(buffer.len()));
                self.record_write_success(offered, bytes);
                Poll::Ready(Ok(bytes))
            }
            Poll::Ready(Err(error)) => {
                self.record_write_error(&error);
                Poll::Ready(Err(error))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn is_write_vectored(&self) -> bool {
        self.inner.is_write_vectored()
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match Pin::new(&mut self.inner).poll_flush(cx) {
            Poll::Ready(Ok(())) => {
                self.flush_pending = false;
                self.snapshot_active_response(HttpLifecyclePhase::ServerResponseFlushBytes);
                self.record_connection(HttpLifecyclePhase::ServerConnectionFlushOk, 0);
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(error)) => {
                self.flush_pending = false;
                self.write_terminal = true;
                if let Some(request_id) = self
                    .active_response
                    .as_ref()
                    .map(|active| active.request_id)
                {
                    self.state.trace.record(
                        request_id,
                        HttpLifecyclePhase::ServerResponseWriteError,
                        self.state.connection,
                    );
                }
                self.snapshot_active_response(HttpLifecyclePhase::ServerResponseTerminalBytes);
                self.record_pending_response(HttpLifecyclePhase::ServerResponseWriteError);
                self.record_connection(
                    HttpLifecyclePhase::ServerConnectionFlushError,
                    error.raw_os_error().unwrap_or_default() as u16,
                );
                Poll::Ready(Err(error))
            }
            Poll::Pending => {
                if !self.flush_pending {
                    self.flush_pending = true;
                    self.record_connection(HttpLifecyclePhase::ServerConnectionFlushPending, 0);
                }
                Poll::Pending
            }
        }
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match Pin::new(&mut self.inner).poll_shutdown(cx) {
            Poll::Ready(Ok(())) => {
                self.shutdown_pending = false;
                if !self.write_terminal {
                    self.write_terminal = true;
                    self.snapshot_active_response(HttpLifecyclePhase::ServerResponseTerminalBytes);
                    self.record_pending_response(HttpLifecyclePhase::ServerResponsePendingAtDrop);
                    self.record_connection(HttpLifecyclePhase::ServerConnectionShutdown, 0);
                }
                Poll::Ready(Ok(()))
            }
            Poll::Ready(Err(error)) => {
                self.shutdown_pending = false;
                self.write_terminal = true;
                if let Some(request_id) = self
                    .active_response
                    .as_ref()
                    .map(|active| active.request_id)
                {
                    self.state.trace.record(
                        request_id,
                        HttpLifecyclePhase::ServerResponseWriteError,
                        self.state.connection,
                    );
                }
                self.snapshot_active_response(HttpLifecyclePhase::ServerResponseTerminalBytes);
                self.record_pending_response(HttpLifecyclePhase::ServerResponseWriteError);
                self.record_connection(
                    HttpLifecyclePhase::ServerConnectionShutdownError,
                    error.raw_os_error().unwrap_or_default() as u16,
                );
                Poll::Ready(Err(error))
            }
            Poll::Pending => {
                if !self.shutdown_pending {
                    self.shutdown_pending = true;
                    self.record_connection(HttpLifecyclePhase::ServerConnectionShutdownPending, 0);
                }
                Poll::Pending
            }
        }
    }
}

impl<T> Drop for TracedTestServerIo<T> {
    fn drop(&mut self) {
        self.snapshot_active_response(HttpLifecyclePhase::ServerResponseTerminalBytes);
        self.record_pending_response(HttpLifecyclePhase::ServerResponsePendingAtDrop);
        let detail = u16::from(self.saw_read)
            | (u16::from(self.saw_write) << 1)
            | (u16::from(self.read_terminal) << 2)
            | (u16::from(self.write_terminal) << 3);
        self.record_connection(HttpLifecyclePhase::ServerConnectionDrop, detail);
    }
}

fn traced_test_server_body<B: HttpBody>(
    body: B,
    request_id: usize,
    side: &'static str,
) -> TracedHttpBody<B> {
    TracedHttpBody::new(
        body,
        test_server_http_trace().clone(),
        request_id,
        side,
        None,
    )
}

fn traced_test_server_response_body<B: HttpBody>(
    body: B,
    request_id: usize,
    connection: Option<TracedTestServerConnection>,
) -> TracedHttpBody<B> {
    TracedHttpBody::new(
        body,
        test_server_http_trace().clone(),
        request_id,
        "server-response",
        connection.map(|connection| connection.state),
    )
}

/// A transparent body observer. It never polls ahead or adds an await: every host poll is
/// delegated exactly once while frame byte totals and the terminal outcome are recorded.
struct TracedHttpBody<B: HttpBody> {
    inner: Pin<Box<B>>,
    trace: HttpLifecycleTrace,
    request: usize,
    side: &'static str,
    server_connection: Option<Arc<HttpConnectionState>>,
    saw_frame: bool,
    terminal: bool,
    expected_body_bytes: Option<u64>,
    polled_body_bytes: u64,
    body_bytes_recorded: bool,
}

impl<B: HttpBody> TracedHttpBody<B> {
    fn new(
        inner: B,
        trace: HttpLifecycleTrace,
        request: usize,
        side: &'static str,
        server_connection: Option<Arc<HttpConnectionState>>,
    ) -> Self {
        let is_end_stream = inner.is_end_stream();
        let expected_body_bytes = (side == "server-response")
            .then(|| inner.size_hint().exact())
            .flatten();
        let mut body = Self {
            inner: Box::pin(inner),
            trace,
            request,
            side,
            server_connection,
            saw_frame: false,
            terminal: false,
            expected_body_bytes,
            polled_body_bytes: 0,
            body_bytes_recorded: false,
        };
        if side == "server-response" {
            if let Some(expected) = body.expected_body_bytes {
                record_http_byte_count(
                    &body.trace,
                    request,
                    HttpLifecyclePhase::ServerResponseBodyExpectedBytes,
                    expected,
                    HTTP_BYTE_COUNT_EXPECTED,
                );
            } else {
                body.trace.record(
                    request,
                    HttpLifecyclePhase::ServerResponseBodyExpectedUnknown,
                    0,
                );
            }
        }
        if is_end_stream {
            body.record_terminal("eof");
        }
        body
    }

    fn event(&self, outcome: &'static str) {
        let phase = match (self.side, outcome) {
            ("request", "first-data") => HttpLifecyclePhase::RequestFirstData,
            ("request", "first-trailers") => HttpLifecyclePhase::RequestFirstTrailers,
            ("request", "eof") => HttpLifecyclePhase::RequestEof,
            ("request", "error") => HttpLifecyclePhase::RequestError,
            ("request", "drop-before-terminal") => HttpLifecyclePhase::RequestDrop,
            ("response", "first-data") => HttpLifecyclePhase::ResponseFirstData,
            ("response", "first-trailers") => HttpLifecyclePhase::ResponseFirstTrailers,
            ("response", "eof") => HttpLifecyclePhase::ResponseEof,
            ("response", "error") => HttpLifecyclePhase::ResponseError,
            ("response", "drop-before-terminal") => HttpLifecyclePhase::ResponseDrop,
            ("server-request", "first-data") => HttpLifecyclePhase::ServerRequestFirstData,
            ("server-request", "eof") => HttpLifecyclePhase::ServerRequestEof,
            ("server-request", "error") => HttpLifecyclePhase::ServerRequestError,
            ("server-request", "drop-before-terminal") => HttpLifecyclePhase::ServerRequestDrop,
            ("server-response", "first-data") => HttpLifecyclePhase::ServerResponseFirstData,
            ("server-response", "eof") => HttpLifecyclePhase::ServerResponseEof,
            ("server-response", "error") => HttpLifecyclePhase::ServerResponseError,
            ("server-response", "drop-before-terminal") => HttpLifecyclePhase::ServerResponseDrop,
            _ => return,
        };
        self.trace.record(self.request, phase, 0);
    }

    fn record_body_bytes(&mut self) {
        if self.side == "server-response" && !self.body_bytes_recorded {
            self.body_bytes_recorded = true;
            record_http_byte_count(
                &self.trace,
                self.request,
                HttpLifecyclePhase::ServerResponseBodyPolledBytes,
                self.polled_body_bytes,
                HTTP_BYTE_COUNT_POLLED,
            );
        }
    }

    fn record_terminal(&mut self, outcome: &'static str) {
        if !self.terminal {
            self.terminal = true;
            self.event(outcome);
        }
        self.record_body_bytes();
    }
}

impl<B: HttpBody> HttpBody for TracedHttpBody<B> {
    type Data = B::Data;
    type Error = B::Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let this = self.get_mut();
        match this.inner.as_mut().poll_frame(cx) {
            Poll::Ready(Some(Ok(frame))) => {
                if let Some(data) = frame.data_ref() {
                    this.polled_body_bytes = this
                        .polled_body_bytes
                        .saturating_add(data.remaining() as u64);
                }
                if !this.saw_frame {
                    this.saw_frame = true;
                    let outcome = if frame.is_data() {
                        "first-data"
                    } else {
                        "first-trailers"
                    };
                    this.event(outcome);
                    if outcome == "first-data"
                        && let Some(connection) = &this.server_connection
                    {
                        connection.arm_response(this.request);
                    }
                }
                if this.inner.as_ref().is_end_stream() {
                    this.record_terminal("eof");
                }
                Poll::Ready(Some(Ok(frame)))
            }
            Poll::Ready(Some(Err(error))) => {
                this.record_terminal("error");
                Poll::Ready(Some(Err(error)))
            }
            Poll::Ready(None) => {
                this.record_terminal("eof");
                Poll::Ready(None)
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn is_end_stream(&self) -> bool {
        self.inner.as_ref().is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.inner.as_ref().size_hint()
    }
}

impl<B: HttpBody> Drop for TracedHttpBody<B> {
    fn drop(&mut self) {
        if !self.terminal && !self.inner.as_ref().is_end_stream() {
            self.event("drop-before-terminal");
        }
        self.record_body_bytes();
    }
}

#[derive(Clone)]
struct HttpTraceHooks(HttpLifecycleTrace);

impl wasmtime_wasi_http::WasiHttpHooks for HttpTraceHooks {
    fn send_request(
        &mut self,
        request: http::Request<wasmtime_wasi_http::WasiBody>,
        options: Option<wasmtime_wasi_http::RequestOptions>,
        response_processing: Box<dyn Future<Output = Result<(), wasmtime_wasi_http::Error>> + Send>,
    ) -> Box<
        dyn Future<
                Output = wasmtime_wasi_http::Result<(
                    http::Response<wasmtime_wasi_http::WasiBody>,
                    Box<dyn Future<Output = Result<(), wasmtime_wasi_http::Error>> + Send>,
                )>,
            > + Send,
    > {
        // Match Wasmtime's default hook: response-processing is currently not wired into the
        // default client. Keep that ownership behavior unchanged while tracing the returned I/O
        // future, which is the transport's actual connection lifetime signal.
        drop(response_processing);

        let trace = self.0.clone();
        let request_id = record_http_submit(&trace, &request);
        let (parts, body) = request.into_parts();
        let request = http::Request::from_parts(
            parts,
            TracedHttpBody::new(body, trace.clone(), request_id, "request", None).boxed_unsync(),
        );

        Box::new(async move {
            let result = wasmtime_wasi_http::default_send_request(request, options).await;
            let (response, io) = match result {
                Ok(value) => value,
                Err(error) => {
                    trace.record(request_id, HttpLifecyclePhase::SendError, 0);
                    return Err(error);
                }
            };
            trace.record(
                request_id,
                HttpLifecyclePhase::ResponseHead,
                response.status().as_u16(),
            );
            let (parts, body) = response.into_parts();
            let response = http::Response::from_parts(
                parts,
                TracedHttpBody::new(body, trace.clone(), request_id, "response", None)
                    .boxed_unsync(),
            );
            let io_trace = trace.clone();
            let io = Box::new(async move {
                let result = io.await;
                io_trace.record(
                    request_id,
                    if result.is_ok() {
                        HttpLifecyclePhase::ResponseIoOk
                    } else {
                        HttpLifecyclePhase::ResponseIoError
                    },
                    0,
                );
                result
            }) as Box<dyn Future<Output = Result<_, _>> + Send>;
            Ok((response, io))
        })
    }
}

#[derive(Clone, Copy)]
struct HostTraceWriter;

impl std::io::Write for HostTraceWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let mut trace = HOST_TRACE.lock().unwrap();
        trace.extend_from_slice(buf);
        let len = trace.len();
        if len > HOST_TRACE_CAP {
            trace.drain(..len - HOST_TRACE_CAP);
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl tracing_subscriber::fmt::MakeWriter<'_> for HostTraceWriter {
    type Writer = HostTraceWriter;

    fn make_writer(&self) -> Self::Writer {
        *self
    }
}

/// Returns the host-side tracing output captured so far (see [`init_tracing`]).
pub fn host_trace() -> String {
    String::from_utf8_lossy(&HOST_TRACE.lock().unwrap()).into_owned()
}

/// Installs a global tracing subscriber (once per process) so host-side `tracing` diagnostics
/// are visible in test output. Most importantly, `wasmtime-wasi-http` flattens the underlying
/// hyper error of a failed outgoing request into `ErrorCode::HttpProtocolError` and only reports
/// the real error via `tracing::warn!` — without a subscriber that information is lost, which
/// makes intermittent CI-only fetch failures undiagnosable.
///
/// The output is collected into [`HOST_TRACE`] (not the test runner's capture buffer) so that
/// failing tests can attach it to their error message, which is the only output channel visible
/// in the CI failure reports.
///
/// The filter can be overridden with `RUST_LOG`; by default only `wasmtime-wasi-http` warnings
/// are shown to keep output noise low.
pub fn init_tracing() {
    use std::sync::Once;
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        let filter = tracing_subscriber::EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("wasmtime_wasi_http=warn"));
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_writer(HostTraceWriter)
            .with_ansi(false)
            .try_init();
    });
}

/// Strip JSONC comments (// and /* */) while respecting string literals.
pub fn strip_jsonc_comments(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let chars: Vec<char> = input.chars().collect();
    let len = chars.len();
    let mut i = 0;

    while i < len {
        if chars[i] == '"' {
            result.push(chars[i]);
            i += 1;
            while i < len && chars[i] != '"' {
                if chars[i] == '\\' && i + 1 < len {
                    result.push(chars[i]);
                    result.push(chars[i + 1]);
                    i += 2;
                } else {
                    result.push(chars[i]);
                    i += 1;
                }
            }
            if i < len {
                result.push(chars[i]);
                i += 1;
            }
        } else if chars[i] == '/' && i + 1 < len && chars[i + 1] == '/' {
            i += 2;
            while i < len && chars[i] != '\n' {
                i += 1;
            }
        } else if chars[i] == '/' && i + 1 < len && chars[i + 1] == '*' {
            i += 2;
            while i + 1 < len && !(chars[i] == '*' && chars[i + 1] == '/') {
                i += 1;
            }
            if i + 1 < len {
                i += 2;
            }
        } else {
            result.push(chars[i]);
            i += 1;
        }
    }

    result
}

pub(crate) fn truthy_env(name: &str) -> bool {
    std::env::var(name)
        .map(|value| {
            matches!(
                value.to_ascii_lowercase().as_str(),
                "1" | "true" | "yes" | "on"
            )
        })
        .unwrap_or(false)
}

pub(crate) fn test_artifact_cache_enabled() -> bool {
    truthy_env(TEST_ARTIFACT_CACHE_ENV)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TestComponentProfile {
    Dev,
    Release,
}

impl TestComponentProfile {
    fn from_env() -> anyhow::Result<Self> {
        match std::env::var(TEST_COMPONENT_PROFILE_ENV) {
            Err(std::env::VarError::NotPresent) => Ok(Self::Dev),
            Ok(value) if value == "dev" => Ok(Self::Dev),
            Ok(value) if value == "release" => Ok(Self::Release),
            Ok(value) => Err(anyhow!(
                "unsupported {TEST_COMPONENT_PROFILE_ENV} value {value:?}; expected dev or release"
            )),
            Err(error) => Err(anyhow!(
                "could not read {TEST_COMPONENT_PROFILE_ENV}: {error}"
            )),
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Dev => "dev",
            Self::Release => "release",
        }
    }

    fn cargo_output_directory(self) -> &'static str {
        match self {
            Self::Dev => "debug",
            Self::Release => "release",
        }
    }
}

fn test_drop_cache_enabled() -> bool {
    truthy_env(TEST_DROP_CACHE_ENV)
}

fn test_prepared_component_cache_enabled() -> bool {
    truthy_env(TEST_PREPARED_COMPONENT_CACHE_ENV)
}

fn test_unoptimized_enabled() -> bool {
    truthy_env(TEST_UNOPTIMIZED_ENV)
}

fn test_wasmtime_cache_enabled() -> bool {
    test_wasmtime_cache_enabled_from(
        truthy_env(TEST_WASMTIME_CACHE_ENV),
        test_drop_cache_enabled(),
    )
}

fn test_wasmtime_cache_enabled_from(enabled: bool, drop_cache: bool) -> bool {
    enabled && !drop_cache
}

fn test_cache_stamp_dir() -> Utf8PathBuf {
    Utf8Path::new("tmp").join("test-artifact-cache")
}

fn drop_test_artifact_cache_once() {
    static DROPPED: OnceLock<()> = OnceLock::new();
    DROPPED.get_or_init(|| {
        if test_drop_cache_enabled() {
            let _ = fs::remove_dir_all(test_cache_stamp_dir());
        }
    });
}

fn test_cache_stamp(
    name: &str,
    feature_combination: FeatureCombination,
    kind: &str,
) -> Utf8PathBuf {
    test_cache_stamp_dir().join(format!(
        "{}-{}-{kind}.stamp",
        name.to_snake_case(),
        feature_combination.label(),
    ))
}

fn test_cache_lock(name: &str, feature_combination: FeatureCombination, kind: &str) -> Utf8PathBuf {
    test_cache_stamp_dir().join(format!(
        "{}-{}-{kind}.lock",
        name.to_snake_case(),
        feature_combination.label(),
    ))
}

fn shared_runtime_target_name(feature_combination: FeatureCombination) -> String {
    if matches!(
        feature_combination,
        FeatureCombination::InternalTestExecution
    ) {
        format!("rt-target-{}", feature_combination.label())
    } else {
        "rt-target".to_string()
    }
}

fn rustc_version_verbose() -> String {
    Command::new("rustc")
        .arg("-Vv")
        .output()
        .ok()
        .and_then(|output| {
            if output.status.success() {
                Some(String::from_utf8_lossy(&output.stdout).to_string())
            } else {
                None
            }
        })
        .unwrap_or_else(|| "rustc-version-unavailable".to_string())
}

fn cache_stamp_signature(
    name: &str,
    feature_combination: FeatureCombination,
    kind: &str,
    extra: &[(&str, String)],
) -> String {
    static RUSTC_VERSION_VERBOSE: OnceLock<String> = OnceLock::new();
    let rustc_version = RUSTC_VERSION_VERBOSE.get_or_init(rustc_version_verbose);
    let mut signature = format!(
        "wasm-rquickjs-test-cache-v2\nname={name}\nfeature={}\nkind={kind}\nrustc={rustc_version}\n",
        feature_combination.label(),
    );

    for env_name in [
        "CARGO",
        "CARGO_BUILD_TARGET",
        "CARGO_ENCODED_RUSTFLAGS",
        "CARGO_PROFILE_TEST_OPT_LEVEL",
        "CARGO_TARGET_DIR",
        "RUSTC",
        "RUSTFLAGS",
        "RUSTUP_TOOLCHAIN",
        TEST_COMPONENT_PROFILE_ENV,
    ] {
        if let Ok(value) = std::env::var(env_name) {
            signature.push_str(env_name);
            signature.push('=');
            signature.push_str(&value);
            signature.push('\n');
        }
    }

    for (key, value) in extra {
        signature.push_str(key);
        signature.push('=');
        signature.push_str(value);
        signature.push('\n');
    }

    signature
}

fn modified_time(path: &Utf8Path) -> anyhow::Result<SystemTime> {
    Ok(fs::metadata(path)?.modified()?)
}

fn newest_modified_time(path: &Utf8Path) -> anyhow::Result<SystemTime> {
    let metadata = fs::metadata(path)?;
    let mut newest = metadata.modified()?;
    if metadata.is_dir() {
        for entry in fs::read_dir(path)? {
            let entry = entry?;
            let entry_path = Utf8PathBuf::from_path_buf(entry.path())
                .map_err(|_| anyhow!("Non UTF-8 path under {path}"))?;
            newest = newest.max(newest_modified_time(&entry_path)?);
        }
    }
    Ok(newest)
}

fn newest_modified_time_of_existing(paths: &[Utf8PathBuf]) -> anyhow::Result<SystemTime> {
    let mut newest = SystemTime::UNIX_EPOCH;
    for path in paths {
        if path.exists() {
            newest = newest.max(newest_modified_time(path)?);
        }
    }
    Ok(newest)
}

fn optimize_cache_inputs(input: &Utf8Path) -> Vec<Utf8PathBuf> {
    vec![
        input.to_path_buf(),
        Utf8Path::new("crates")
            .join("wasm-rquickjs")
            .join("src")
            .join("optimize.rs"),
        Utf8Path::new("crates")
            .join("wasm-rquickjs")
            .join("src")
            .join("optimize"),
        Utf8Path::new("Cargo.toml").to_path_buf(),
        Utf8Path::new("Cargo.lock").to_path_buf(),
        Utf8Path::new("crates")
            .join("wasm-rquickjs")
            .join("Cargo.toml"),
    ]
}

fn compile_cache_inputs(path: &Utf8Path) -> Vec<Utf8PathBuf> {
    vec![
        path.to_path_buf(),
        Utf8Path::new("crates").join("wasm-rquickjs").join("src"),
        Utf8Path::new("crates")
            .join("wasm-rquickjs")
            .join("skeleton"),
        Utf8Path::new("crates").join("wasi-logging").join("src"),
        Utf8Path::new("crates").join("golem-websocket"),
        Utf8Path::new("Cargo.toml").to_path_buf(),
        Utf8Path::new("Cargo.lock").to_path_buf(),
        Utf8Path::new("crates")
            .join("wasm-rquickjs")
            .join("Cargo.toml"),
        Utf8Path::new("crates")
            .join("wasi-logging")
            .join("Cargo.toml"),
    ]
}

fn output_fresh_for_inputs(
    output: &Utf8Path,
    stamp: &Utf8Path,
    inputs: &[Utf8PathBuf],
    signature: &str,
) -> bool {
    drop_test_artifact_cache_once();

    if !output.exists() || !stamp.exists() || test_drop_cache_enabled() {
        return false;
    }

    let Ok(stamp_contents) = fs::read_to_string(stamp) else {
        return false;
    };
    if stamp_contents != signature {
        return false;
    }

    let Ok(output_mtime) = modified_time(output) else {
        return false;
    };
    let Ok(stamp_mtime) = modified_time(stamp) else {
        return false;
    };
    if stamp_mtime < output_mtime {
        return false;
    }
    let Ok(input_mtime) = newest_modified_time_of_existing(inputs) else {
        return false;
    };

    output_mtime >= input_mtime && stamp_mtime >= input_mtime
}

fn refresh_cache_stamp(stamp: &Utf8Path, signature: &str) -> anyhow::Result<()> {
    if let Some(parent) = stamp.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(stamp, signature)?;
    Ok(())
}

struct TestCacheLock {
    path: Utf8PathBuf,
}

impl TestCacheLock {
    fn acquire(path: Utf8PathBuf) -> anyhow::Result<Self> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        let started = Instant::now();
        loop {
            match fs::create_dir(&path) {
                Ok(()) => return Ok(Self { path }),
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                    if fs::metadata(&path)
                        .and_then(|metadata| metadata.modified())
                        .ok()
                        .and_then(|modified| modified.elapsed().ok())
                        .is_some_and(|age| age > Duration::from_secs(10 * 60))
                    {
                        let _ = fs::remove_dir_all(&path);
                        continue;
                    }
                    if started.elapsed() > Duration::from_secs(120) {
                        anyhow::bail!("timed out waiting for test artifact cache lock {path}");
                    }
                    thread::sleep(Duration::from_millis(100));
                }
                Err(error) => return Err(error.into()),
            }
        }
    }
}

impl Drop for TestCacheLock {
    fn drop(&mut self) {
        let _ = fs::remove_dir(&self.path);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;
    use test_r::test;
    use tokio::io::{AsyncRead as _, AsyncReadExt as _, AsyncWrite as _, AsyncWriteExt as _};

    #[derive(Default)]
    struct ScriptedIoCalls {
        reads: AtomicUsize,
        writes: AtomicUsize,
        vectored_writes: AtomicUsize,
        flushes: AtomicUsize,
        shutdowns: AtomicUsize,
    }

    struct CountedBody {
        frames: VecDeque<bytes::Bytes>,
        polls: Arc<AtomicUsize>,
        exact_size: Option<u64>,
        end_when_empty: bool,
    }

    impl HttpBody for CountedBody {
        type Data = bytes::Bytes;
        type Error = std::convert::Infallible;

        fn poll_frame(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
            self.polls.fetch_add(1, Ordering::Relaxed);
            Poll::Ready(self.frames.pop_front().map(|data| Ok(Frame::data(data))))
        }

        fn is_end_stream(&self) -> bool {
            self.end_when_empty && self.frames.is_empty()
        }

        fn size_hint(&self) -> SizeHint {
            let mut hint = SizeHint::new();
            if let Some(exact_size) = self.exact_size {
                hint.set_exact(exact_size);
            }
            hint
        }
    }

    struct ScriptedIo {
        calls: Arc<ScriptedIoCalls>,
        fail_write: bool,
        accepted_writes: VecDeque<usize>,
        flush_pending_once: bool,
        shutdown_pending_once: bool,
        fail_flush: bool,
        fail_shutdown: bool,
    }

    impl tokio::io::AsyncRead for ScriptedIo {
        fn poll_read(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buffer: &mut tokio::io::ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            self.calls.reads.fetch_add(1, Ordering::Relaxed);
            buffer.put_slice(b"r");
            Poll::Ready(Ok(()))
        }
    }

    impl tokio::io::AsyncWrite for ScriptedIo {
        fn poll_write(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buffer: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            self.calls.writes.fetch_add(1, Ordering::Relaxed);
            if self.fail_write {
                Poll::Ready(Err(std::io::Error::other("scripted write failure")))
            } else {
                Poll::Ready(Ok(self
                    .accepted_writes
                    .pop_front()
                    .unwrap_or(buffer.len())
                    .min(buffer.len())))
            }
        }

        fn poll_write_vectored(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buffers: &[std::io::IoSlice<'_>],
        ) -> Poll<std::io::Result<usize>> {
            self.calls.vectored_writes.fetch_add(1, Ordering::Relaxed);
            if self.fail_write {
                Poll::Ready(Err(std::io::Error::other("scripted write failure")))
            } else {
                let offered = buffers.iter().map(|buffer| buffer.len()).sum();
                Poll::Ready(Ok(self
                    .accepted_writes
                    .pop_front()
                    .unwrap_or(offered)
                    .min(offered)))
            }
        }

        fn is_write_vectored(&self) -> bool {
            true
        }

        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            self.calls.flushes.fetch_add(1, Ordering::Relaxed);
            if std::mem::take(&mut self.flush_pending_once) {
                cx.waker().wake_by_ref();
                return Poll::Pending;
            }
            if self.fail_flush {
                return Poll::Ready(Err(std::io::Error::other("scripted flush failure")));
            }
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
        ) -> Poll<std::io::Result<()>> {
            self.calls.shutdowns.fetch_add(1, Ordering::Relaxed);
            if std::mem::take(&mut self.shutdown_pending_once) {
                cx.waker().wake_by_ref();
                return Poll::Pending;
            }
            if self.fail_shutdown {
                return Poll::Ready(Err(std::io::Error::other("scripted shutdown failure")));
            }
            Poll::Ready(Ok(()))
        }
    }

    fn scripted_connection(
        trace: HttpLifecycleTrace,
        connection: u16,
        fail_write: bool,
    ) -> (TracedTestServerIo<ScriptedIo>, Arc<ScriptedIoCalls>) {
        let calls = Arc::new(ScriptedIoCalls::default());
        let state = Arc::new(HttpConnectionState::new(trace, connection));
        let io = TracedTestServerIo::new(
            ScriptedIo {
                calls: calls.clone(),
                fail_write,
                accepted_writes: VecDeque::new(),
                flush_pending_once: false,
                shutdown_pending_once: false,
                fail_flush: false,
                fail_shutdown: false,
            },
            state,
        );
        (io, calls)
    }

    #[test]
    fn http_lifecycle_ring_rejects_delayed_old_generation() {
        let journal = HttpLifecycleJournal::new();
        journal.publish(1, 1, HttpLifecyclePhase::Submit, 0);
        journal.publish(
            1 + HTTP_LIFECYCLE_CAP,
            2,
            HttpLifecyclePhase::ResponseHead,
            200,
        );
        journal.publish(1, 3, HttpLifecyclePhase::SendError, 0);

        let retained = journal.slots[1].load(Ordering::Acquire);
        assert_eq!(retained >> 40, (1 + HTTP_LIFECYCLE_CAP) as u64);
        assert_eq!((retained >> 24) & 0xffff, 2);
    }

    #[test]
    fn http_lifecycle_ring_accepts_encoded_sequence_rollover() {
        let journal = HttpLifecycleJournal::new();
        let before_rollover = HTTP_LIFECYCLE_SEQUENCE_MASK as usize;
        journal.publish(
            before_rollover - (HTTP_LIFECYCLE_CAP - 1),
            1,
            HttpLifecyclePhase::Submit,
            0,
        );
        journal.publish(
            before_rollover + 1,
            2,
            HttpLifecyclePhase::ResponseHead,
            200,
        );

        let retained =
            journal.slots[(before_rollover + 1) % HTTP_LIFECYCLE_CAP].load(Ordering::Acquire);
        assert_eq!(retained >> 40, 0);
        assert_eq!((retained >> 24) & 0xffff, 2);
    }

    #[test]
    fn http_lifecycle_ring_remains_valid_during_concurrent_snapshots() {
        let journal = Arc::new(HttpLifecycleJournal::new());
        let writers = (0..8)
            .map(|request| {
                let journal = journal.clone();
                thread::spawn(move || {
                    for _ in 0..1_000 {
                        journal.record(request, HttpLifecyclePhase::Submit, 0);
                    }
                })
            })
            .collect::<Vec<_>>();

        for _ in 0..100 {
            let snapshot = journal.snapshot(1);
            assert!(snapshot.starts_with("invocation=1\n"));
        }
        for writer in writers {
            writer.join().unwrap();
        }

        let newest = journal.next_event.load(Ordering::Acquire) - 1;
        let retained = journal
            .slots
            .iter()
            .map(|slot| slot.load(Ordering::Acquire) >> 40)
            .collect::<Vec<_>>();
        assert!(retained.contains(&(newest as u64)));
        assert!(
            retained
                .iter()
                .all(|sequence| *sequence > (newest - HTTP_LIFECYCLE_CAP) as u64)
        );
    }

    #[test]
    fn http_lifecycle_empty_bodies_record_eof_without_polling() {
        let trace = HttpLifecycleTrace::new();
        for (request, side) in [(1, "request"), (2, "response"), (3, "server-request")] {
            drop(TracedHttpBody::new(
                http_body_util::Empty::<bytes::Bytes>::new(),
                trace.clone(),
                request,
                side,
                None,
            ));
        }

        let server_connection = TracedTestServerConnection {
            state: Arc::new(HttpConnectionState::new(trace.clone(), 17)),
        };
        record_test_server_connection(4, Some(&server_connection));
        drop(TracedHttpBody::new(
            http_body_util::Empty::<bytes::Bytes>::new(),
            trace.clone(),
            4,
            "server-response",
            Some(server_connection.state),
        ));

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=1 phase=request-eof"));
        assert!(snapshot.contains("request=2 phase=response-eof"));
        assert!(snapshot.contains("request=3 phase=server-request-eof"));
        assert!(snapshot.contains("request=4 phase=server-response-eof"));
        assert!(snapshot.contains("request=4 phase=server-request-connection detail=17"));
        assert!(snapshot.contains("request=4 phase=server-response-body-expected-bytes detail=0"));
        assert!(snapshot.contains("request=4 phase=server-response-body-polled-bytes detail=0"));
        assert!(!snapshot.contains("drop-before-terminal"));
    }

    #[test]
    async fn http_lifecycle_send_error_is_terminal_boundary() {
        use wasmtime_wasi_http::WasiHttpHooks;

        let trace = HttpLifecycleTrace::new();
        let mut hooks = HttpTraceHooks(trace.clone());
        let request = http::Request::builder()
            .uri("/")
            .body(
                http_body_util::Empty::<bytes::Bytes>::new()
                    .map_err(|never| match never {})
                    .boxed_unsync(),
            )
            .unwrap();
        let result =
            Box::into_pin(hooks.send_request(request, None, Box::new(async { Ok(()) }))).await;

        assert!(result.is_err());
        let snapshot = trace.snapshot();
        assert!(snapshot.contains("phase=send-error"));
        assert!(!snapshot.contains("phase=response-head"));
    }

    #[test]
    fn http_lifecycle_submit_does_not_mutate_guest_headers() {
        let trace = HttpLifecycleTrace::new();
        let request = http::Request::get("http://127.0.0.1:1234/same")
            .header("x-guest-header", "preserved")
            .header("x-wrq-http-trace-id", "guest-value")
            .body(())
            .unwrap();
        let request_without_trace_header = http::Request::get("http://127.0.0.1:1234/same")
            .body(())
            .unwrap();

        let first_request_id = record_http_submit(&trace, &request);
        let second_request_id = record_http_submit(&trace, &request_without_trace_header);

        assert_ne!(first_request_id, second_request_id);
        assert_eq!(request.headers()["x-guest-header"], "preserved");
        assert_eq!(request.headers()["x-wrq-http-trace-id"], "guest-value");
        assert!(
            !request_without_trace_header
                .headers()
                .contains_key("x-wrq-http-trace-id")
        );
    }

    #[test]
    fn http_lifecycle_server_io_delegates_each_poll_once() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, calls) = scripted_connection(trace.clone(), 7, false);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        let mut storage = [0; 4];
        let mut read = tokio::io::ReadBuf::new(&mut storage);
        assert!(Pin::new(&mut io).poll_read(&mut cx, &mut read).is_ready());
        assert_eq!(read.filled(), b"r");
        assert_eq!(calls.reads.load(Ordering::Relaxed), 1);

        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"abc"),
            Poll::Ready(Ok(3))
        ));
        assert_eq!(calls.writes.load(Ordering::Relaxed), 1);

        let buffers = [std::io::IoSlice::new(b"d"), std::io::IoSlice::new(b"ef")];
        assert!(matches!(
            Pin::new(&mut io).poll_write_vectored(&mut cx, &buffers),
            Poll::Ready(Ok(3))
        ));
        assert_eq!(calls.vectored_writes.load(Ordering::Relaxed), 1);
        assert!(io.is_write_vectored());

        assert!(matches!(
            Pin::new(&mut io).poll_flush(&mut cx),
            Poll::Ready(Ok(()))
        ));
        assert_eq!(calls.flushes.load(Ordering::Relaxed), 1);
        assert!(matches!(
            Pin::new(&mut io).poll_shutdown(&mut cx),
            Poll::Ready(Ok(()))
        ));
        assert_eq!(calls.shutdowns.load(Ordering::Relaxed), 1);

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=7 phase=server-connection-first-read detail=1"));
        assert!(snapshot.contains("request=7 phase=server-connection-first-write detail=3"));
        assert!(snapshot.contains("request=7 phase=server-connection-shutdown"));
    }

    #[test]
    fn http_lifecycle_server_response_frame_arms_exactly_one_correlated_write() {
        let trace = HttpLifecycleTrace::new();
        let state = Arc::new(HttpConnectionState::new(trace.clone(), 9));
        let body = http_body_util::Full::new(bytes::Bytes::from_static(b"body"));
        let mut body = Box::pin(TracedHttpBody::new(
            body,
            trace.clone(),
            41,
            "server-response",
            Some(state.clone()),
        ));
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        assert!(matches!(
            body.as_mut().poll_frame(&mut cx),
            Poll::Ready(Some(Ok(_)))
        ));
        assert_eq!(state.pending_response.load(Ordering::Acquire), 41);

        let calls = Arc::new(ScriptedIoCalls::default());
        let mut io = TracedTestServerIo::new(
            ScriptedIo {
                calls,
                fail_write: false,
                accepted_writes: VecDeque::new(),
                flush_pending_once: false,
                shutdown_pending_once: false,
                fail_flush: false,
                fail_shutdown: false,
            },
            state.clone(),
        );
        let buffers = [
            std::io::IoSlice::new(b"head"),
            std::io::IoSlice::new(b"body"),
        ];
        assert!(matches!(
            Pin::new(&mut io).poll_write_vectored(&mut cx, &buffers),
            Poll::Ready(Ok(8))
        ));
        assert_eq!(state.pending_response.load(Ordering::Acquire), 0);
        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"later"),
            Poll::Ready(Ok(5))
        ));

        let snapshot = trace.snapshot();
        assert_eq!(
            snapshot
                .matches("request=41 phase=server-response-write-after-frame detail=8")
                .count(),
            1
        );
        assert!(snapshot.contains("request=41 phase=server-response-body-expected-bytes detail=4"));
        assert!(snapshot.contains("request=41 phase=server-response-body-polled-bytes detail=4"));
    }

    #[test]
    fn http_lifecycle_server_response_counts_partial_and_cumulative_writes() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, calls) = scripted_connection(trace.clone(), 10, false);
        io.inner.accepted_writes = VecDeque::from([4, 6]);
        io.state.arm_response(44);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"0123456789"),
            Poll::Ready(Ok(4))
        ));
        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"456789"),
            Poll::Ready(Ok(6))
        ));
        assert!(matches!(
            Pin::new(&mut io).poll_flush(&mut cx),
            Poll::Ready(Ok(()))
        ));
        assert_eq!(calls.writes.load(Ordering::Relaxed), 2);
        assert_eq!(calls.flushes.load(Ordering::Relaxed), 1);

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=44 phase=server-response-write-after-frame detail=4"));
        assert!(snapshot.contains("request=44 phase=server-response-write-partial detail=6"));
        assert!(snapshot.contains("request=44 phase=server-response-flush-bytes detail=10"));
    }

    #[test]
    fn http_lifecycle_server_response_records_full_accepted_write_at_terminal() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, _) = scripted_connection(trace.clone(), 11, false);
        io.state.arm_response(54);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        let response = [0; 151];

        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, &response),
            Poll::Ready(Ok(151))
        ));
        drop(io);

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=54 phase=server-response-write-after-frame detail=151"));
        assert!(snapshot.contains("request=54 phase=server-response-terminal-bytes detail=151"));
        assert!(!snapshot.contains("request=54 phase=server-response-write-partial"));
    }

    #[test]
    fn http_lifecycle_server_response_counters_are_independent_after_flush() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, _) = scripted_connection(trace.clone(), 12, false);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        for (request, bytes) in [(45, b"first".as_slice()), (46, b"second".as_slice())] {
            io.state.arm_response(request);
            assert!(Pin::new(&mut io).poll_write(&mut cx, bytes).is_ready());
            assert!(Pin::new(&mut io).poll_flush(&mut cx).is_ready());
        }

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=45 phase=server-response-flush-bytes detail=5"));
        assert!(snapshot.contains("request=46 phase=server-response-flush-bytes detail=6"));
        assert!(!snapshot.contains("server-response-correlation-boundary"));
    }

    #[test]
    fn http_lifecycle_server_io_records_pending_flush_and_shutdown_once() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, calls) = scripted_connection(trace.clone(), 14, false);
        io.inner.flush_pending_once = true;
        io.inner.shutdown_pending_once = true;
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        assert!(Pin::new(&mut io).poll_flush(&mut cx).is_pending());
        assert!(Pin::new(&mut io).poll_flush(&mut cx).is_ready());
        assert!(Pin::new(&mut io).poll_shutdown(&mut cx).is_pending());
        assert!(Pin::new(&mut io).poll_shutdown(&mut cx).is_ready());
        assert_eq!(calls.flushes.load(Ordering::Relaxed), 2);
        assert_eq!(calls.shutdowns.load(Ordering::Relaxed), 2);

        let snapshot = trace.snapshot();
        assert_eq!(
            snapshot.matches("server-connection-flush-pending").count(),
            1
        );
        assert_eq!(snapshot.matches("server-connection-flush-ok").count(), 1);
        assert_eq!(
            snapshot
                .matches("server-connection-shutdown-pending")
                .count(),
            1
        );
        assert_eq!(snapshot.matches("server-connection-shutdown").count(), 2);
    }

    #[test]
    fn http_lifecycle_server_io_errors_snapshot_active_and_pending_responses() {
        let trace = HttpLifecycleTrace::new();
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        let (mut flush_io, _) = scripted_connection(trace.clone(), 21, false);
        flush_io.state.arm_response(55);
        assert!(matches!(
            Pin::new(&mut flush_io).poll_write(&mut cx, b"four"),
            Poll::Ready(Ok(4))
        ));
        flush_io.state.arm_response(56);
        flush_io.inner.fail_flush = true;
        assert!(matches!(
            Pin::new(&mut flush_io).poll_flush(&mut cx),
            Poll::Ready(Err(_))
        ));
        drop(flush_io);

        let (mut shutdown_io, _) = scripted_connection(trace.clone(), 22, false);
        shutdown_io.state.arm_response(57);
        assert!(matches!(
            Pin::new(&mut shutdown_io).poll_write(&mut cx, b"five!"),
            Poll::Ready(Ok(5))
        ));
        shutdown_io.state.arm_response(58);
        shutdown_io.inner.fail_shutdown = true;
        assert!(matches!(
            Pin::new(&mut shutdown_io).poll_shutdown(&mut cx),
            Poll::Ready(Err(_))
        ));
        drop(shutdown_io);

        let snapshot = trace.snapshot();
        for (active, pending, connection, bytes, connection_phase) in [
            (55, 56, 21, 4, "server-connection-flush-error"),
            (57, 58, 22, 5, "server-connection-shutdown-error"),
        ] {
            assert_eq!(
                snapshot
                    .matches(&format!(
                        "request={active} phase=server-response-write-error detail={connection}"
                    ))
                    .count(),
                1
            );
            assert_eq!(
                snapshot
                    .matches(&format!(
                        "request={active} phase=server-response-terminal-bytes detail={bytes}"
                    ))
                    .count(),
                1
            );
            assert_eq!(
                snapshot
                    .matches(&format!(
                        "request={pending} phase=server-response-write-error detail={connection}"
                    ))
                    .count(),
                1
            );
            assert!(snapshot.contains(&format!("request={connection} phase={connection_phase}")));
        }
    }

    #[test]
    fn http_lifecycle_server_response_body_counts_terminate_without_extra_poll() {
        let trace = HttpLifecycleTrace::new();
        let exact_polls = Arc::new(AtomicUsize::new(0));
        let exact = CountedBody {
            frames: VecDeque::from([
                bytes::Bytes::from_static(b"abc"),
                bytes::Bytes::from_static(b"defg"),
            ]),
            polls: exact_polls.clone(),
            exact_size: Some(7),
            end_when_empty: true,
        };
        let mut exact = Box::pin(TracedHttpBody::new(
            exact,
            trace.clone(),
            47,
            "server-response",
            None,
        ));
        let unknown_polls = Arc::new(AtomicUsize::new(0));
        let unknown = CountedBody {
            frames: VecDeque::from([
                bytes::Bytes::from_static(b"un"),
                bytes::Bytes::from_static(b"known"),
            ]),
            polls: unknown_polls.clone(),
            exact_size: None,
            end_when_empty: true,
        };
        let mut unknown = Box::pin(TracedHttpBody::new(
            unknown,
            trace.clone(),
            48,
            "server-response",
            None,
        ));
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        for body in [&mut exact, &mut unknown] {
            assert!(matches!(
                body.as_mut().poll_frame(&mut cx),
                Poll::Ready(Some(Ok(_)))
            ));
            assert!(matches!(
                body.as_mut().poll_frame(&mut cx),
                Poll::Ready(Some(Ok(_)))
            ));
        }
        assert_eq!(exact_polls.load(Ordering::Relaxed), 2);
        assert_eq!(unknown_polls.load(Ordering::Relaxed), 2);
        drop(exact);
        drop(unknown);

        let overflow = http_body_util::Full::new(bytes::Bytes::from(vec![0; 70_000]));
        let mut overflow = Box::pin(TracedHttpBody::new(
            overflow,
            trace.clone(),
            49,
            "server-response",
            None,
        ));
        assert!(overflow.as_mut().poll_frame(&mut cx).is_ready());
        drop(overflow);

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=47 phase=server-response-body-expected-bytes detail=7"));
        assert!(snapshot.contains("request=47 phase=server-response-body-polled-bytes detail=7"));
        assert!(snapshot.contains("request=47 phase=server-response-eof"));
        assert!(!snapshot.contains("request=47 phase=server-response-drop-before-terminal"));
        assert!(snapshot.contains("request=48 phase=server-response-body-expected-unknown"));
        assert!(snapshot.contains("request=48 phase=server-response-body-polled-bytes detail=7"));
        assert!(snapshot.contains("request=48 phase=server-response-eof"));
        assert!(!snapshot.contains("request=48 phase=server-response-drop-before-terminal"));
        assert!(
            snapshot.contains("request=49 phase=server-response-body-expected-bytes detail=65535")
        );
        assert!(
            snapshot.contains("request=49 phase=server-response-body-polled-bytes detail=65535")
        );
        assert_eq!(
            snapshot
                .matches("request=49 phase=server-response-byte-count-overflow")
                .count(),
            2
        );
    }

    #[test]
    fn http_lifecycle_server_response_write_error_preserves_correlation() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, _) = scripted_connection(trace.clone(), 11, true);
        io.state.arm_response(42);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"response"),
            Poll::Ready(Err(_))
        ));
        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=42 phase=server-response-write-error detail=11"));
        assert!(snapshot.contains("request=11 phase=server-connection-write-error"));
    }

    #[test]
    fn http_lifecycle_server_response_error_and_drop_snapshot_accepted_bytes() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, _) = scripted_connection(trace.clone(), 15, false);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        io.state.arm_response(49);
        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"abc"),
            Poll::Ready(Ok(3))
        ));
        io.inner.fail_write = true;
        assert!(matches!(
            Pin::new(&mut io).poll_write(&mut cx, b"failure"),
            Poll::Ready(Err(_))
        ));

        let (mut dropped, _) = scripted_connection(trace.clone(), 16, false);
        dropped.state.arm_response(50);
        assert!(matches!(
            Pin::new(&mut dropped).poll_write(&mut cx, b"drop"),
            Poll::Ready(Ok(4))
        ));
        drop(dropped);

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=49 phase=server-response-terminal-bytes detail=3"));
        assert!(snapshot.contains("request=49 phase=server-response-write-error detail=15"));
        assert!(snapshot.contains("request=50 phase=server-response-terminal-bytes detail=4"));
    }

    #[test]
    fn http_lifecycle_server_connection_drop_reports_armed_response() {
        let trace = HttpLifecycleTrace::new();
        let (io, _) = scripted_connection(trace.clone(), 13, false);
        io.state.arm_response(43);
        drop(io);

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=43 phase=server-response-pending-at-drop detail=13"));
        assert!(snapshot.contains("request=13 phase=server-connection-drop"));
    }

    #[test]
    fn http_lifecycle_server_connection_maps_multiple_requests_to_same_connection() {
        let trace = HttpLifecycleTrace::new();
        let connection = TracedTestServerConnection {
            state: Arc::new(HttpConnectionState::new(trace.clone(), 17)),
        };
        record_test_server_connection(51, Some(&connection));
        record_test_server_connection(52, Some(&connection));

        let snapshot = trace.snapshot();
        assert!(snapshot.contains("request=51 phase=server-request-connection detail=17"));
        assert!(snapshot.contains("request=52 phase=server-request-connection detail=17"));
    }

    #[test]
    fn http_lifecycle_server_response_overlap_is_explicit_and_non_overwriting() {
        let trace = HttpLifecycleTrace::new();
        let state = HttpConnectionState::new(trace.clone(), 19);
        state.arm_response(61);
        state.arm_response(62);

        assert_eq!(state.pending_response.load(Ordering::Acquire), 61);
        let snapshot = trace.snapshot();
        assert!(
            snapshot.contains("request=62 phase=server-response-correlation-overlap detail=61")
        );
    }

    #[test]
    fn http_lifecycle_server_response_boundary_without_flush_is_explicit() {
        let trace = HttpLifecycleTrace::new();
        let (mut io, _) = scripted_connection(trace.clone(), 20, false);
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        io.state.arm_response(63);
        assert!(Pin::new(&mut io).poll_write(&mut cx, b"one").is_ready());
        io.state.arm_response(64);
        assert!(Pin::new(&mut io).poll_write(&mut cx, b"two").is_ready());

        let snapshot = trace.snapshot();
        assert!(
            snapshot.contains("request=63 phase=server-response-write-boundary-bytes detail=3")
        );
        assert!(
            snapshot.contains("request=63 phase=server-response-correlation-boundary detail=64")
        );
        assert!(snapshot.contains("request=64 phase=server-response-write-after-frame detail=3"));
    }

    #[test]
    async fn http_lifecycle_axum_pipeline_preserves_response_correlation() {
        use axum::body::Body;
        use axum::extract::{ConnectInfo, Request};
        use axum::routing::any;
        use bytes::Bytes;
        use http_body_util::Full;

        let trace = HttpLifecycleTrace::new();
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let listener = TracedTestServerListener {
            listener,
            trace: trace.clone(),
        };
        let router = axum::Router::new().route(
            "/",
            any(
                |ConnectInfo(connection): ConnectInfo<TracedTestServerConnection>,
                 request: Request| async move {
                    assert!(matches!(
                        request
                            .headers()
                            .get("x-wrq-http-trace-id")
                            .and_then(|value| value.to_str().ok()),
                        Some("guest-one" | "guest-two")
                    ));
                    let request_id = next_test_server_http_request();
                    record_test_server_connection(request_id, Some(&connection));
                    axum::response::Response::new(Body::new(TracedHttpBody::new(
                        Full::new(Bytes::from_static(b"ok")),
                        connection.state.trace.clone(),
                        request_id,
                        "server-response",
                        Some(connection.state),
                    )))
                },
            ),
        );
        let server = tokio::spawn(async move {
            axum::serve(
                listener,
                router.into_make_service_with_connect_info::<TracedTestServerConnection>(),
            )
            .await
            .unwrap();
        });

        let mut client = tokio::net::TcpStream::connect(address).await.unwrap();
        client
            .write_all(
                b"GET / HTTP/1.1\r\nHost: localhost\r\nx-wrq-http-trace-id: guest-one\r\n\r\n\
                  GET / HTTP/1.1\r\nHost: localhost\r\nx-wrq-http-trace-id: guest-two\r\nConnection: close\r\n\r\n",
            )
            .await
            .unwrap();
        let mut response = Vec::new();
        client.read_to_end(&mut response).await.unwrap();
        server.abort();

        assert_eq!(
            String::from_utf8_lossy(&response)
                .matches("HTTP/1.1 200 OK")
                .count(),
            2
        );
        let snapshot = trace.snapshot();
        let mut request_ids = snapshot
            .lines()
            .filter(|line| line.contains("phase=server-request-connection"))
            .filter_map(|line| {
                line.split_whitespace()
                    .find_map(|field| field.strip_prefix("request="))
            })
            .collect::<Vec<_>>();
        request_ids.sort_unstable();
        request_ids.dedup();
        assert_eq!(request_ids.len(), 2, "{snapshot}");
        for request_id in request_ids {
            assert!(snapshot.contains(&format!(
                "request={request_id} phase=server-request-connection"
            )));
            assert!(snapshot.contains(&format!(
                "request={request_id} phase=server-response-write-after-frame"
            )));
            assert!(snapshot.contains(&format!(
                "request={request_id} phase=server-response-body-expected-bytes detail=2"
            )));
            assert!(snapshot.contains(&format!(
                "request={request_id} phase=server-response-body-polled-bytes detail=2"
            )));
        }
        assert!(!snapshot.contains("server-response-correlation-overlap"));
        assert!(!snapshot.contains("server-response-correlation-boundary"));
    }

    #[cfg(feature = "use-golem-wasmtime")]
    #[test]
    async fn p2_body_method_drops_unused_completion_before_dispatch() {
        use wasmtime_wasi_http::p2::body::{RequestBodyCompletion, prepare_request};

        let (sender, receiver) = tokio::sync::oneshot::channel::<
            Result<(), wasmtime_wasi_http::p2::bindings::http::types::ErrorCode>,
        >();
        let mut request = http::Request::post("http://localhost/")
            .body(
                http_body_util::Empty::<bytes::Bytes>::new()
                    .map_err(|never| match never {})
                    .boxed_unsync(),
            )
            .unwrap();
        request
            .extensions_mut()
            .insert(RequestBodyCompletion(Arc::new(Mutex::new(Some(receiver)))));
        let request = prepare_request(request).await.unwrap();

        assert!(
            request
                .extensions()
                .get::<RequestBodyCompletion>()
                .is_none()
        );
        assert!(sender.is_closed());
    }

    #[test]
    fn source_changes_invalidate_artifact_caches() -> anyhow::Result<()> {
        if test_drop_cache_enabled() {
            return Ok(());
        }

        for (relative, source_inputs) in [
            (
                "crates/golem-websocket/src/lib.rs",
                compile_cache_inputs(Utf8Path::new("fixture")),
            ),
            (
                "crates/golem-websocket/wit/deps/golem-websocket/websocket.wit",
                compile_cache_inputs(Utf8Path::new("fixture")),
            ),
            (
                "crates/golem-websocket/wit-p3/deps/golem-websocket/websocket.wit",
                compile_cache_inputs(Utf8Path::new("fixture")),
            ),
            (
                "crates/wasm-rquickjs/src/optimize/preinit.rs",
                optimize_cache_inputs(Utf8Path::new("fixture.wasm")),
            ),
        ] {
            let temp = Utf8TempDir::new()?;
            let bridge_input = temp.path().join(relative);
            fs::create_dir_all(bridge_input.parent().unwrap())?;
            fs::write(&bridge_input, "bridge-v1")?;
            let inputs: Vec<_> = source_inputs
                .iter()
                .map(|path| temp.path().join(path))
                .collect();
            let output = temp.path().join("output.wasm");
            let stamp = temp.path().join("output.stamp");
            let signature = "test-signature";
            fs::write(&output, "output")?;
            refresh_cache_stamp(&stamp, signature)?;
            assert!(output_fresh_for_inputs(&output, &stamp, &inputs, signature));

            fs::write(&bridge_input, "bridge-v2")?;
            fs::File::open(&bridge_input)?.set_times(
                fs::FileTimes::new().set_modified(modified_time(&stamp)? + Duration::from_secs(1)),
            )?;
            assert!(
                !output_fresh_for_inputs(&output, &stamp, &inputs, signature),
                "a source-only change to {relative} must invalidate the component"
            );
        }
        Ok(())
    }

    #[test]
    fn artifact_cache_stamp_must_not_be_older_than_output() -> anyhow::Result<()> {
        if test_drop_cache_enabled() {
            return Ok(());
        }

        let temp = Utf8TempDir::new()?;
        let input = temp.path().join("input.txt");
        let output = temp.path().join("output.wasm");
        let stamp = temp.path().join("output.stamp");
        let signature = "test-signature";
        fs::write(&input, "input")?;
        fs::write(&output, "output-v1")?;
        refresh_cache_stamp(&stamp, signature)?;

        assert!(output_fresh_for_inputs(
            &output,
            &stamp,
            std::slice::from_ref(&input),
            signature,
        ));

        let stamp_mtime = modified_time(&stamp)?;
        let started = Instant::now();
        loop {
            thread::sleep(Duration::from_millis(10));
            fs::write(&output, format!("output-v2-{:?}", started.elapsed()))?;
            if modified_time(&output)? > stamp_mtime {
                break;
            }
            if started.elapsed() > Duration::from_secs(2) {
                anyhow::bail!("output mtime did not advance beyond cache stamp mtime");
            }
        }

        assert!(
            !output_fresh_for_inputs(&output, &stamp, &[input], signature),
            "a stale stamp must not validate an artifact rewritten after the stamp was produced"
        );

        Ok(())
    }

    #[test]
    fn prepared_component_cache_key_includes_content_hash() -> anyhow::Result<()> {
        let temp = Utf8TempDir::new()?;
        let wasm = temp.path().join("component.wasm");

        fs::write(&wasm, b"aaaa")?;
        let first = prepared_component_cache_key(&wasm)?;

        fs::write(&wasm, b"bbbb")?;
        let second = prepared_component_cache_key(&wasm)?;

        assert_eq!(first.path, second.path);
        assert_eq!(first.len, second.len);
        assert_ne!(
            first.content_hash, second.content_hash,
            "prepared component cache keys must change when same-length component bytes change"
        );

        Ok(())
    }

    #[test]
    fn drop_cache_bypasses_explicit_wasmtime_cache() {
        assert!(test_wasmtime_cache_enabled_from(true, false));
        assert!(!test_wasmtime_cache_enabled_from(false, false));
        assert!(!test_wasmtime_cache_enabled_from(true, true));
        assert!(!test_wasmtime_cache_enabled_from(false, true));
    }

    #[test]
    fn internal_test_runtime_targets_are_isolated() {
        assert_eq!(
            shared_runtime_target_name(FeatureCombination::Normal),
            "rt-target"
        );
        assert_ne!(
            shared_runtime_target_name(FeatureCombination::Normal),
            shared_runtime_target_name(FeatureCombination::InternalTestExecution)
        );
    }
}

fn configure_test_wasmtime_cache(config: &mut wasmtime::Config) -> anyhow::Result<()> {
    if test_wasmtime_cache_enabled() {
        config.cache(Some(wasmtime::Cache::new(wasmtime::CacheConfig::new())?));
    }
    Ok(())
}

fn test_p3_wasmtime_config() -> anyhow::Result<wasmtime::Config> {
    let mut config = wasmtime::Config::default();
    config.wasm_component_model(true);
    config.wasm_component_model_async(true);
    config.epoch_interruption(true);
    config.async_stack_size(32 * 1024 * 1024);
    config.max_wasm_stack(16 * 1024 * 1024);
    configure_test_wasmtime_cache(&mut config)?;
    Ok(config)
}

fn precompile_component(wasm_path: &Utf8Path) -> anyhow::Result<bool> {
    if !test_wasmtime_cache_enabled() {
        return Ok(false);
    }

    let stamp = wasm_path.with_extension("component-precompiled.stamp");
    let signature = cache_stamp_signature(
        wasm_path.file_stem().unwrap_or("component"),
        FeatureCombination::Normal,
        "component-precompile",
        &[("component", wasm_path.to_string())],
    );
    let inputs = [wasm_path.to_path_buf()];
    if output_fresh_for_inputs(&stamp, &stamp, &inputs, &signature) {
        return Ok(false);
    }

    let _lock = TestCacheLock::acquire(stamp.with_extension("lock"))?;
    if output_fresh_for_inputs(&stamp, &stamp, &inputs, &signature) {
        return Ok(false);
    }

    let config = test_p3_wasmtime_config()?;
    let engine = Engine::new(&config)?;
    drop(Component::from_file(&engine, wasm_path)?);
    refresh_cache_stamp(&stamp, &signature)?;
    Ok(true)
}

fn start_test_epoch_thread(engine: &Engine) {
    let epoch_engine = engine.clone();
    std::thread::spawn(move || {
        loop {
            std::thread::sleep(std::time::Duration::from_millis(10));
            epoch_engine.increment_epoch();
        }
    });
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum NodeCompatCategory {
    /// The test exercises supported public API and should pass. Failures count against primary compatibility.
    Runnable,
    /// The tested public API is not implemented yet, but is in scope for this runtime.
    KnownGap,
    /// The test requires capabilities that WASI Preview 2 cannot provide.
    WasmImpossible,
    /// The test depends on V8-specific behavior that QuickJS cannot reasonably mirror.
    EngineDifference,
    /// The test checks Node.js internal implementation details rather than public API.
    NodeInternals,
    /// The test has not been triaged yet and should not affect compatibility percentages.
    Unevaluated,
}

impl NodeCompatCategory {
    pub fn from_config_value(value: &str) -> anyhow::Result<Self> {
        match value {
            "runnable" | "expected-pass" => Ok(Self::Runnable),
            "gap" | "known-gap" | "not-implemented" => Ok(Self::KnownGap),
            "wasi-impossible" | "wasm-impossible" | "impossible" | "unsupported-by-wasi" => {
                Ok(Self::WasmImpossible)
            }
            "engine-difference" | "quickjs-difference" | "v8-specific" => {
                Ok(Self::EngineDifference)
            }
            "node-internals" | "internals" | "implementation-detail" => Ok(Self::NodeInternals),
            "unevaluated" | "untriaged" => Ok(Self::Unevaluated),
            other => anyhow::bail!("unknown node_compat category '{other}'"),
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Runnable => "runnable",
            Self::KnownGap => "known gap",
            Self::WasmImpossible => "WASI-impossible",
            Self::EngineDifference => "engine difference",
            Self::NodeInternals => "Node.js internals",
            Self::Unevaluated => "unevaluated",
        }
    }

    pub fn should_ignore_in_runner(self) -> bool {
        !matches!(self, Self::Runnable)
    }

    pub fn is_primary_surface(self) -> bool {
        matches!(self, Self::Runnable | Self::KnownGap)
    }
}

#[derive(Debug, Clone)]
pub struct NodeCompatSubtestEntry {
    pub name: String,
    pub index: usize,
    pub category: NodeCompatCategory,
    pub reason: Option<String>,
    pub flaky: bool,
}

#[derive(Debug, Clone)]
pub struct NodeCompatTestEntry {
    pub path: String,
    pub category: NodeCompatCategory,
    pub reason: Option<String>,
    pub split: bool,
    pub nested_node_test: bool,
    pub isolate_block_subtests: bool,
    pub timeout_secs: u64,
    pub flaky: bool,
    pub subtests: Vec<NodeCompatSubtestEntry>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum NodeModulesAppCategory {
    Runnable,
    KnownGap,
    Deferred,
}

impl NodeModulesAppCategory {
    pub fn from_config_value(value: &str) -> anyhow::Result<Self> {
        match value {
            "runnable" => Ok(Self::Runnable),
            "known-gap" | "gap" => Ok(Self::KnownGap),
            "deferred" => Ok(Self::Deferred),
            other => anyhow::bail!("unknown node_modules_apps category '{other}'"),
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Runnable => "runnable",
            Self::KnownGap => "known gap",
            Self::Deferred => "deferred",
        }
    }

    pub fn status_label(self) -> &'static str {
        match self {
            Self::Runnable => "Passing",
            Self::KnownGap => "Known gap",
            Self::Deferred => "Deferred",
        }
    }

    pub fn should_ignore_in_runner(self) -> bool {
        !matches!(self, Self::Runnable)
    }
}

#[derive(Debug, Clone)]
pub struct NodeModulesAppTestEntry {
    pub file: String,
    pub category: NodeModulesAppCategory,
    pub coverage: String,
    pub reason: Option<String>,
    pub timeout_secs: u64,
    pub flaky: bool,
}

#[derive(Debug, Clone)]
pub struct NodeModulesAppEntry {
    pub name: String,
    pub category: NodeModulesAppCategory,
    pub reason: Option<String>,
    pub tests: Vec<NodeModulesAppTestEntry>,
}

/// Extract the numeric index from a subtest name like "block_00_foo" or "test_03_bar".
/// Panics if the name doesn't match the expected format (config is authoritative).
pub fn extract_node_compat_subtest_index(name: &str) -> usize {
    let after_prefix = if let Some(rest) = name.strip_prefix("block_") {
        rest
    } else if let Some(rest) = name.strip_prefix("test_") {
        rest
    } else {
        panic!("Subtest name '{name}' must start with 'block_' or 'test_'");
    };
    let digits: String = after_prefix
        .chars()
        .take_while(|c| c.is_ascii_digit())
        .collect();
    digits
        .parse()
        .unwrap_or_else(|_| panic!("Subtest name '{name}' has no valid numeric index after prefix"))
}

fn is_unevaluated_node_compat_reason(reason: &str) -> bool {
    let r = reason.trim();
    r == "newly discovered, not yet evaluated" || r.starts_with("inherited: newly discovered")
}

fn node_compat_category_from_entry(
    path: &str,
    entry: &serde_json::Value,
    inherited: Option<NodeCompatCategory>,
    suite_root: &std::path::Path,
) -> anyhow::Result<NodeCompatCategory> {
    if let Some(category) = entry.get("category").and_then(|v| v.as_str()) {
        return NodeCompatCategory::from_config_value(category);
    }

    if entry
        .get("impossible")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        return Ok(NodeCompatCategory::WasmImpossible);
    }

    if entry.get("skip").and_then(|v| v.as_bool()).unwrap_or(false) {
        let reason = entry.get("reason").and_then(|v| v.as_str()).unwrap_or("");
        return Ok(if is_unevaluated_node_compat_reason(reason) {
            NodeCompatCategory::Unevaluated
        } else if uses_node_internals(suite_root, path)? {
            NodeCompatCategory::NodeInternals
        } else {
            NodeCompatCategory::KnownGap
        });
    }

    if let Some(category) = inherited
        && category.should_ignore_in_runner()
    {
        return Ok(category);
    }

    if uses_node_internals(suite_root, path)? {
        Ok(NodeCompatCategory::NodeInternals)
    } else {
        Ok(NodeCompatCategory::Runnable)
    }
}

pub fn load_node_compat_config(path: &str) -> anyhow::Result<Vec<NodeCompatTestEntry>> {
    let config_path = std::path::Path::new(path);
    let suite_root = config_path
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."))
        .join("suite");
    load_node_compat_config_with_suite_root(path, &suite_root)
}

pub fn load_node_compat_config_with_suite_root(
    path: &str,
    suite_root: &std::path::Path,
) -> anyhow::Result<Vec<NodeCompatTestEntry>> {
    let content = fs::read_to_string(path)?;
    let json_str = strip_jsonc_comments(&content);
    let value: serde_json::Value = serde_json::from_str(&json_str)?;

    let expected_node_version = value
        .get("nodeVersion")
        .and_then(|value| value.as_str())
        .ok_or_else(|| anyhow!("config.jsonc missing string 'nodeVersion'"))?;
    validate_node_compat_suite(suite_root, expected_node_version)?;

    let tests_obj = value
        .get("tests")
        .and_then(|v| v.as_object())
        .ok_or_else(|| anyhow::anyhow!("config.jsonc missing 'tests' object"))?;

    let mut tests = Vec::new();
    for (path, opts) in tests_obj {
        let category = node_compat_category_from_entry(path, opts, None, suite_root)?;
        let reason = opts
            .get("reason")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let split = opts.get("split").and_then(|v| v.as_bool()).unwrap_or(false);
        let nested_node_test = opts
            .get("nestedNodeTest")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let isolate_block_subtests = opts
            .get("isolateBlockSubtests")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let timeout_secs = opts
            .get("timeout")
            .and_then(|v| v.as_u64())
            .unwrap_or(DEFAULT_NODE_COMPAT_TEST_TIMEOUT_SECS);
        let flaky = opts.get("flaky").and_then(|v| v.as_bool()).unwrap_or(false);

        let mut subtests = Vec::new();
        if let Some(subtests_obj) = opts.get("subtests").and_then(|v| v.as_object()) {
            for (subtest_name, subtest_opts) in subtests_obj {
                let sub_category = node_compat_category_from_entry(
                    path,
                    subtest_opts,
                    Some(category),
                    suite_root,
                )?;
                let sub_reason = subtest_opts
                    .get("reason")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .or_else(|| reason.clone());
                let sub_flaky = subtest_opts
                    .get("flaky")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(flaky);
                let index = extract_node_compat_subtest_index(subtest_name);
                subtests.push(NodeCompatSubtestEntry {
                    name: subtest_name.clone(),
                    index,
                    category: sub_category,
                    reason: sub_reason,
                    flaky: sub_flaky,
                });
            }
        }

        tests.push(NodeCompatTestEntry {
            path: path.clone(),
            category,
            reason,
            split,
            nested_node_test,
            isolate_block_subtests,
            timeout_secs,
            flaky,
            subtests,
        });
    }

    Ok(tests)
}

fn validate_node_compat_suite(
    suite_root: &std::path::Path,
    expected_node_version: &str,
) -> anyhow::Result<()> {
    let version_path = suite_root.join("NODE_VERSION");
    let actual_node_version = fs::read_to_string(&version_path).map_err(|error| {
        anyhow!(
            "vendored Node.js test suite is unavailable at {}: {error}; run ./tests/node_compat/vendor.sh {expected_node_version}",
            version_path.display()
        )
    })?;
    let actual_node_version = actual_node_version.trim();
    if actual_node_version != expected_node_version {
        return Err(anyhow!(
            "vendored Node.js test suite version mismatch at {}: config requires {expected_node_version}, found {actual_node_version:?}; run ./tests/node_compat/vendor.sh {expected_node_version}",
            version_path.display()
        ));
    }
    Ok(())
}

pub fn load_node_modules_apps_config(path: &str) -> anyhow::Result<Vec<NodeModulesAppEntry>> {
    let content = fs::read_to_string(path)?;
    let json_str = strip_jsonc_comments(&content);
    let value: serde_json::Value = serde_json::from_str(&json_str)?;

    let apps_obj = value
        .get("apps")
        .and_then(|v| v.as_object())
        .ok_or_else(|| anyhow::anyhow!("node_modules_apps config missing 'apps' object"))?;

    let mut apps = Vec::new();
    for (app_name, opts) in apps_obj {
        let category = node_modules_app_category_from_value(opts, None)?;
        let reason = opts
            .get("reason")
            .and_then(|v| v.as_str())
            .map(str::to_string);
        let default_timeout_secs = opts
            .get("timeout")
            .and_then(|v| v.as_u64())
            .unwrap_or(DEFAULT_NODE_COMPAT_TEST_TIMEOUT_SECS);
        let tests_obj = opts
            .get("tests")
            .and_then(|v| v.as_object())
            .ok_or_else(|| {
                anyhow::anyhow!("node_modules app '{app_name}' missing 'tests' object")
            })?;

        let mut tests = Vec::new();
        for (test_file, test_opts) in tests_obj {
            let test_category = node_modules_app_category_from_value(test_opts, Some(category))?;
            let (coverage, test_reason, timeout_secs, flaky) = match test_opts {
                serde_json::Value::String(coverage) => (
                    coverage.clone(),
                    reason.clone(),
                    default_timeout_secs,
                    false,
                ),
                serde_json::Value::Object(_) => {
                    let coverage = test_opts
                        .get("coverage")
                        .or_else(|| test_opts.get("description"))
                        .and_then(|v| v.as_str())
                        .ok_or_else(|| {
                            anyhow::anyhow!(
                                "node_modules app '{app_name}' test '{test_file}' missing coverage"
                            )
                        })?
                        .to_string();
                    let test_reason = test_opts
                        .get("reason")
                        .and_then(|v| v.as_str())
                        .map(str::to_string)
                        .or_else(|| reason.clone());
                    let timeout_secs = test_opts
                        .get("timeout")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(default_timeout_secs);
                    let flaky = test_opts
                        .get("flaky")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false);
                    (coverage, test_reason, timeout_secs, flaky)
                }
                _ => anyhow::bail!(
                    "node_modules app '{app_name}' test '{test_file}' must be a coverage string or object"
                ),
            };

            tests.push(NodeModulesAppTestEntry {
                file: test_file.clone(),
                category: test_category,
                coverage,
                reason: test_reason,
                timeout_secs,
                flaky,
            });
        }
        tests.sort_by(|a, b| a.file.cmp(&b.file));

        apps.push(NodeModulesAppEntry {
            name: app_name.clone(),
            category,
            reason,
            tests,
        });
    }
    apps.sort_by(|a, b| a.name.cmp(&b.name));

    Ok(apps)
}

fn node_modules_app_category_from_value(
    value: &serde_json::Value,
    inherited: Option<NodeModulesAppCategory>,
) -> anyhow::Result<NodeModulesAppCategory> {
    if let Some(category) = value.get("category").and_then(|v| v.as_str()) {
        return NodeModulesAppCategory::from_config_value(category);
    }
    if value.get("skip").and_then(|v| v.as_bool()).unwrap_or(false) {
        return Ok(NodeModulesAppCategory::KnownGap);
    }
    Ok(inherited.unwrap_or(NodeModulesAppCategory::Runnable))
}

/// Recursively copy a directory and all its contents to a destination.
pub fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> anyhow::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if src_path.is_dir() {
            copy_dir_recursive(&src_path, &dst_path)?;
        } else {
            fs::copy(&src_path, &dst_path)?;
        }
    }
    Ok(())
}

/// Copy a vendored Node.js test file and common shims into a temp directory.
///
/// Sets up the directory layout expected by the node-compat-runner:
/// - `/home/node/test/<suite>/<test_file>` — the test itself
/// - `/home/node/test/common/` — common shims
/// - `/tmp/` — for tmpdir shim
/// - `/home/node/test/fixtures/` — fixture data files (recursively copied)
pub fn setup_node_compat_test_files(temp: &Utf8Path, test_rel_path: &str) -> anyhow::Result<()> {
    // Parse the suite name from the relative path (e.g., "parallel/test-foo.js" → "parallel")
    let suite = test_rel_path.split('/').next().unwrap_or("parallel");

    // Create directory structure: /home/node/test/<suite>/ and /home/node/test/common/
    // The /home/node prefix ensures import.meta.url matches patterns like /.*\/test\//.
    let test_root = temp.join("home").join("node").join("test");
    let suite_dir = test_root.join(suite);
    let common_dir = test_root.join("common");
    fs::create_dir_all(&suite_dir)?;
    fs::create_dir_all(&common_dir)?;

    // Copy the test file
    let test_filename = test_rel_path.rsplit('/').next().unwrap_or(test_rel_path);
    let src_test = format!("tests/node_compat/suite/{test_rel_path}");
    let dst_test = suite_dir.join(test_filename);
    fs::copy(&src_test, &dst_test)?;

    // Some vendored ESM tests import sibling test files with relative specifiers.
    // The split runner still executes one configured test at a time, but those
    // relative imports need the original suite directory shape.
    let src_suite_dir = std::path::Path::new("tests/node_compat/suite").join(suite);
    if suite == "es-module" && src_suite_dir.exists() {
        for entry in fs::read_dir(&src_suite_dir)? {
            let entry = entry?;
            if entry.file_type()?.is_file() {
                let file_name = entry.file_name();
                let file_name_str = file_name.to_string_lossy();
                let dst = suite_dir.join(file_name_str.as_ref());
                if !dst.exists() {
                    fs::copy(entry.path(), dst)?;
                }
            }
        }
    }

    // Copy the common shim
    let src_shim = "tests/node_compat/common-shim/index.js";
    let dst_shim = common_dir.join("index.js");
    fs::copy(src_shim, &dst_shim)?;

    // Copy the common ESM shim if it exists
    let src_shim_mjs = "tests/node_compat/common-shim/index.mjs";
    if std::path::Path::new(src_shim_mjs).exists() {
        fs::copy(src_shim_mjs, common_dir.join("index.mjs"))?;
    }

    // Copy all additional common shims from common-shim directory
    let shim_dir = std::path::Path::new("tests/node_compat/common-shim");
    if shim_dir.exists() {
        for entry in fs::read_dir(shim_dir)? {
            let entry = entry?;
            let file_name = entry.file_name();
            let file_name_str = file_name.to_string_lossy();
            // Skip index.js and index.mjs (already copied above)
            if file_name_str == "index.js" || file_name_str == "index.mjs" {
                continue;
            }
            if entry.file_type()?.is_file() {
                fs::copy(entry.path(), common_dir.join(file_name_str.as_ref()))?;
            }
        }
    }

    // Copy vendored ESM common helpers that are not replaced by local shims.
    let vendored_common_dir = std::path::Path::new("tests/node_compat/suite/common");
    if vendored_common_dir.exists() {
        for entry in fs::read_dir(vendored_common_dir)? {
            let entry = entry?;
            let file_name = entry.file_name();
            let file_name_str = file_name.to_string_lossy();
            if entry.file_type()?.is_file()
                && file_name_str.ends_with(".mjs")
                && !common_dir.join(file_name_str.as_ref()).exists()
            {
                fs::copy(entry.path(), common_dir.join(file_name_str.as_ref()))?;
            }
        }
    }

    // Create /tmp directory for tmpdir shim
    let tmp_dir = temp.join("tmp");
    fs::create_dir_all(&tmp_dir)?;

    // Copy fixture data files for tests that use require('../common/fixtures')
    let fixtures_dst = test_root.join("fixtures");

    // First copy vendored suite fixtures
    let vendored_fixtures_src = std::path::Path::new("tests/node_compat/suite/fixtures");
    if vendored_fixtures_src.exists() {
        copy_dir_recursive(vendored_fixtures_src, fixtures_dst.as_std_path())?;
    }

    // Then overlay with our custom fixtures (take priority over vendored ones)
    let fixtures_src = std::path::Path::new("tests/node_compat/fixtures");
    if fixtures_src.exists() {
        copy_dir_recursive(fixtures_src, fixtures_dst.as_std_path())?;
    }

    if test_rel_path == "sequential/test-module-loading.js" && vendored_fixtures_src.exists() {
        copy_dir_recursive(vendored_fixtures_src, fixtures_dst.as_std_path())?;
    }

    Ok(())
}

pub fn collect_example_paths(dirs: &[&str]) -> anyhow::Result<Vec<Utf8PathBuf>> {
    let mut result = Vec::new();
    for dir in dirs {
        let paths = fs::read_dir(dir)?;
        for example_path in paths {
            let example_path = example_path?;
            let metadata = example_path.metadata()?;
            if metadata.is_dir() {
                let path = Utf8PathBuf::from_path_buf(example_path.path())
                    .map_err(|_| anyhow!("Non UTF-8 example path"))?;
                result.push(path);
            }
        }
    }
    Ok(result)
}

/// Copies a WIT directory to `dst`, turning every synchronous freestanding exported function into
/// an `async func`.
///
/// The Preview 3 generation path rejects *synchronous freestanding exports* — both world-level
/// `export …: func(…)` and plain `name: func(…)` declarations inside an exported `interface`. A
/// synchronous *resource instance method* additionally traps at runtime if its JS implementation
/// returns a Promise. Because the JS in these examples freely uses `async` methods, the rewrite
/// async-ifies every `name: func(` declaration — freestanding functions and resource instance
/// methods alike (see [`rewrite_wit_source_exports_async`]). Resource `constructor`s and `static
/// func`s are left synchronous: WIT has no async spelling for them, and their JS returns values
/// directly.
///
/// Only the package's own `.wit` files (those directly in `src_wit_dir`) are rewritten; the
/// `deps/` subtree is copied verbatim. Dependency interfaces are *imported* (e.g. `wasi:random`),
/// and their function signatures must keep matching the host imports, so they must never be
/// async-ified. Examples that *export* an interface defined in a dependency package may therefore
/// still fail to build or run under the P3 lane; every test is run in P3 mode on CI so such gaps
/// surface directly.
pub fn rewrite_wit_exports_async(
    src_wit_dir: &Utf8Path,
    dst_wit_dir: &Utf8Path,
) -> anyhow::Result<()> {
    if dst_wit_dir.exists() {
        fs::remove_dir_all(dst_wit_dir)?;
    }
    fs::create_dir_all(dst_wit_dir)?;

    for entry in fs::read_dir(src_wit_dir)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        let src_path =
            Utf8PathBuf::from_path_buf(entry.path()).map_err(|_| anyhow!("Non UTF-8 WIT path"))?;
        let file_name = src_path
            .file_name()
            .ok_or_else(|| anyhow!("WIT entry without file name"))?;
        let dst_path = dst_wit_dir.join(file_name);

        if file_type.is_dir() {
            // A `deps/` subtree holds *imported* interfaces. Imports satisfied by the *host*
            // (`wasi:*`, `golem:*` packages — the host registers synchronous implementations)
            // must keep their sync signatures, so those files are copied verbatim. Imports
            // satisfied by *another example component* via composition (`plug_into`) must be
            // rewritten to async, because the providing component is itself built in P3 mode
            // with its exports rewritten to `async func` — otherwise the plug's async exports
            // would not type-match the socket's sync imports.
            copy_deps_rewriting_non_host_packages(src_path.as_std_path(), dst_path.as_std_path())?;
        } else if src_path.extension() == Some("wit") {
            let rewritten = rewrite_wit_source_exports_async(&fs::read_to_string(&src_path)?);
            fs::write(&dst_path, rewritten)?;
        } else {
            fs::copy(&src_path, &dst_path)?;
        }
    }
    Ok(())
}

/// Recursively copies a `deps/` subtree, rewriting `: func(` to `: async func(` in every WIT
/// file whose package is *not* host-provided. Host-provided packages (`wasi:*`, `golem:*`)
/// are copied verbatim because the test host registers synchronous implementations for them;
/// everything else (e.g. `quickjs:*` interfaces exported by sibling example components) is
/// rewritten so composed components type-match. See [`rewrite_wit_exports_async`].
fn copy_deps_rewriting_non_host_packages(
    src: &std::path::Path,
    dst: &std::path::Path,
) -> anyhow::Result<()> {
    fs::create_dir_all(dst)?;
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let src_path = entry.path();
        let dst_path = dst.join(entry.file_name());
        if src_path.is_dir() {
            copy_deps_rewriting_non_host_packages(&src_path, &dst_path)?;
        } else if src_path.extension().and_then(|e| e.to_str()) == Some("wit") {
            let source = fs::read_to_string(&src_path)?;
            let is_host_package = source.lines().any(|line| {
                let line = line.trim_start();
                line.starts_with("package wasi:") || line.starts_with("package golem:")
            });
            if is_host_package {
                fs::write(&dst_path, source)?;
            } else {
                fs::write(&dst_path, rewrite_wit_source_exports_async(&source))?;
            }
        } else {
            fs::copy(&src_path, &dst_path)?;
        }
    }
    Ok(())
}

/// Line-oriented rewrite backing [`rewrite_wit_exports_async`]. Kept separate so it is trivially
/// unit-testable and free of any filesystem access.
///
/// Every line declaring a function type as `name: func(` is turned into `name: async func(`. This
/// covers world-level `export foo: func(…)`, freestanding `foo: func(…)` inside an exported
/// interface, and resource *instance* methods `bar: func(…)`. It deliberately does **not** match
/// `constructor(…)` (no `: func(`) or `baz: static func(…)` (spelled `: static func(`, not
/// `: func(`): WIT has no async spelling for those, and their JS returns values directly.
fn rewrite_wit_source_exports_async(source: &str) -> String {
    source
        .lines()
        .map(|line| {
            if line.contains(": func(") && !line.contains(": async func(") {
                line.replacen(": func(", ": async func(", 1)
            } else {
                line.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
        + if source.ends_with('\n') { "\n" } else { "" }
}

#[derive(Copy, Clone)]
pub enum FeatureCombination {
    None,
    Lite,
    Normal,
    InternalTestExecution,
    NetWriteProfiling,
    NodeCompatNetWriteProfiling,
    TypeScriptRuntime,
    TypeScriptTransformRuntime,
    TypeScriptCompilerProfiling,
    Full,
    FullNoLogging,
    Golem,
    FullWithGolem,
    FullNoLoggingWithGolem,
    FullNoLoggingWithGolemAndTypeScript,
}

impl FeatureCombination {
    pub fn all() -> Vec<FeatureCombination> {
        vec![Self::Lite, Self::Normal, Self::Full, Self::FullWithGolem]
    }

    pub fn label(&self) -> &str {
        match self {
            Self::None => "none",
            Self::Lite => "lite",
            Self::Normal => "normal",
            Self::InternalTestExecution => "internal-test-execution",
            Self::NetWriteProfiling => "net-write-profiling",
            Self::NodeCompatNetWriteProfiling => "node-compat-net-write-profiling",
            Self::TypeScriptRuntime => "typescript-runtime",
            Self::TypeScriptTransformRuntime => "typescript-transform-runtime",
            Self::TypeScriptCompilerProfiling => "typescript-compiler-profiling",
            Self::Full => "full",
            Self::FullNoLogging => "full-no-logging",
            Self::Golem => "golem",
            Self::FullWithGolem => "full-golem",
            Self::FullNoLoggingWithGolem => "full-no-logging-golem",
            Self::FullNoLoggingWithGolemAndTypeScript => "full-no-logging-golem-typescript",
        }
    }

    /// Cargo `--features` args for this combination.
    ///
    /// The runtime ships its `wasi:http@0.3` based fetch and node:http unconditionally, so
    /// `None`/`Lite` collapse onto bare `p3`. The features are always spelled out explicitly so a
    /// build never silently falls back to the default feature set.
    pub fn cargo_args(&self) -> Vec<&'static str> {
        let features = match self {
            FeatureCombination::None | FeatureCombination::Lite => "p3",
            FeatureCombination::Normal => "normal-p3",
            FeatureCombination::InternalTestExecution => "normal-p3,internal-test-execution",
            FeatureCombination::NetWriteProfiling => "normal-p3,net-write-profiling",
            FeatureCombination::NodeCompatNetWriteProfiling => {
                "full-no-logging-p3,golem,typescript-runtime,net-write-profiling"
            }
            FeatureCombination::TypeScriptRuntime => {
                "normal-p3,typescript-runtime,test-observability"
            }
            FeatureCombination::TypeScriptTransformRuntime => {
                "normal-p3,typescript-transform-runtime"
            }
            FeatureCombination::TypeScriptCompilerProfiling => {
                "normal-p3,typescript-compiler-profiling"
            }
            FeatureCombination::Full => "full-p3",
            FeatureCombination::FullNoLogging => "full-no-logging-p3",
            FeatureCombination::Golem => "normal-p3,golem",
            FeatureCombination::FullWithGolem => "full-p3,golem",
            FeatureCombination::FullNoLoggingWithGolem => "full-no-logging-p3,golem",
            FeatureCombination::FullNoLoggingWithGolemAndTypeScript => {
                "full-no-logging-p3,golem,typescript-runtime"
            }
        };
        vec!["--no-default-features", "--features", features]
    }

    fn includes_crypto_full(self) -> bool {
        matches!(
            self,
            FeatureCombination::Full
                | FeatureCombination::FullNoLogging
                | FeatureCombination::FullWithGolem
                | FeatureCombination::FullNoLoggingWithGolem
                | FeatureCombination::FullNoLoggingWithGolemAndTypeScript
                | FeatureCombination::NodeCompatNetWriteProfiling
        )
    }
}

pub struct PreparedComponent {
    engine: Engine,
    linker: Linker<Host>,
    component: Component,
}

impl PreparedComponent {
    /// A Component Model async engine, a P2+P3 WASI/HTTP linker, and the component. Works on both
    /// stock wasmtime and the Golem fork — see [`p3_engine`].
    pub fn new(wasm_path: &Utf8Path) -> anyhow::Result<Self> {
        init_tracing();
        let engine = p3_engine()?;
        let linker = p3_linker(&engine)?;
        let component = Component::from_file(&engine, wasm_path)?;
        Ok(Self {
            engine,
            linker,
            component,
        })
    }
}

/// Mock logging level for wasi:logging/logging
#[derive(Debug, Clone, wasmtime::component::ComponentType, wasmtime::component::Lift)]
#[component(enum)]
#[repr(u8)]
#[allow(dead_code)]
pub enum LogLevel {
    #[component(name = "trace")]
    Trace,
    #[component(name = "debug")]
    Debug,
    #[component(name = "info")]
    Info,
    #[component(name = "warn")]
    Warn,
    #[component(name = "error")]
    Error,
    #[component(name = "critical")]
    Critical,
}

/// Mock attribute-value variant for golem:api/context
#[derive(wasmtime::component::ComponentType, wasmtime::component::Lift)]
#[component(variant)]
pub enum AttributeValue {
    #[component(name = "string")]
    String(String),
}

/// Mock span for golem:api/context testing
pub struct GolemSpan {
    pub name: String,
    pub attributes: Vec<(String, String)>,
    pub finished: bool,
    resource_rep: Option<u32>,
}

/// A PreparedComponent that includes a mock golem:api/context host implementation.
pub struct GolemPreparedComponent {
    engine: Engine,
    linker: Linker<Host>,
    component: Component,
}

impl GolemPreparedComponent {
    /// The P2+P3 WASI/HTTP surface plus the `wasi:logging` and `golem:websocket` mocks (see
    /// [`p3_linker`]) and a `golem:api/context` span-recording mock. Works on both stock wasmtime
    /// and the Golem fork.
    pub fn new(wasm_path: &Utf8Path) -> anyhow::Result<Self> {
        init_tracing();
        let engine = p3_engine()?;
        let mut linker = p3_linker(&engine)?;
        add_golem_context_mock(&mut linker)?;
        let component = Component::from_file(&engine, wasm_path)?;
        Ok(Self {
            engine,
            linker,
            component,
        })
    }
}

#[allow(dead_code)]
pub struct TestInstance {
    engine: Engine,
    linker: Linker<Host>,
    component: Component,
    store: Store<Host>,
    instance: Instance,
    stdout_file: NamedUtf8TempFile,
    stderr_file: NamedUtf8TempFile,
    temp_dir: Utf8TempDir,
    golem_spans: Option<Arc<Mutex<Vec<GolemSpan>>>>,
}

impl TestInstance {
    pub async fn new(wasm_path: &Utf8Path) -> anyhow::Result<Self> {
        if test_prepared_component_cache_enabled() {
            let prepared = prepared_component_for_path(wasm_path)?;
            return Self::from_prepared(&prepared).await;
        }

        let prepared = PreparedComponent::new(wasm_path)?;
        Self::from_prepared(&prepared).await
    }

    pub async fn from_prepared_with_wasi(
        prepared: &PreparedComponent,
        wasi: wasmtime_wasi::WasiCtxBuilder,
    ) -> anyhow::Result<Self> {
        Self::from_parts(
            &prepared.engine,
            &prepared.linker,
            &prepared.component,
            None,
            false,
            wasi,
        )
        .await
    }

    pub async fn new_with_memory_tracking(wasm_path: &Utf8Path) -> anyhow::Result<Self> {
        let prepared = if test_prepared_component_cache_enabled() {
            prepared_component_for_path(wasm_path)?
        } else {
            Arc::new(PreparedComponent::new(wasm_path)?)
        };
        Self::from_parts(
            &prepared.engine,
            &prepared.linker,
            &prepared.component,
            None,
            true,
            WasiCtx::builder(),
        )
        .await
    }

    pub async fn from_prepared(prepared: &PreparedComponent) -> anyhow::Result<Self> {
        Self::from_parts(
            &prepared.engine,
            &prepared.linker,
            &prepared.component,
            None,
            false,
            WasiCtx::builder(),
        )
        .await
    }

    pub async fn from_prepared_with_memory_tracking(
        prepared: &PreparedComponent,
    ) -> anyhow::Result<Self> {
        Self::from_parts(
            &prepared.engine,
            &prepared.linker,
            &prepared.component,
            None,
            true,
            WasiCtx::builder(),
        )
        .await
    }

    pub async fn from_golem_prepared(prepared: &GolemPreparedComponent) -> anyhow::Result<Self> {
        Self::from_parts(
            &prepared.engine,
            &prepared.linker,
            &prepared.component,
            Some(Arc::new(Mutex::new(Vec::new()))),
            false,
            WasiCtx::builder(),
        )
        .await
    }

    async fn from_parts(
        engine: &Engine,
        linker: &Linker<Host>,
        component: &Component,
        golem_spans: Option<Arc<Mutex<Vec<GolemSpan>>>>,
        track_linear_memory: bool,
        mut ctx_builder: wasmtime_wasi::WasiCtxBuilder,
    ) -> anyhow::Result<Self> {
        let stdout_file = NamedUtf8TempFile::new()?;
        let stderr_file = NamedUtf8TempFile::new()?;

        let temp_dir = Utf8TempDir::new()?;
        fs::write(temp_dir.path().join("input.txt"), "test file contents")?;
        fs::create_dir(temp_dir.path().join("test"))?;

        ctx_builder
            .stdout(OutputFile::new(stdout_file.reopen()?))
            .stderr(OutputFile::new(stderr_file.reopen()?))
            .arg("first-arg")
            .arg("second-arg")
            .env("TEST_KEY", "TEST_VALUE")
            .env("TEST_KEY_2", "TEST_VALUE_2")
            .preopened_dir(&temp_dir, "/", FsPerms::ReadWrite)?
            .inherit_network()
            .allow_tcp(true)
            .allow_udp(true)
            .allow_ip_name_lookup(true);
        #[cfg(feature = "use-golem-wasmtime")]
        let (ctx, io_ctx) = ctx_builder.build();
        #[cfg(not(feature = "use-golem-wasmtime"))]
        let ctx = ctx_builder.build();
        let http_ctx = WasiHttpCtx::new();
        let http_trace = HttpLifecycleTrace::new();
        let host = Host {
            table: Arc::new(Mutex::new(ResourceTable::new())),
            wasi: Arc::new(Mutex::new(ctx)),
            wasi_http: Arc::new(Mutex::new(http_ctx)),
            http_hooks: HttpTraceHooks(http_trace),
            started_at: Instant::now(),
            timeout: Duration::from_secs(120),
            log_messages: Arc::new(Mutex::new(Vec::new())),
            ws_sent: Arc::new(Mutex::new(Vec::new())),
            #[cfg(feature = "use-golem-wasmtime")]
            io_ctx: Arc::new(Mutex::new(io_ctx)),
            golem_spans: golem_spans.clone(),
            linear_memory_high_water: track_linear_memory.then(|| Arc::new(AtomicUsize::new(0))),
            linear_memory_limit: None,
        };

        let mut store = Store::new(engine, host);
        if track_linear_memory {
            store.limiter(|host| host);
        }
        store.set_epoch_deadline(0);
        store.epoch_deadline_callback(|cx| {
            let data = cx.data();
            if data.started_at.elapsed() >= data.timeout {
                Ok(UpdateDeadline::Interrupt)
            } else {
                Ok(UpdateDeadline::YieldCustom(
                    1,
                    tokio::task::yield_now().boxed(),
                ))
            }
        });

        let instance = linker.instantiate_async(&mut store, component).await?;

        Ok(Self {
            engine: engine.clone(),
            linker: linker.clone(),
            component: component.clone(),
            store,
            instance,
            stdout_file,
            stderr_file,
            temp_dir,
            golem_spans,
        })
    }

    pub async fn invoke_and_capture_output(
        &mut self,
        interface_name: Option<&str>,
        function_name: &str,
        args: &[Val],
    ) -> (anyhow::Result<Option<Val>>, String) {
        let (results, stdout, _stderr) = self
            .invoke_and_capture_output_with_stderr(interface_name, function_name, args)
            .await;
        (results, stdout)
    }

    pub async fn invoke(
        &mut self,
        interface_name: Option<&str>,
        function_name: &str,
        args: &[Val],
    ) -> anyhow::Result<Option<Val>> {
        self.invoke_and_capture_output_inner(interface_name, function_name, args)
            .await
            .map(|results| results.first().cloned())
    }

    pub async fn invoke_and_capture_output_with_stderr(
        &mut self,
        interface_name: Option<&str>,
        function_name: &str,
        args: &[Val],
    ) -> (anyhow::Result<Option<Val>>, String, String) {
        let results = self
            .invoke_and_capture_output_inner(interface_name, function_name, args)
            .await;

        let stdout = fs::read_to_string(&self.stdout_file).expect("failed to read stdout");
        let stderr = fs::read_to_string(&self.stderr_file).expect("failed to read stderr");

        if results.is_err() {
            for line in stdout.lines() {
                println!("[stdout] {line}");
            }
        }

        for line in stderr.lines() {
            println!("[stderr] {line}");
        }

        // Attach the captured guest output and the host-side tracing output to the error
        // itself so they show up in the test failure report (the `println!`s above are
        // captured by the test runner and are not part of the reported failure message
        // on CI).
        let results = results.map_err(|err| {
            let diagnostics = self.failure_diagnostics();
            err.context(format!(
                "guest stdout:\n{stdout}\nguest stderr:\n{stderr}\n{diagnostics}"
            ))
        });

        (
            results.map(|results| results.first().cloned()),
            stdout,
            stderr,
        )
    }

    /// Read existing journals even after a timeout cancelled the invocation future.
    pub fn failure_diagnostics(&self) -> String {
        let http_lifecycle = self.store.data().http_hooks.0.snapshot();
        let server_http_lifecycle = test_server_http_trace().snapshot();
        let host_trace = host_trace();
        format!(
            "HTTP lifecycle:\n{http_lifecycle}\ntest-server HTTP lifecycle:\n{server_http_lifecycle}\nhost trace:\n{host_trace}"
        )
    }

    pub fn set_epoch_deadline(&mut self, timeout_secs: u64) {
        self.store.data_mut().timeout = Duration::from_secs(timeout_secs);
        self.store.data_mut().started_at = Instant::now();
    }

    /// Caps the guest's linear memory: growth past `bytes` fails like `memory.grow` would.
    pub fn set_linear_memory_limit(&mut self, bytes: usize) {
        self.store.data_mut().linear_memory_limit = Some(bytes);
        self.store.limiter(|host| host);
    }

    pub fn temp_dir_path(&self) -> &Utf8Path {
        self.temp_dir.path()
    }

    /// Highest requested Wasm linear-memory size observed by this test instance.
    /// This is test-only instrumentation; it does not change the component API.
    pub fn linear_memory_high_water_bytes(&self) -> usize {
        self.store
            .data()
            .linear_memory_high_water
            .as_ref()
            .map_or(0, |value| value.load(Ordering::Relaxed))
    }

    pub fn golem_spans(&self) -> Option<Arc<Mutex<Vec<GolemSpan>>>> {
        self.golem_spans.clone()
    }

    pub fn read_stdout(&self) -> anyhow::Result<String> {
        Ok(fs::read_to_string(&self.stdout_file)?)
    }

    pub fn read_stderr(&self) -> anyhow::Result<String> {
        Ok(fs::read_to_string(&self.stderr_file)?)
    }

    pub fn read_log_messages(&self) -> Vec<(LogLevel, String, String)> {
        self.store.data().log_messages.lock().unwrap().clone()
    }

    pub fn read_ws_sent(&self) -> Vec<WsSentMessage> {
        self.store.data().ws_sent.lock().unwrap().clone()
    }

    async fn invoke_and_capture_output_inner(
        &mut self,
        interface_name: Option<&str>,
        function_name: &str,
        args: &[Val],
    ) -> anyhow::Result<Vec<Val>> {
        let func = match interface_name {
            Some(interface_name) => {
                let (_, exported_instance_id) = self
                    .instance
                    .get_export(&mut self.store, None, interface_name)
                    .ok_or_else(|| anyhow!("Interface {interface_name} not found"))?;
                let (_, func_id) = self
                    .instance
                    .get_export(&mut self.store, Some(&exported_instance_id), function_name)
                    .ok_or_else(|| {
                        anyhow!("Function {function_name} not found in interface {interface_name}")
                    })?;
                self.instance
                    .get_func(&mut self.store, func_id)
                    .ok_or_else(|| anyhow!("Function {function_name} not found"))?
            }
            None => self
                .instance
                .get_func(&mut self.store, function_name)
                .ok_or_else(|| anyhow!("Function {function_name} not found"))?,
        };

        match timeout(Duration::from_secs(300), self.perform_invoke(func, args)).await {
            Ok(result) => result,
            Err(_) => Err(anyhow!("Function {function_name} timed out")),
        }
    }

    async fn perform_invoke(&mut self, func: Func, args: &[Val]) -> anyhow::Result<Vec<Val>> {
        let mut results = (0..func.ty(&self.store).results().len())
            .map(|_| Val::Bool(false))
            .collect::<Vec<_>>();
        func.call_async(&mut self.store, args, &mut results).await?;
        Ok(results)
    }

    pub async fn drop_resource(&mut self, resource: ResourceAny) -> anyhow::Result<()> {
        resource.resource_drop_async(&mut self.store).await?;
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct PreparedComponentCacheKey {
    path: Utf8PathBuf,
    len: u64,
    modified: Duration,
    content_hash: u64,
}

fn prepared_component_cache_key(wasm_path: &Utf8Path) -> anyhow::Result<PreparedComponentCacheKey> {
    let metadata = fs::metadata(wasm_path)?;
    let path = fs::canonicalize(wasm_path)
        .ok()
        .and_then(|path| Utf8PathBuf::from_path_buf(path).ok())
        .unwrap_or_else(|| wasm_path.to_path_buf());
    let modified = metadata
        .modified()?
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default();
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let mut file = fs::File::open(wasm_path)?;
    let mut buffer = [0; 64 * 1024];
    loop {
        let read = file.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        buffer[..read].hash(&mut hasher);
    }
    Ok(PreparedComponentCacheKey {
        path,
        len: metadata.len(),
        modified,
        content_hash: hasher.finish(),
    })
}

fn prepared_component_for_path(wasm_path: &Utf8Path) -> anyhow::Result<Arc<PreparedComponent>> {
    static PREPARED_COMPONENTS: OnceLock<
        Mutex<HashMap<PreparedComponentCacheKey, Arc<PreparedComponent>>>,
    > = OnceLock::new();
    static DROPPED: OnceLock<()> = OnceLock::new();

    let key = prepared_component_cache_key(wasm_path)?;
    let mut prepared = PREPARED_COMPONENTS
        .get_or_init(|| Mutex::new(HashMap::new()))
        .lock()
        .unwrap();

    if test_drop_cache_enabled() {
        DROPPED.get_or_init(|| prepared.clear());
    }

    if let Some(component) = prepared.get(&key) {
        return Ok(component.clone());
    }

    let component = Arc::new(PreparedComponent::new(wasm_path)?);
    prepared.insert(key, component.clone());
    Ok(component)
}

pub async fn invoke_and_capture_output(
    wasm_path: &Utf8Path,
    interface_name: Option<&str>,
    function_name: &str,
    args: &[Val],
) -> (anyhow::Result<Option<Val>>, String) {
    let (results, stdout, _stderr) =
        invoke_and_capture_output_with_stderr(wasm_path, interface_name, function_name, args).await;
    (results, stdout)
}

pub async fn invoke_and_capture_output_with_stderr(
    wasm_path: &Utf8Path,
    interface_name: Option<&str>,
    function_name: &str,
    args: &[Val],
) -> (anyhow::Result<Option<Val>>, String, String) {
    match TestInstance::new(wasm_path).await {
        Ok(mut test_instance) => {
            test_instance
                .invoke_and_capture_output_with_stderr(interface_name, function_name, args)
                .await
        }
        Err(e) => (Err(e), String::new(), String::new()),
    }
}

enum WasmSource {
    Precompiled(Utf8PathBuf),
    OwnedTemporary(NamedUtf8TempFile),
}

pub struct CompiledTest {
    wasm: WasmSource,
}

impl CompiledTest {
    pub async fn new(path: &Utf8Path, use_shared_target: bool) -> anyhow::Result<CompiledTest> {
        Self::new_with_features(path, use_shared_target, FeatureCombination::Normal).await
    }

    pub async fn new_unoptimized_with_features(
        path: &Utf8Path,
        use_shared_target: bool,
        feature_combination: FeatureCombination,
    ) -> anyhow::Result<CompiledTest> {
        Self::compile_with_features(path, use_shared_target, feature_combination, &[]).await
    }

    pub async fn new_with_features(
        path: &Utf8Path,
        use_shared_target: bool,
        feature_combination: FeatureCombination,
    ) -> anyhow::Result<CompiledTest> {
        Self::new_with_features_and_additional_modules(
            path,
            use_shared_target,
            feature_combination,
            &[],
        )
        .await
    }

    pub async fn new_with_features_and_additional_modules(
        path: &Utf8Path,
        use_shared_target: bool,
        feature_combination: FeatureCombination,
        additional_modules: &[JsModuleSpec],
    ) -> anyhow::Result<CompiledTest> {
        let compiled = Self::compile_with_features(
            path,
            use_shared_target,
            feature_combination,
            additional_modules,
        )
        .await?;
        let compiled = if test_unoptimized_enabled() {
            compiled
        } else {
            compiled.optimize().await?
        };
        if truthy_env(TEST_PRECOMPILE_COMPONENT_ENV) {
            let started = Instant::now();
            if precompile_component(compiled.wasm_path())? {
                println!(
                    "Precompiled changed component once before parallel workers start: {} ({:.3?})",
                    compiled.wasm_path(),
                    started.elapsed()
                );
            }
        }
        Ok(compiled)
    }

    async fn compile_with_features(
        path: &Utf8Path,
        use_shared_target: bool,
        feature_combination: FeatureCombination,
        additional_modules: &[JsModuleSpec],
    ) -> anyhow::Result<CompiledTest> {
        drop_test_artifact_cache_once();
        let component_profile = TestComponentProfile::from_env()?;
        let name = path.file_name().unwrap();
        let wrapper_crate_root = Utf8Path::new("tmp")
            .join(name)
            .join(feature_combination.label());
        // Test workers are separate processes. Lock the shared output root even when artifact
        // caching is disabled, so generation and patching cannot overlap another worker's build.
        fs::create_dir_all(wrapper_crate_root.parent().unwrap())?;
        let wrapper_root_guard = fs::File::create(wrapper_crate_root.with_extension("lock"))?;
        wrapper_root_guard.lock()?;

        // shared_target is relative to wrapper_crate_root. Internal-test builds are isolated from
        // normal builds because runtime group 2 compiles both variants of the same fetch example
        // in parallel; sharing the final Cargo output would let one overwrite the other. Other
        // feature combinations retain the common target to avoid multiplying large build trees.
        let shared_target_name = shared_runtime_target_name(feature_combination);
        let shared_target = Utf8Path::new("..").join("..").join(&shared_target_name);
        let wasm_file_name = format!("{}.wasm", name.to_snake_case());
        let compiled_wasm_path = if use_shared_target {
            Utf8Path::new("tmp")
                .join(&shared_target_name)
                .join("wasm32-wasip2")
                .join(component_profile.cargo_output_directory())
                .join(&wasm_file_name)
        } else {
            wrapper_crate_root
                .join("target")
                .join("wasm32-wasip2")
                .join(component_profile.cargo_output_directory())
                .join(&wasm_file_name)
        };
        let compile_cache_kind = format!("compile-{}", component_profile.label());
        let compile_stamp = test_cache_stamp(name, feature_combination, &compile_cache_kind);
        let compile_inputs = compile_cache_inputs(path);
        let compile_signature = cache_stamp_signature(
            name,
            feature_combination,
            "compile",
            &[
                ("target", "wasm32-wasip2".to_string()),
                ("generation_target", "WasiP3".to_string()),
                ("use_shared_target", use_shared_target.to_string()),
                ("component_profile", component_profile.label().to_string()),
                ("cargo_args", feature_combination.cargo_args().join("|")),
                (
                    "crypto_dev_opt_level",
                    if feature_combination.includes_crypto_full() {
                        "3"
                    } else {
                        "default"
                    }
                    .to_string(),
                ),
                ("additional_modules", format!("{additional_modules:?}")),
            ],
        );

        if test_artifact_cache_enabled()
            && output_fresh_for_inputs(
                &compiled_wasm_path,
                &compile_stamp,
                &compile_inputs,
                &compile_signature,
            )
        {
            println!("Reusing cached wrapper component {compiled_wasm_path}");
            return Ok(CompiledTest {
                wasm: Precompiled(compiled_wasm_path),
            });
        }

        let _cache_lock = if test_artifact_cache_enabled() {
            Some(TestCacheLock::acquire(test_cache_lock(
                name,
                feature_combination,
                &compile_cache_kind,
            ))?)
        } else {
            None
        };

        if test_artifact_cache_enabled()
            && output_fresh_for_inputs(
                &compiled_wasm_path,
                &compile_stamp,
                &compile_inputs,
                &compile_signature,
            )
        {
            println!("Reusing cached wrapper component {compiled_wasm_path}");
            return Ok(CompiledTest {
                wasm: Precompiled(compiled_wasm_path),
            });
        }

        // The examples' world-level exported functions are rewritten to `async func` before
        // generation. The rewritten WIT lives inside the wrapper crate dir so it never touches the
        // committed example sources.
        let wit_dir = wrapper_crate_root.join("wit-async");
        rewrite_wit_exports_async(&path.join("wit"), &wit_dir)?;

        println!("Generating wrapper create for example '{name}' to {wrapper_crate_root}");
        let mut js_modules = vec![JsModuleSpec {
            name: name.to_string(),
            mode: EmbeddingMode::EmbedFile(path.join("src").join(format!("{name}.js"))),
        }];
        js_modules.extend_from_slice(additional_modules);
        generate_wrapper_crate(&wit_dir, &js_modules, &wrapper_crate_root, None)?;
        use_local_golem_websocket(&wrapper_crate_root)?;

        println!("Compiling wrapper crate in {wrapper_crate_root}");
        let locked_build = truthy_env(TEST_LOCKED_BUILDS_ENV);
        let build_wrapper = |offline: bool| -> std::io::Result<_> {
            let mut command = Command::new("cargo");
            command.arg("build");
            if component_profile == TestComponentProfile::Release {
                command.arg("--release");
            }
            if locked_build {
                command.arg("--locked");
            }
            if offline {
                command.arg("--offline");
            }
            if component_profile == TestComponentProfile::Dev
                && feature_combination.includes_crypto_full()
            {
                command
                    .arg("--config")
                    .arg("profile.dev.package.rsa.opt-level=3")
                    .arg("--config")
                    .arg("profile.dev.package.num-bigint-dig.opt-level=3");
            }
            command.arg("--target").arg("wasm32-wasip2");
            if use_shared_target {
                command.arg("--target-dir");
                command.arg(&shared_target);
            }
            command
                .args(feature_combination.cargo_args())
                .current_dir(&wrapper_crate_root)
                .status()
        };
        let mut status = build_wrapper(locked_build)?;
        if locked_build && !status.success() {
            println!("Locked local build failed; retrying with dependency downloads enabled");
            status = build_wrapper(false)?;
        }
        if !status.success() {
            return Err(std::io::Error::other(format!(
                "cargo build failed for {wrapper_crate_root}"
            ))
            .into());
        }

        if test_artifact_cache_enabled() {
            refresh_cache_stamp(&compile_stamp, &compile_signature)?;
        }

        Ok(CompiledTest {
            wasm: Precompiled(compiled_wasm_path),
        })
    }

    /// Run Wizer pre-initialization on the compiled component.
    /// Returns a new `CompiledTest` pointing to the optimized wasm file.
    pub async fn optimize(&self) -> anyhow::Result<CompiledTest> {
        drop_test_artifact_cache_once();

        let input = self.wasm_path();
        let optimized = input.with_extension("optimized.wasm");
        let optimize_stamp = input.with_extension("optimized.stamp");
        let optimize_inputs = optimize_cache_inputs(input);
        let optimize_signature = cache_stamp_signature(
            input.file_stem().unwrap_or("component"),
            FeatureCombination::Normal,
            "optimize",
            &[
                ("input", input.to_string()),
                ("init_func", "wizer-initialize".to_string()),
                ("optimizer", "wasm_rquickjs::optimize_component".to_string()),
            ],
        );
        if test_artifact_cache_enabled()
            && output_fresh_for_inputs(
                &optimized,
                &optimize_stamp,
                &optimize_inputs,
                &optimize_signature,
            )
        {
            println!("Reusing cached optimized component {optimized}");
            return Ok(CompiledTest {
                wasm: Precompiled(optimized),
            });
        }

        let _cache_lock = if test_artifact_cache_enabled() {
            let lock_name = input.file_stem().unwrap_or("component");
            Some(TestCacheLock::acquire(test_cache_lock(
                lock_name,
                FeatureCombination::Normal,
                "optimize",
            ))?)
        } else {
            None
        };

        if test_artifact_cache_enabled()
            && output_fresh_for_inputs(
                &optimized,
                &optimize_stamp,
                &optimize_inputs,
                &optimize_signature,
            )
        {
            println!("Reusing cached optimized component {optimized}");
            return Ok(CompiledTest {
                wasm: Precompiled(optimized),
            });
        }

        println!("Optimizing component {input} -> {optimized}");
        // Readers outlive the build lock. Publish a complete component instead of truncating
        // the shared output while another worker may be loading it.
        let pending = NamedUtf8TempFile::new_in(optimized.parent().unwrap())?;
        wasm_rquickjs::optimize_component(input, pending.path(), "wizer-initialize").await?;
        pending.persist(&optimized)?;
        if test_artifact_cache_enabled() {
            refresh_cache_stamp(&optimize_stamp, &optimize_signature)?;
        }
        Ok(CompiledTest {
            wasm: Precompiled(optimized),
        })
    }

    pub fn wasm_path(&self) -> &Utf8Path {
        match &self.wasm {
            WasmSource::Precompiled(path) => path,
            WasmSource::OwnedTemporary(temp_file) => temp_file.path(),
        }
    }
}

/// Opt `CompiledTest` into test-r's `Cloneable` sharing strategy so that
/// worker subprocesses can share the parent's compilation result instead
/// of forcing the suite into single-threaded mode under output capturing.
///
/// The wire format is just the **absolute** wasm path. The parent compiles
/// the wrapper crate once (via the existing `CompiledTest::new*` ctors) into
/// a stable on-disk location under `tmp/<example>/<features>/...` (or the
/// shared `tmp/rt-target/...` tree when `use_shared_target = true`) — these
/// paths outlive both the dep value and the suite. Each worker simply receives
/// the path and reconstructs a `Precompiled(...)` `CompiledTest` that points
/// at the same on-disk artifact.
///
/// `OwnedTemporary` is only ever produced by `plug_into`, which is called
/// inside test bodies (never inside a `#[test_dep]` ctor). Shipping an
/// `OwnedTemporary` over wire would silently delete the temp file as soon as
/// the parent dropped the value after `to_wire`, leaving workers reading a
/// dangling path. We refuse loudly instead.
impl test_r::core::CloneableDep for CompiledTest {
    fn to_wire(&self) -> Vec<u8> {
        match &self.wasm {
            Precompiled(path) => {
                let abs = path.canonicalize_utf8().unwrap_or_else(|e| {
                    panic!(
                        "CompiledTest path '{path}' must exist before \
                         being shipped via Cloneable scope: {e}"
                    )
                });
                abs.as_str().as_bytes().to_vec()
            }
            WasmSource::OwnedTemporary(_) => panic!(
                "OwnedTemporary CompiledTest cannot be shared via Cloneable \
                 scope; plug_into() output must stay inside a single test body"
            ),
        }
    }

    fn from_wire(bytes: &[u8]) -> Self {
        let path_str = std::str::from_utf8(bytes)
            .expect("Cloneable CompiledTest wire bytes must be valid UTF-8 path");
        let path = Utf8PathBuf::from(path_str);
        assert!(
            path.exists(),
            "Cloneable CompiledTest received path that does not exist: {path}. \
             The parent must keep the compiled wasm artifact alive for the suite duration."
        );
        CompiledTest {
            wasm: Precompiled(path),
        }
    }
}

impl CompiledTest {
    pub fn plug_into(&self, other: &CompiledTest) -> anyhow::Result<CompiledTest> {
        let mut graph = CompositionGraph::new();
        let socket_package =
            Package::from_file("socket", None, other.wasm_path(), graph.types_mut())?;
        let socket_id = graph.register_package(socket_package)?;

        let plug_package = Package::from_file("plug", None, self.wasm_path(), graph.types_mut())?;
        let plug_id = graph.register_package(plug_package)?;

        plug(
            &mut graph,
            vec![(self.wasm_path().to_string(), plug_id)],
            socket_id,
        )?;

        let bytes = graph.encode(EncodeOptions::default())?;
        let mut wasm_path = NamedUtf8TempFile::new()?;
        wasm_path.write_all(bytes.as_slice())?;
        wasm_path.flush()?;
        Ok(CompiledTest {
            wasm: WasmSource::OwnedTemporary(wasm_path),
        })
    }
}

#[derive(Clone)]
pub struct Host {
    pub table: Arc<Mutex<ResourceTable>>,
    pub wasi: Arc<Mutex<WasiCtx>>,
    pub wasi_http: Arc<Mutex<WasiHttpCtx>>,
    http_hooks: HttpTraceHooks,
    pub started_at: Instant,
    pub timeout: Duration,
    pub log_messages: Arc<Mutex<Vec<(LogLevel, String, String)>>>,
    pub ws_sent: Arc<Mutex<Vec<WsSentMessage>>>,
    #[cfg(feature = "use-golem-wasmtime")]
    pub io_ctx: Arc<Mutex<wasmtime_wasi::IoCtx>>,
    pub golem_spans: Option<Arc<Mutex<Vec<GolemSpan>>>>,
    pub linear_memory_high_water: Option<Arc<AtomicUsize>>,
    /// Refuses linear-memory growth past this size, as an embedder's memory cap does.
    pub linear_memory_limit: Option<usize>,
}

impl wasmtime::ResourceLimiter for Host {
    fn memory_growing(
        &mut self,
        current: usize,
        desired: usize,
        _maximum: Option<usize>,
        #[cfg(feature = "use-golem-wasmtime")] kind: wasmtime::MemoryKind,
    ) -> wasmtime::Result<bool> {
        #[cfg(feature = "use-golem-wasmtime")]
        let is_linear_memory = kind == wasmtime::MemoryKind::LinearMemory;
        #[cfg(not(feature = "use-golem-wasmtime"))]
        let is_linear_memory = true;
        if is_linear_memory && let Some(high_water) = &self.linear_memory_high_water {
            high_water.fetch_max(current.max(desired), Ordering::Relaxed);
        }
        Ok(!is_linear_memory
            || self
                .linear_memory_limit
                .is_none_or(|limit| desired <= limit))
    }

    fn table_growing(
        &mut self,
        _current: usize,
        _desired: usize,
        _maximum: Option<usize>,
    ) -> wasmtime::Result<bool> {
        Ok(true)
    }
}

impl WasiView for Host {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: Arc::get_mut(&mut self.wasi)
                .expect("WasiCtx is shared and cannot be borrowed mutably")
                .get_mut()
                .expect("WasiCtx mutex must never fail"),
            table: Arc::get_mut(&mut self.table)
                .expect("ResourceTable is shared and cannot be borrowed mutably")
                .get_mut()
                .expect("ResourceTable mutex must never fail"),
            #[cfg(feature = "use-golem-wasmtime")]
            io_ctx: Arc::get_mut(&mut self.io_ctx)
                .expect("IoCtx is shared and cannot be borrowed mutably")
                .get_mut()
                .expect("IoCtx mutex must never fail"),
        }
    }
}

impl WasiHttpView for Host {
    fn http(&mut self) -> WasiHttpCtxView<'_> {
        WasiHttpCtxView {
            ctx: Arc::get_mut(&mut self.wasi_http)
                .expect("WasiHttpCtx is shared and cannot be borrowed mutably")
                .get_mut()
                .expect("WasiHttpCtx mutex must never fail"),
            table: Arc::get_mut(&mut self.table)
                .expect("ResourceTable is shared and cannot be borrowed mutably")
                .get_mut()
                .expect("ResourceTable mutex must never fail"),
            hooks: &mut self.http_hooks,
        }
    }
}

// ---------------------------------------------------------------------------------------------
// WASI Preview 3 (Component Model async) host support.
//
// Works on both stock wasmtime and the Golem wasmtime fork (`use-golem-wasmtime`). The shared
// `Host` handles the fork's extra `IoCtx` view field and excludes its GC-heap callbacks from the
// guest linear-memory high-water metric.
// ---------------------------------------------------------------------------------------------

/// Preview 3 engine: same stack/epoch configuration as the P2 host, plus Component Model async
/// support so that async-lifted exports can be driven by the concurrent executor that
/// `Func::call_async` uses internally.
fn p3_engine() -> anyhow::Result<Engine> {
    let config = test_p3_wasmtime_config()?;
    let engine = Engine::new(&config)?;

    start_test_epoch_thread(&engine);
    Ok(engine)
}

/// Preview 3 linker: the P2 WASI surface (P3 components still import residual `wasi:io`/0.2 std
/// interfaces), the P3 WASI surface, and the P3 async HTTP surface used by `fetch`. Also mocks
/// `wasi:logging/logging` and `golem:websocket/client@1.5.0` so P3 builds with the (target-
/// agnostic) `logging` / `websocket` features can instantiate; the definitions are ignored by
/// components that don't import them.
fn p3_linker(engine: &Engine) -> anyhow::Result<Linker<Host>> {
    let mut linker: Linker<Host> = Linker::new(engine);
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
    wasmtime_wasi::p3::add_to_linker(&mut linker)?;
    wasmtime_wasi_http::p3::add_to_linker(&mut linker)?;
    add_wasi_logging_mock(&mut linker)?;
    add_websocket_client_mock(&mut linker)?;
    Ok(linker)
}

/// Mock `wasi:logging/logging`: records every `log` call in the Host's `log_messages` list.
fn add_wasi_logging_mock(linker: &mut Linker<Host>) -> anyhow::Result<()> {
    let mut logging = linker.instance("wasi:logging/logging")?;
    logging.func_wrap(
        "log",
        |mut ctx: StoreContextMut<'_, Host>,
         (level, context, message): (LogLevel, String, String)|
         -> Result<(), wasmtime::Error> {
            ctx.data_mut()
                .log_messages
                .lock()
                .unwrap()
                .push((level, context, message));
            Ok(())
        },
    )?;
    Ok(())
}

/// Mock `golem:api/context@1.5.0`: implements `start-span`, `span.set-attribute`, and
/// `span.finish`, recording every span in the current store's list so tests can assert on the
/// emitted tracing spans without sharing records between component instances.
fn add_golem_context_mock(linker: &mut Linker<Host>) -> anyhow::Result<()> {
    let mut golem_ctx = linker.instance("golem:api/context@1.5.0")?;

    // Register the span resource type
    let span_resource_type = ResourceType::host::<GolemSpan>();
    golem_ctx.resource("span", span_resource_type, {
        move |mut ctx: StoreContextMut<'_, Host>, rep: u32| {
            // Destructor: mark span as finished if not already
            let table = ctx.data_mut().table.lock().unwrap();
            // Resource already dropped by wasmtime
            let _ = (rep, table);
            Ok(())
        }
    })?;

    // start-span: func(name: string) -> span
    golem_ctx.func_wrap(
        "start-span",
        move |mut ctx: StoreContextMut<'_, Host>,
              (name,): (String,)|
              -> Result<(wasmtime::component::Resource<GolemSpan>,), wasmtime::Error> {
            let spans = ctx
                .data()
                .golem_spans
                .clone()
                .expect("Golem span host requires an instance-local span collection");
            let span = GolemSpan {
                name: name.clone(),
                attributes: Vec::new(),
                finished: false,
                resource_rep: None,
            };
            let mut table = ctx.data_mut().table.lock().unwrap();
            let resource = table.push(span)?;
            let resource_rep = resource.rep();
            if let Ok(span) = table.get_mut(&resource) {
                span.resource_rep = Some(resource_rep);
            }
            spans.lock().unwrap().push(GolemSpan {
                name,
                attributes: Vec::new(),
                finished: false,
                resource_rep: Some(resource_rep),
            });
            Ok((resource,))
        },
    )?;

    // [method]span.set-attribute: func(name: string, value: attribute-value)
    // attribute-value is a variant with one case: string(string)
    golem_ctx.func_wrap(
        "[method]span.set-attribute",
        move |mut ctx: StoreContextMut<'_, Host>,
              (span_res, attr_name, attr_value): (
            wasmtime::component::Resource<GolemSpan>,
            String,
            AttributeValue,
        )|
              -> Result<(), wasmtime::Error> {
            let spans = ctx
                .data()
                .golem_spans
                .clone()
                .expect("Golem span host requires an instance-local span collection");
            let value_str = match &attr_value {
                AttributeValue::String(s) => s.clone(),
            };
            let resource_rep = span_res.rep();
            let mut table = ctx.data_mut().table.lock().unwrap();
            if let Ok(span) = table.get_mut(&span_res) {
                span.attributes.push((attr_name.clone(), value_str.clone()));
            }
            let mut shared = spans.lock().unwrap();
            if let Some(recorded) = shared
                .iter_mut()
                .rev()
                .find(|span| span.resource_rep == Some(resource_rep))
            {
                recorded.attributes.push((attr_name, value_str));
            }
            Ok(())
        },
    )?;

    // [method]span.finish: func()
    golem_ctx.func_wrap(
        "[method]span.finish",
        move |mut ctx: StoreContextMut<'_, Host>,
              (span_res,): (wasmtime::component::Resource<GolemSpan>,)|
              -> Result<(), wasmtime::Error> {
            let spans = ctx
                .data()
                .golem_spans
                .clone()
                .expect("Golem span host requires an instance-local span collection");
            let resource_rep = span_res.rep();
            let mut table = ctx.data_mut().table.lock().unwrap();
            if let Ok(span) = table.get_mut(&span_res) {
                span.finished = true;
                let name = span.name.clone();
                let attributes = span.attributes.clone();
                let mut shared = spans.lock().unwrap();
                if let Some(recorded) = shared
                    .iter_mut()
                    .rev()
                    .find(|span| span.resource_rep == Some(resource_rep))
                {
                    recorded.name = name;
                    recorded.finished = true;
                    recorded.attributes = attributes;
                }
            }
            Ok(())
        },
    )?;

    Ok(())
}

/// Add the functional `golem:websocket/client@1.5.0` mock.
///
/// Connections close cleanly on receive and sent frames remain instance-local for exact assertions.
fn add_websocket_client_mock(linker: &mut Linker<Host>) -> anyhow::Result<()> {
    ws_mock_p3::golem::websocket::client::add_to_linker::<Host, HasSelf<Host>>(linker, |host| {
        host
    })?;
    Ok(())
}

// Based on https://github.com/bytecodealliance/wac/blob/release-0.6.0/crates/wac-graph/src/plug.rs#L23
// but instead of returning NoPlugError, it logs skipped instantiations
fn plug(
    graph: &mut CompositionGraph,
    plugs: Vec<(String, PackageId)>,
    socket: PackageId,
) -> Result<(), PlugError> {
    let socket_instantiation = graph.instantiate(socket);

    let mut requested_plugs = BTreeSet::<String>::new();
    let mut plug_exports_to_plug = BTreeMap::<String, String>::new();

    for (plug_name, plug) in plugs {
        requested_plugs.insert(plug_name.clone());

        let mut plug_exports = Vec::new();
        let mut cache = Default::default();
        let mut checker = SubtypeChecker::new(&mut cache);
        for (name, plug_ty) in &graph.types()[graph[plug].ty()].exports {
            if let Some(socket_ty) = graph.types()[graph[socket].ty()].imports.get(name)
                && checker
                    .is_subtype(*plug_ty, graph.types(), *socket_ty, graph.types())
                    .is_ok()
            {
                plug_exports.push(name.clone());
            }
        }

        // Instantiate the plug component
        let mut plug_instantiation = None;
        for plug_export_name in plug_exports {
            plug_exports_to_plug.insert(plug_export_name.clone(), plug_name.clone());

            let plug_instantiation =
                *plug_instantiation.get_or_insert_with(|| graph.instantiate(plug));
            let export = graph
                .alias_instance_export(plug_instantiation, &plug_export_name)
                .map_err(|err| PlugError::GraphError { source: err.into() })?;
            graph
                .set_instantiation_argument(socket_instantiation, &plug_export_name, export)
                .map_err(|err| PlugError::GraphError { source: err.into() })?;
        }
    }

    // Export all exports from the socket component.
    for name in graph.types()[graph[socket].ty()]
        .exports
        .keys()
        .cloned()
        .collect::<Vec<_>>()
    {
        let export = graph
            .alias_instance_export(socket_instantiation, &name)
            .map_err(|err| PlugError::GraphError { source: err.into() })?;

        graph
            .export(export, &name)
            .map_err(|err| PlugError::GraphError { source: err.into() })?;
    }

    Ok(())
}

/// Classify a test filename into a module category based on its name prefix.
pub fn classify_test(filename: &str) -> &str {
    // Strip "test-" prefix
    let name = filename
        .strip_prefix("test-")
        .unwrap_or(filename)
        .strip_suffix(".js")
        .unwrap_or(filename);

    if name.starts_with("path") {
        "path"
    } else if name.starts_with("assert") {
        "assert"
    } else if name.starts_with("buffer") {
        "buffer"
    } else if name.starts_with("stream") {
        "stream"
    } else if name.starts_with("string-decoder") || name.starts_with("stringdecoder") {
        "string_decoder"
    } else if name.starts_with("url") {
        "url"
    } else if name.starts_with("util") {
        "util"
    } else if name.starts_with("querystring") {
        "querystring"
    } else if name.starts_with("events") || name.starts_with("event-emitter") {
        "events"
    } else if name.starts_with("fs") || name.starts_with("file") {
        "fs"
    } else if name.starts_with("crypto") {
        "crypto"
    } else if name.starts_with("http") || name.starts_with("http2") || name.starts_with("https") {
        "http"
    } else if name.starts_with("net") {
        "net"
    } else if name.starts_with("dns") {
        "dns"
    } else if name.starts_with("os") {
        "os"
    } else if name.starts_with("process") {
        "process"
    } else if name.starts_with("child-process") || name.starts_with("child_process") {
        "child_process"
    } else if name.starts_with("tls") || name.starts_with("ssl") {
        "tls"
    } else if name.starts_with("zlib") {
        "zlib"
    } else if name.starts_with("console") {
        "console"
    } else if name.starts_with("timers")
        || name.starts_with("settimeout")
        || name.starts_with("setinterval")
        || name.starts_with("setimmediate")
    {
        "timers"
    } else if name.starts_with("worker") || name.starts_with("worker-threads") {
        "worker_threads"
    } else if name.starts_with("cluster") {
        "cluster"
    } else if name.starts_with("readline") {
        "readline"
    } else if name.starts_with("repl") {
        "repl"
    } else if name.starts_with("vm") {
        "vm"
    } else if name.starts_with("dgram") {
        "dgram"
    } else if name.starts_with("tty") {
        "tty"
    } else if name.starts_with("async-hooks")
        || name.starts_with("async-context")
        || name.starts_with("async-local-storage")
    {
        "async_hooks"
    } else if name.starts_with("inspector") || name.starts_with("debugger") {
        "inspector"
    } else if name.starts_with("module")
        || name.starts_with("require")
        || name.starts_with("esm")
        || name.starts_with("cjs")
        || name.starts_with("loaders")
    {
        "module"
    } else if name.starts_with("perf") || name.starts_with("performance") {
        "perf_hooks"
    } else if name.starts_with("diagnostics") {
        "diagnostics_channel"
    } else if name.starts_with("domain") {
        "domain"
    } else if name.starts_with("v8") {
        "v8"
    } else if name.starts_with("trace") {
        "trace_events"
    } else if name.starts_with("runner") || name.starts_with("test-runner") {
        "test_runner"
    } else if name.starts_with("abortcontroller")
        || name.starts_with("abortsignal")
        || name.starts_with("aborted")
    {
        "abort"
    } else if name.starts_with("encoding")
        || name.starts_with("textdecoder")
        || name.starts_with("textencoder")
    {
        "encoding"
    } else if name.starts_with("blob") {
        "blob"
    } else if name.starts_with("fetch")
        || name.starts_with("response")
        || name.starts_with("request")
        || name.starts_with("headers")
    {
        "fetch"
    } else if name.starts_with("readable")
        || name.starts_with("writable")
        || name.starts_with("transform")
        || name.starts_with("duplex")
    {
        "stream"
    } else if name.starts_with("sqlite") {
        "sqlite"
    } else if name.starts_with("whatwg") {
        "whatwg"
    } else if name.starts_with("webcrypto") {
        "webcrypto"
    } else if name.starts_with("permission") {
        "permission"
    } else if name.starts_with("promise") || name.starts_with("promises") {
        "promises"
    } else if name.starts_with("global") {
        "global"
    } else if name.starts_with("compile") {
        "compile"
    } else if name.starts_with("cli") {
        "cli"
    } else if name.starts_with("stdin") || name.starts_with("stdout") || name.starts_with("stdio") {
        "stdio"
    } else if name.starts_with("signal") {
        "signal"
    } else if name.starts_with("errors") || name.starts_with("error") {
        "errors"
    } else if name.starts_with("pipe")
        || name.starts_with("socket")
        || name.starts_with("listen")
        || name.starts_with("tcp")
    {
        "net"
    } else if name.starts_with("webstream") || name.starts_with("webstreams") {
        "webstreams"
    } else if name.starts_with("snapshot") {
        "snapshot"
    } else if name.starts_with("eslint") {
        "eslint"
    } else if name.starts_with("internal") {
        "internal"
    } else if name.starts_with("heap") {
        "heap"
    } else if name.starts_with("node") {
        "node"
    } else if name.starts_with("inspect") {
        "inspector"
    } else if name.starts_with("shadow-realm") {
        "shadow_realm"
    } else if name.starts_with("btoa") || name.starts_with("atob") {
        "encoding"
    } else if name.starts_with("common") {
        "common"
    } else {
        "other"
    }
}

/// Check if a test file relies on Node.js internals (not public API).
///
/// Detects patterns like `// Flags: --expose-internals`, `require('internal/...')`,
/// and `internalBinding(...)` in the test source code.
fn uses_node_internals(suite_root: &std::path::Path, test_path: &str) -> anyhow::Result<bool> {
    let file_path = suite_root.join(test_path);
    let content = fs::read_to_string(&file_path).map_err(|error| {
        anyhow!(
            "cannot classify node-compat entry {test_path:?}: vendored source {} is unavailable: {error}; re-run ./tests/node_compat/vendor.sh",
            file_path.display()
        )
    })?;
    // Only check the first 50 lines for the Flags comment (it's always near the top)
    let header: String = content.lines().take(50).collect::<Vec<_>>().join("\n");
    if header.contains("--expose-internals") {
        return Ok(true);
    }
    // Check the full file for internal requires/bindings
    Ok(content.contains("require('internal/")
        || content.contains("require(\"internal/")
        || content.contains("internalBinding("))
}