polyplug_js 0.1.1

QuickJS loader for polyplug - loads JavaScript plugins via QuickJS
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
//! QuickJS in-process plugin loader implementation.
//!
//! Loads JS plugin bundles via the embedded QuickJS VM (rquickjs).
//! Each bundle gets its own QuickJS Runtime and Context for complete isolation
//! between bundles and between polyplug Runtime instances.
//! Uses VM dispatch to call JS functions through the QuickJS API.

use core::sync::atomic::AtomicU64;
use core::sync::atomic::Ordering;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::thread::ThreadId;

use rquickjs::Array;
use rquickjs::Context;
use rquickjs::Ctx;
use rquickjs::Function;
use rquickjs::Object;
use rquickjs::Persistent;
use rquickjs::Runtime;
use rquickjs::Value;

use polyplug::Runtime as PolyplugRuntime;
use polyplug::error::LoaderError;
use polyplug::loader::BundleLoader;
use polyplug::loader::BundleSource;
use polyplug::loader::ManifestData;
use polyplug::logger::LoggerHandle;
use polyplug_abi::AbiError;
use polyplug_abi::AbiErrorCode;
use polyplug_abi::BundleInitContext;
use polyplug_abi::CallArena;
use polyplug_abi::DispatchType;
use polyplug_abi::GuestContractHandle;
use polyplug_abi::GuestContractInstance;
use polyplug_abi::GuestContractInterface;
use polyplug_abi::HostApi;
use polyplug_abi::HostContractInstance;
use polyplug_abi::HostContractInterface;
use polyplug_abi::PluginDescriptor;
use polyplug_abi::StringView;
use polyplug_abi::SupportedLanguage;
use polyplug_abi::VmLoaderData;
use polyplug_abi::dispatch::dispatch_mechanisms::DispatchMechanisms;
use polyplug_abi::dispatch::vm_dispatch::VmDispatch;
use polyplug_abi::types::LogLevel;
use polyplug_abi::types::Version;
use polyplug_utils::BundleId;
use polyplug_utils::GuestContractId;

use crate::config::JsConfig;

// ─── Registration data returned by polyplug_init ──────────────────────────────

/// Registration data extracted from `polyplug_init`'s return value.
///
/// `polyplug_init` RETURNS `[registrations, abiError]` (nothing is deposited into
/// any global or VM userdata — Rule 12); the loader reads `registrations[0]` and
/// extracts these fields. The `Persistent` values are `'static`, so they travel
/// out of the `Context::with` closure that built them.
struct JsRegistrationData {
    contract_id: u64,
    contract_version: u32,
    contract_name: String,
    functions: Vec<Persistent<Function<'static>>>,
    /// Factory that builds a fresh impl object. The loader calls it once at load
    /// to build the stateless default impl and once per `create_instance` for a
    /// live per-instance impl, threading the bridge + host vtable explicitly.
    factory: Persistent<Function<'static>>,
}

// ─── JS Loader Data for VM Dispatch ───────────────────────────────────────────

/// Loader-specific data for JS plugin dispatch.
///
/// Each bundle gets its own QuickJS Runtime and Context, ensuring complete
/// isolation between bundles and between polyplug Runtime instances.
/// The Context is cached for fast dispatch without per-call creation overhead.
///
/// # Field drop order
/// Rust drops fields in declaration order, and QuickJS's `JS_FreeRuntime` asserts
/// that every JS object (the `Persistent<Function>`s, the `Persistent<Value>` impls,
/// and the `Context`) is already freed when the `Runtime` is dropped. Every
/// JS-holding field (`functions`, `factory`, `default_impl`, `instances`, `ctx`) is
/// therefore declared BEFORE `_runtime` so they drop first; reordering them would
/// re-introduce a `JS_FreeRuntime: Assertion 'list_empty(&rt->gc_obj_list)' failed`
/// abort when a bundle's VM is reclaimed on unload.
pub struct JsLoaderData {
    pub functions: Vec<Persistent<Function<'static>>>,
    /// Factory producing a fresh impl object per `create_instance`. Restored under
    /// `Context::with` and called with `(bridge, host_lo, host_hi)` — the bridge and
    /// host vtable are threaded explicitly (no per-VM global — Rule 12), so the
    /// factory's impl can capture them.
    pub factory: Persistent<Function<'static>>,
    /// The host-capability bridge object the loader builds at load time and threads
    /// explicitly into `polyplug_init`, every dispatch call, and each factory call —
    /// it is NEVER set on `globalThis` (Rule 12). Restored under `Context::with`.
    /// Declared BEFORE `_runtime` so it drops before the QuickJS `Runtime` (see the
    /// field-drop-order note above).
    pub bridge: Persistent<Object<'static>>,
    /// HostApi pointer split into f64 lo/hi halves, threaded to each factory call so
    /// the guest impl can store it and reach host-contract / peer callers. f64 avoids
    /// rquickjs sign-extending a u32 > INT32_MAX to a negative tagged int.
    pub host_lo: f64,
    pub host_hi: f64,
    /// Stateless default impl, built once at load via the factory. Serves dispatch
    /// on a null (id 0) instance handle so low-level / host-caller dispatch with a
    /// null instance still resolves an impl.
    pub default_impl: Persistent<Value<'static>>,
    /// Live per-instance impls keyed by their non-zero id (the value carried in a
    /// `GuestContractInstance` handle's `data` field). Two live instances of the
    /// same contract therefore never share state.
    pub instances: Mutex<HashMap<u64, Persistent<Value<'static>>>>,
    /// Next instance id to mint. Starts at 1 so a handle's `data` is never null
    /// (`GuestContractInstance::is_null` keys on `data`).
    pub next_id: AtomicU64,
    /// Contract id this VM provides — stamped into every instance handle so a
    /// cross-call routes by it.
    pub contract_id: u64,
    pub ctx: Context,
    pub _runtime: Runtime,
    /// Thread-aware same-VM reentrancy guard for [`js_dispatch`].
    ///
    /// rquickjs is built with the `parallel` feature, so a `Context` is reachable
    /// from any thread and is internally lock-guarded. Two cases must be told
    /// apart, and a plain `AtomicBool` cannot distinguish them:
    ///
    /// 1. SAME-thread nested dispatch — a plugin→plugin cross-call that resolves
    ///    back to a contract in THIS
    ///    same Context while this thread is already mid-dispatch. That would call
    ///    `Context::with` recursively on the same context on the same thread, which
    ///    rquickjs panics/aborts on. This MUST be refused with `ReentrantCall`
    ///    BEFORE `Context::with` is entered.
    /// 2. CROSS-thread concurrent dispatch — a different thread dispatches into
    ///    this Context while a dispatch is in flight on another thread. rquickjs
    ///    serializes this safely by blocking on its internal lock, matching the
    ///    HostApi contract ("safe to call from any thread; the runtime handles
    ///    internal synchronization"). This MUST proceed and be allowed to block.
    ///
    /// The set of thread ids currently inside a dispatch on this Context captures
    /// exactly that distinction: presence of the current thread's id means a
    /// same-thread nested call (refuse); absence means a fresh caller — possibly
    /// from another thread concurrently — which proceeds. It lives on the per-VM
    /// `JsLoaderData`, never globally, so it is Rule-12 compliant. Contention is
    /// trivial: the vec holds 0..N concurrent caller threads and never duplicates.
    pub in_dispatch_threads: Mutex<Vec<ThreadId>>,
    /// Instance-owned copy of the runtime's logger, taken at load time.
    ///
    /// Dispatch-time diagnostics have no `&Runtime` back-reference, so the
    /// per-VM data carries its own `Copy` of the handle. Same callback
    /// contract as `RuntimeConfig::log` — never invoked under a lock guard.
    pub logger: LoggerHandle,
}

/// Owning, thread-shareable handle to a bundle's [`JsLoaderData`].
///
/// `JsLoaderData` is `!Send`/`!Sync` because `Persistent<Function>` carries a raw
/// `*mut JSRuntime`. The previous design laundered this by leaking the box behind a
/// raw `*mut c_void` inside `VmLoaderData`; this newtype instead owns the box so it
/// can be dropped on unload, while restoring `Send + Sync` so the loader's `live`
/// collection (and therefore `JsLoader`) stays `Send + Sync` and a box can be moved
/// into the `Send + 'static` epoch-deferred reclaim closure on unload.
///
/// The pointer stored in the dispatch `bridge_data` is `self.0`'s stable heap
/// address; it is dereferenced only inside `js_dispatch`, which enters
/// `Context::with`. rquickjs is built with the `parallel` feature, so every VM
/// access serializes on the runtime's internal lock — exactly the invariant the
/// cross-thread dispatch path already relies on.
struct SendVm(Box<JsLoaderData>);

// SAFETY: every access to the wrapped JsLoaderData's VM goes through `Context::with`
// (in js_dispatch) or the bundle's own `in_dispatch_threads` Mutex (in unload).
// rquickjs's `parallel` feature serializes all VM operations on the runtime's
// internal lock, so moving ownership of the box between threads and sharing `&SendVm`
// across threads never produces concurrent unsynchronized VM access. This is the same
// soundness the existing cross-thread `js_dispatch` path depends on.
unsafe impl Send for SendVm {}
// SAFETY: see the Send impl — VM access is serialized by rquickjs's internal lock and
// the per-bundle in_dispatch_threads Mutex, so shared references are sound.
unsafe impl Sync for SendVm {}

impl SendVm {
    /// The stable heap address of the wrapped [`JsLoaderData`], used as the dispatch
    /// `bridge_data`. Stable across moves of the `SendVm`/`Box` while owned.
    fn as_ptr(&self) -> *const JsLoaderData {
        &*self.0 as *const JsLoaderData
    }

    /// Borrow the wrapped [`JsLoaderData`] (e.g. to inspect `in_dispatch_threads`).
    ///
    /// Test-only since unload became uniform epoch-deferred reclaim: production code no
    /// longer inspects per-VM state at unload time (the epoch governs liveness), so the
    /// only remaining caller is the in-flight-marking unit test.
    #[cfg(test)]
    fn data(&self) -> &JsLoaderData {
        &self.0
    }
}

/// RAII guard that removes the current thread's id from
/// [`JsLoaderData::in_dispatch_threads`] on every exit path, including panics
/// that unwind through `js_dispatch`.
struct JsDispatchGuard<'a> {
    threads: &'a Mutex<Vec<ThreadId>>,
}

impl Drop for JsDispatchGuard<'_> {
    fn drop(&mut self) {
        let this: ThreadId = std::thread::current().id();
        // Recover from poisoning: a panic in another dispatch may have poisoned
        // the lock, but the data is a plain Vec<ThreadId> that cannot be left
        // logically corrupt between lock/unlock, so reusing the inner value is
        // sound. This is production code, so we never unwrap.
        let mut guard: std::sync::MutexGuard<'_, Vec<ThreadId>> =
            self.threads.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(pos) = guard.iter().position(|&id| id == this) {
            guard.swap_remove(pos);
        }
    }
}

// ─── JS Dispatch Function ─────────────────────────────────────────────────────

// ─── Instance Lifecycle ─────────────────────────────────────────────────────────

/// Create a fresh JS contract instance by running the bundle's factory.
///
/// Runs `factory()` inside the VM, persists the returned impl object, mints a
/// non-zero id, keys the impl under it in the per-contract registry, and stamps the
/// `GuestContractInstance` handle with that id + the contract id. Two instances of
/// the same contract therefore never share state.
///
/// # Safety
/// - `loader_data`, when non-null, must wrap a valid pointer to a [`JsLoaderData`]
///   created by the loader (its box address is stable for as long as the bundle is
///   loaded).
/// - `out_instance`, when non-null, must be writable per the ABI contract.
unsafe extern "C" fn js_create_instance(
    loader_data: VmLoaderData,
    _host: *const HostApi,
    _args: *const (),
    out_instance: *mut GuestContractInstance,
) {
    if out_instance.is_null() {
        return;
    }
    // A null loader_data carries no contract to build an instance for (e.g. a peer
    // caller that constructs a zeroed VmLoaderData and routes by stamping the
    // contract id afterward). Write a null instance and return rather than deref a
    // null pointer.
    if loader_data.data.is_null() {
        // SAFETY: out_instance is non-null (checked above) and writable per the ABI contract.
        unsafe { out_instance.write(GuestContractInstance::null()) };
        return;
    }
    // SAFETY: loader_data wraps a valid JsLoaderData pointer created by the loader
    // (non-null checked above); its box address stays valid for as long as the
    // bundle is loaded.
    let data: &JsLoaderData = unsafe { &*(loader_data.data as *const JsLoaderData) };

    // Refuse a same-thread nested create: running the factory would re-enter
    // QuickJS's `Context::with` on this VM already entered by the in-flight dispatch
    // on this thread, which rquickjs aborts on. There is no error out-param here, so
    // write a null instance (the caller routes by stamped contract id → default impl).
    let this_thread: ThreadId = std::thread::current().id();
    {
        // Poison recovery: the Vec<ThreadId> cannot be left logically corrupt
        // between lock/unlock, so reusing it is sound. Production code, no unwrap.
        let threads: std::sync::MutexGuard<'_, Vec<ThreadId>> = data
            .in_dispatch_threads
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if threads.contains(&this_thread) {
            drop(threads);
            // SAFETY: out_instance is non-null (checked above) and writable per the ABI contract.
            unsafe { out_instance.write(GuestContractInstance::null()) };
            return;
        }
    }

    let built: Result<Persistent<Value<'static>>, rquickjs::Error> = data.ctx.with(|ctx| {
        let factory: Function<'_> = data.factory.clone().restore(&ctx)?;
        // Thread the bridge + host vtable lo/hi explicitly (no per-VM global — Rule 12)
        // so the per-instance impl can capture them and reach host-contract / peer callers.
        let bridge: Object<'_> = data.bridge.clone().restore(&ctx)?;
        let impl_val: Value<'_> = factory.call::<(Object<'_>, f64, f64), Value<'_>>((
            bridge,
            data.host_lo,
            data.host_hi,
        ))?;
        Ok(Persistent::save(&ctx, impl_val))
    });

    let instance: GuestContractInstance = match built {
        Ok(impl_persistent) => {
            let id: u64 = data.next_id.fetch_add(1, Ordering::Relaxed);
            // Poison recovery: a poisoned registry between lock/unlock leaves the
            // HashMap usable. Production code, no unwrap.
            let mut map: std::sync::MutexGuard<'_, HashMap<u64, Persistent<Value<'static>>>> = data
                .instances
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            map.insert(id, impl_persistent);
            GuestContractInstance {
                data: id as usize as *mut core::ffi::c_void,
                contract_id: GuestContractId::from_u64(data.contract_id),
            }
        }
        Err(e) => {
            data.logger.log(LogLevel::Error, "loader.js", || {
                format!("JS create_instance: factory call failed: {e}")
            });
            GuestContractInstance::null()
        }
    };

    // SAFETY: out_instance is non-null (checked above) and writable per the ABI contract.
    unsafe { out_instance.write(instance) };
}

/// Destroy a JS contract instance.
///
/// Removes the impl keyed under the instance handle's id from the per-contract
/// registry, dropping its `Persistent`. A null handle (id 0) refers to the stateless
/// default impl, which the loader owns for the bundle lifetime, so it is a no-op.
///
/// # Safety
/// - `loader_data`, when non-null, must wrap a valid pointer to a [`JsLoaderData`]
///   created by the loader.
/// - `instance` must be a handle previously produced by [`js_create_instance`] for
///   this contract (or a null handle).
unsafe extern "C" fn js_destroy_instance(
    loader_data: VmLoaderData,
    _host: *const HostApi,
    instance: GuestContractInstance,
) {
    let id: u64 = instance.data as usize as u64;
    if id == 0 {
        return;
    }
    // A null loader_data carries no per-contract registry to remove from (e.g. a
    // peer caller that passes a zeroed VmLoaderData). Nothing to drop.
    if loader_data.data.is_null() {
        return;
    }
    // SAFETY: loader_data wraps a valid JsLoaderData pointer created by the loader
    // (non-null checked above); its box address stays valid for as long as the
    // bundle is loaded.
    let data: &JsLoaderData = unsafe { &*(loader_data.data as *const JsLoaderData) };
    // Poison recovery: a poisoned registry between lock/unlock leaves the HashMap
    // usable. Production code, no unwrap. Dropping the removed Persistent releases the
    // JS ref through rquickjs's runtime (no Context::with required).
    let mut map: std::sync::MutexGuard<'_, HashMap<u64, Persistent<Value<'static>>>> = data
        .instances
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    map.remove(&id);
}

// ─── JS Dispatch Function ─────────────────────────────────────────────────────

/// Dispatch function for JS plugins using VM dispatch pattern.
///
/// # Safety
/// - `loader_data` must be a valid VmLoaderData wrapping JsLoaderData
/// - `args` and `out` must be valid pointers for the ABI call
/// - `arena`, when non-null, must point to a valid [`CallArena`] reset by the
///   caller for this call. Values written by the guest into the arena (via
///   `polyplug.arenaAlloc`) are valid until the caller's next reset.
unsafe extern "C" fn js_dispatch(
    loader_data: VmLoaderData,
    instance: GuestContractInstance,
    fn_id: u32,
    args: *const (),
    out: *mut (),
    arena: *mut CallArena,
    out_err: *mut AbiError,
) {
    // SAFETY: loader_data wraps a valid pointer to JsLoaderData created by the
    // loader; args/out/arena satisfy the ABI dispatch contract for this call.
    let result: AbiError =
        unsafe { js_dispatch_impl(loader_data, instance, fn_id, args, out, arena) };
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe { out_err.write(result) };
    }
}

unsafe fn js_dispatch_impl(
    loader_data: VmLoaderData,
    instance: GuestContractInstance,
    fn_id: u32,
    args: *const (),
    out: *mut (),
    arena: *mut CallArena,
) -> AbiError {
    // SAFETY: loader_data wraps a valid pointer to JsLoaderData created by the loader.
    let data: &JsLoaderData = unsafe { &*(loader_data.data as *const JsLoaderData) };

    // Reject ONLY same-thread nested reentrancy BEFORE entering Context::with. If
    // this thread is already inside a dispatch on this Context (a plugin→plugin
    // cross-call resolving back here), a nested Context::with on the same thread
    // would abort, so refuse with ReentrantCall. A different thread dispatching
    // concurrently is NOT reentrancy: it is allowed to proceed and rquickjs's
    // internal lock serializes it safely. The tracking Mutex is held only around
    // the membership check/insert below, never across Context::with.
    let this_thread: ThreadId = std::thread::current().id();
    {
        // Recover from poisoning (a prior dispatch panic): the Vec<ThreadId>
        // cannot be left logically corrupt between lock/unlock, so the inner
        // value is reusable. Production code, so no unwrap.
        let mut threads: std::sync::MutexGuard<'_, Vec<ThreadId>> = data
            .in_dispatch_threads
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if threads.contains(&this_thread) {
            // Drop the guard (unlock) before returning.
            drop(threads);
            return AbiError {
                code: AbiErrorCode::ReentrantCall as u32,
                message: StringView::null(),
            };
        }
        threads.push(this_thread);
    }
    // From here on this thread's id is registered; the guard removes it on every
    // exit path (early return, normal return, or panic unwind).
    let _dispatch_guard: JsDispatchGuard<'_> = JsDispatchGuard {
        threads: &data.in_dispatch_threads,
    };

    let func_persistent: &Persistent<Function<'static>> = match data.functions.get(fn_id as usize) {
        Some(f) => f,
        None => {
            return AbiError {
                code: AbiErrorCode::FunctionNotAvailable as u32,
                message: StringView::null(),
            };
        }
    };

    // Resolve the impl for this instance: a null handle (id 0) uses the stateless
    // default impl; otherwise look the live instance up by id. The Persistent is
    // cloned OUT of the registry so the map guard drops before Context::with — a
    // nested dispatch can never deadlock on the registry mutex.
    let instance_id: u64 = instance.data as usize as u64;
    let impl_persistent: Persistent<Value<'static>> = if instance_id == 0 {
        data.default_impl.clone()
    } else {
        // Poison recovery: the HashMap cannot be left logically corrupt between
        // lock/unlock, so reusing it is sound. Production code, no unwrap.
        let map: std::sync::MutexGuard<'_, HashMap<u64, Persistent<Value<'static>>>> = data
            .instances
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        match map.get(&instance_id) {
            Some(p) => p.clone(),
            None => {
                return AbiError {
                    code: AbiErrorCode::FunctionNotAvailable as u32,
                    message: StringView::null(),
                };
            }
        }
    };

    let args_usize: usize = args as usize;
    let out_usize: usize = out as usize;

    // Pass pointers as f64. User-space addresses fit within 2^48 < 2^53 (float64 mantissa),
    // so the conversion from usize → f64 → usize is exact on all supported platforms.
    // The generated JS wrapper receives plain Number arguments and passes them directly
    // to readU32/writeU32, which also accept f64 — no BigInt conversion needed.
    let args_f64: f64 = args_usize as f64;
    let out_f64: f64 = out_usize as f64;

    let arena_usize: usize = arena as usize;
    // Pass the per-call arena pointer as a Number argument (NOT published into any VM
    // global — Rule 12). User-space addresses fit within 2^48 < 2^53, so usize → f64
    // → usize is exact; the generated wrapper threads it to bridge.arenaAlloc(size,
    // arena_ptr) for StringView returns.
    let arena_f64: f64 = arena_usize as f64;

    let call_result: Result<i32, rquickjs::Error> = data.ctx.with(|ctx| {
        let js_fn: Function<'_> = func_persistent.clone().restore(&ctx)?;
        // The generated wrapper takes (impl, args_ptr, out_ptr, arena_ptr, bridge):
        // the per-instance impl object is passed first so the wrapper invokes the
        // method on it; the per-call arena pointer and the host-capability bridge are
        // threaded as explicit arguments — nothing is read from or written to any VM
        // global (Rule 12), so concurrent / same-VM reentrant dispatch stay correct.
        let impl_val: Value<'_> = impl_persistent.clone().restore(&ctx)?;
        let bridge: Object<'_> = data.bridge.clone().restore(&ctx)?;

        js_fn.call::<(Value<'_>, f64, f64, f64, Object<'_>), i32>((
            impl_val, args_f64, out_f64, arena_f64, bridge,
        ))
    });

    match call_result {
        Ok(0) => AbiError::ok(),
        Ok(code) => AbiError {
            // AbiError.code is a raw u32, so the plugin-provided code is stored
            // verbatim — no enum materialization, hence no UB on unknown values.
            code: code as u32,
            message: StringView::null(),
        },
        Err(e) => {
            // Context::with has returned, so the QuickJS VM lock is released and
            // no loader lock guard is held — safe to invoke the host logger.
            data.logger.log(LogLevel::Error, "loader.js", || {
                format!("JS function call failed: {e}")
            });
            AbiError {
                code: AbiErrorCode::Generic as u32,
                message: StringView::null(),
            }
        }
    }
}

// ─── Host function registration ───────────────────────────────────────────────

fn pack_handle(h: GuestContractHandle) -> Option<u64> {
    if h.is_null() {
        None
    } else {
        // Carry the full handle identity (generation in the high 32 bits, index in
        // the low 32) so a JS-held token round-trips back to the exact slot+generation
        // and stale handles are detected on resolve. Mirrors GuestContractHandle::pack.
        Some(h.pack())
    }
}

/// Reconstruct a `*const HostApi` from the captured host address, or `None` if null.
///
/// The bridge closures capture the host pointer as a `usize` (a `Copy`/`Send`
/// value) at registration time and reconstruct it here per call — the host
/// pointer is threaded explicitly, never read from a VM global (Rule 12).
fn host_from_usize(addr: usize) -> Option<*const HostApi> {
    let ptr: *const HostApi = addr as *const HostApi;
    if ptr.is_null() { None } else { Some(ptr) }
}

/// Destroy a host-contract instance obtained from `get_host_contract` when the
/// contract is NOT a singleton.
///
/// `get_host_contract` mints a fresh instance per call for multi-instance
/// contracts; the caller owns it and must destroy it or it leaks. Singleton
/// contracts return a runtime-cached instance that must never be destroyed here.
///
/// # Safety
/// `iface` must be the valid, non-null `HostContractInterface` pointer that produced
/// `instance`; `instance` must be the value just returned by `get_host_contract` for
/// this `iface`.
unsafe fn destroy_host_instance_if_needed(
    iface: *const HostContractInterface,
    singleton: bool,
    instance: HostContractInstance,
) {
    if singleton {
        return;
    }
    // SAFETY: iface is a valid non-null HostContractInterface pointer (checked by the
    // caller); destroy_instance follows the self-passing ABI (its first argument is the
    // interface pointer), and `instance` is the value get_host_contract returned for it.
    unsafe { ((*iface).destroy_instance)(iface, instance) };
}

fn register_host_functions<'js>(
    ctx: &Ctx<'js>,
    polyplug_obj: &Object<'js>,
    host_interface: *const HostApi,
    bundle_name: &str,
    logger: LoggerHandle,
) -> Result<(), LoaderError> {
    // Capture the host pointer as a usize: raw pointers are not Send, but the pointee
    // is a 'static HostApi for the runtime lifetime, so each bridge closure can `move`
    // this Copy value in and reconstruct the pointer per call — the host pointer is
    // threaded explicitly, never set on a VM global (Rule 12).
    let host_interface_usize: usize = host_interface as usize;

    let find_by_contract_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |_ctx: Ctx<'js>, lo: u32, hi: u32, min_ver: u32| -> Option<u64> {
            let contract_id: u64 = (hi as u64) << 32 | lo as u64;
            let hvt: *const HostApi = host_from_usize(host_interface_usize)?;
            // SAFETY: hvt points to 'static HostApi data.
            let handle: GuestContractHandle =
                unsafe { ((*hvt).find_guest_contract)(hvt, contract_id, min_ver) };
            pack_handle(handle)
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: findByContract function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("findByContract", find_by_contract_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: findByContract set failed: {e}"),
        })?;

    let find_by_bundle_fn: Function<'js> = Function::new(
        ctx.clone(),
        |_ctx: Ctx<'js>,
         _blo: u32,
         _bhi: u32,
         _clo: u32,
         _chi: u32,
         _min_ver: u32|
         -> Option<u64> {
            // Note: find_by_bundle was removed from HostApi in the instance-based model.
            // Use find_guest_contract instead.
            None
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: findByBundle function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("findByBundle", find_by_bundle_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: findByBundle set failed: {e}"),
        })?;

    let find_all_by_contract_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |_ctx: Ctx<'js>, lo: u32, hi: u32, min_ver: u32| -> u32 {
            let contract_id: u64 = (hi as u64) << 32 | lo as u64;
            let hvt: *const HostApi = match host_from_usize(host_interface_usize) {
                Some(ptr) => ptr,
                None => return 0_u32,
            };
            // SAFETY: hvt points to 'static HostApi data.
            // find_all_guest_contracts returns Array<GuestContractHandle>.
            let handles: polyplug_abi::types::Array<GuestContractHandle> =
                unsafe { ((*hvt).find_all_guest_contracts)(hvt, contract_id, min_ver) };
            handles.len as u32
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!(
            "JS runtime js-quickjs error: findAllByContract function creation failed: {e}"
        ),
    })?;

    polyplug_obj
        .set("findAllByContract", find_all_by_contract_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: findAllByContract set failed: {e}"),
        })?;

    let resolve_guest_contract_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |_ctx: Ctx<'js>, packed: u64| -> Option<u64> {
            // Unpack the full handle identity: index in the low 32 bits, generation
            // in the high 32 (matches pack_handle / GuestContractHandle::pack).
            let index: u32 = packed as u32;
            let generation: u32 = (packed >> 32) as u32;
            let handle: GuestContractHandle = GuestContractHandle { index, generation };
            let hvt: *const HostApi = host_from_usize(host_interface_usize)?;
            // SAFETY: hvt points to 'static HostApi data.
            let vtable_ptr: *const GuestContractInterface =
                unsafe { ((*hvt).resolve_guest_contract)(hvt, handle) };
            if vtable_ptr.is_null() {
                None
            } else {
                Some(vtable_ptr as usize as u64)
            }
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!(
            "JS runtime js-quickjs error: resolveGuestContract function creation failed: {e}"
        ),
    })?;

    polyplug_obj
        .set("resolveGuestContract", resolve_guest_contract_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: resolveGuestContract set failed: {e}"),
        })?;

    // ── revision ─────────────────────────────────────────────────────────────────
    // Reads the runtime's monotonic registry revision counter (HostApi.revision_counter)
    // with Acquire ordering and returns its current u64 value as [lo, hi] f64 halves
    // (matching alloc/arenaAlloc — QuickJS numbers cannot carry a full u64 exactly).
    // A generated peer caller compares this against the value cached at resolve time:
    // a change means a load/reload/unload republished the registry, so the cached peer
    // interface and instance may dangle and must be re-resolved before the next dispatch.
    // QuickJS cannot deref the raw `*const u64`, so the read happens here on the Rust
    // side; one bridge call per dispatch is negligible against microsecond VM dispatch.
    let revision_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |ctx: Ctx<'js>| -> Result<Array<'js>, rquickjs::Error> {
            let value: u64 = match host_from_usize(host_interface_usize) {
                Some(hvt) => {
                    // SAFETY: hvt points to 'static HostApi data; revision_counter is an ABI
                    // function pointer satisfied by passing hvt as the self argument.
                    let ptr: *const u64 = unsafe { ((*hvt).revision_counter)(hvt) };
                    if ptr.is_null() {
                        0_u64
                    } else {
                        // SAFETY: ptr was returned by revision_counter and points to the
                        // runtime's revision counter — an AtomicU64 valid for the runtime's
                        // lifetime. Acquire mirrors the host-side store ordering.
                        unsafe { (*(ptr as *const AtomicU64)).load(Ordering::Acquire) }
                    }
                }
                None => 0_u64,
            };
            let arr: Array<'js> = Array::new(ctx.clone())
                .map_err(|_| rquickjs::Exception::throw_message(&ctx, "array creation failed"))?;
            // Store as f64 halves: rquickjs sign-extends u32 > INT32_MAX to negative JS
            // ints, which corrupts the value; f64 preserves each 32-bit half exactly.
            let _ = arr.set(0, (value as u32) as f64);
            let _ = arr.set(1, ((value >> 32) as u32) as f64);
            Ok(arr)
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: revision function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("revision", revision_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: revision set failed: {e}"),
        })?;

    // ── dispatchPeer ───────────────────────────────────────────────────────────
    // Guarded peer-call path: find → resolve → create_instance → DIRECT dispatch
    // → destroy_instance. The contract_id and min_version come from the generated
    // peer_callers.ts constants so the caller never hard-codes raw numbers.
    //
    // The loader resolves the peer interface itself (find_guest_contract +
    // resolve_guest_contract) and then dispatches DIRECTLY through that interface,
    // without re-entering the host to resolve the same interface a second time. The
    // dispatch logic branches on the resolved interface's dispatch_type (Native:
    // bounds-checked native function-pointer slot; VirtualMachine: vm.call).
    //
    // Per-call create+destroy: a fresh peer instance is built for the call and
    // destroyed after it. create_instance is handed the PEER's own loader_data
    // (read from the resolved interface) so a VM peer reaches its factory; a
    // same-VM peer's create is refused by the loader's reentrancy guard and falls
    // back to the default impl (routed by the stamped contract id).
    let dispatch_peer_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |_ctx: Ctx<'js>,
              contract_id_lo: u32,
              contract_id_hi: u32,
              min_version: u32,
              fn_id: u32,
              args_ptr: u64,
              out_ptr: u64|
              -> u32 {
            let contract_id: u64 = (contract_id_hi as u64) << 32 | contract_id_lo as u64;
            let hvt: *const HostApi = match host_from_usize(host_interface_usize) {
                Some(p) => p,
                None => return AbiErrorCode::Generic as u32,
            };
            // SAFETY: hvt is a valid 'static HostApi pointer stored by register_host_functions;
            // the self-passing ABI pattern is satisfied by passing hvt as the first argument.
            let handle: GuestContractHandle =
                unsafe { ((*hvt).find_guest_contract)(hvt, contract_id, min_version) };
            // SAFETY: hvt is valid (same guarantee as above); handle was just returned by
            // find_guest_contract so it is a well-formed GuestContractHandle.
            let iface: *const GuestContractInterface =
                unsafe { ((*hvt).resolve_guest_contract)(hvt, handle) };
            if iface.is_null() {
                return AbiErrorCode::NotFound as u32;
            }
            // The peer's own loader_data lets a VM peer's create_instance reach its
            // factory; a native peer ignores it. Passing null here (the old behaviour)
            // would force every VM peer onto its default impl.
            // SAFETY: iface is non-null (checked above); `dispatch_type` is a plain
            // field readable through a valid pointer.
            let peer_dt: DispatchType = unsafe { (*iface).dispatch_type };
            let peer_loader_data: VmLoaderData = match peer_dt {
                // SAFETY: iface is non-null; the `vm` union variant is active iff
                // dispatch_type == VirtualMachine, which this arm establishes.
                DispatchType::VirtualMachine => unsafe { (*iface).dispatch.vm.loader_data },
                DispatchType::Native => VmLoaderData::null(),
            };
            let mut instance: GuestContractInstance = GuestContractInstance::null();
            // SAFETY: iface is non-null and points to a valid GuestContractInterface
            // returned by resolve_guest_contract; null ctx is accepted for stateless contracts;
            // `instance` is a valid, writable out-param for the duration of the call.
            unsafe {
                ((*iface).create_instance)(peer_loader_data, hvt, core::ptr::null(), &mut instance)
            };
            // A same-VM peer create is refused (null-id handle); the VM dispatch path
            // routes by instance.contract_id — stamp the id we resolved either way.
            instance.contract_id = GuestContractId::from_u64(contract_id);
            let args: *const core::ffi::c_void = args_ptr as usize as *const core::ffi::c_void;
            let out: *mut core::ffi::c_void = out_ptr as usize as *mut core::ffi::c_void;
            let mut err: AbiError = AbiError::ok();
            // Direct dispatch through the already-resolved interface — no re-entry into
            // the host to re-resolve. `peer_dt` was read above from this same interface,
            // so we branch on it and touch only the union variant the dispatch_type
            // proves active.
            let code: u32 = match peer_dt {
                DispatchType::Native => {
                    // SAFETY: iface is non-null (checked above); dispatch_type == Native
                    // guarantees the `native` union variant is the active one, so reading
                    // it is sound.
                    let native: polyplug_abi::NativeDispatch = unsafe { (*iface).dispatch.native };
                    if fn_id >= native.function_count || native.functions.is_null() {
                        // SAFETY: iface produced `instance` via create_instance with the peer's
                        // own loader_data; destroying it with the same loader_data releases the
                        // per-instance impl before we bail out (a null-id handle is a no-op).
                        unsafe { ((*iface).destroy_instance)(peer_loader_data, hvt, instance) };
                        return AbiErrorCode::FunctionNotAvailable as u32;
                    }
                    // SAFETY: fn_id < function_count and functions is non-null, so the slot
                    // at fn_id is within the peer's static function-pointer array.
                    let slot: *const () = unsafe { *native.functions.add(fn_id as usize) };
                    if slot.is_null() {
                        // SAFETY: same as the bounds-check bail-out above — release the
                        // freshly created instance before returning.
                        unsafe { ((*iface).destroy_instance)(peer_loader_data, hvt, instance) };
                        return AbiErrorCode::FunctionNotAvailable as u32;
                    }
                    // SAFETY: native dispatch slots carry the frozen native ABI signature
                    // `extern "C" fn(GuestContractInstance, *const c_void, *mut c_void, *mut AbiError)`
                    // (see the polyplugc rust generator); `slot` is a non-null pointer to such a
                    // function. The transmute reinterprets the type-erased `*const ()` as that
                    // concrete fn pointer, the established native-call form.
                    let dispatch_fn: unsafe extern "C" fn(
                        GuestContractInstance,
                        *const core::ffi::c_void,
                        *mut core::ffi::c_void,
                        *mut AbiError,
                    ) = unsafe { core::mem::transmute(slot) };
                    // SAFETY: dispatch_fn is transmuted from a valid native function pointer in
                    // this interface's table; `instance` belongs to this contract; args/out are
                    // caller-supplied addresses the generated peer_callers.ts aligns via
                    // polyplug.alloc; `err` is a valid, writable out-param for the call.
                    unsafe { dispatch_fn(instance, args, out, &mut err) };
                    err.code
                }
                DispatchType::VirtualMachine => {
                    // SAFETY: iface is non-null (checked above); dispatch_type == VirtualMachine
                    // guarantees the `vm` union variant is the active one, so reading vm.call and
                    // vm.loader_data is sound. instance belongs to this contract; args/out are the
                    // caller-supplied aligned buffers; a null arena is the documented fallback for
                    // a caller that carries no per-call arena; `err` is a valid, writable out-param.
                    unsafe {
                        ((*iface).dispatch.vm.call)(
                            (*iface).dispatch.vm.loader_data,
                            instance,
                            fn_id,
                            args as *const (),
                            out as *mut (),
                            core::ptr::null_mut(),
                            &mut err,
                        )
                    };
                    err.code
                }
            };
            // SAFETY: iface is non-null (checked above); instance was produced by create_instance
            // on this same interface, so destroying it with the same peer loader_data releases
            // the per-instance impl (a null-id handle is a no-op).
            unsafe { ((*iface).destroy_instance)(peer_loader_data, hvt, instance) };
            code
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: dispatchPeer function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("dispatchPeer", dispatch_peer_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: dispatchPeer set failed: {e}"),
        })?;

    let alloc_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |ctx: Ctx<'js>, size: u32| -> Result<Array<'js>, rquickjs::Error> {
            let hvt: *const HostApi = match host_from_usize(host_interface_usize) {
                Some(ptr) => ptr,
                None => {
                    let arr: Array<'js> = Array::new(ctx.clone()).map_err(|_| {
                        rquickjs::Exception::throw_message(&ctx, "array creation failed")
                    })?;
                    let _ = arr.set(0, 0.0_f64);
                    let _ = arr.set(1, 0.0_f64);
                    return Ok(arr);
                }
            };
            // SAFETY: hvt points to 'static HostApi data.
            let ptr: *mut u8 = unsafe { ((*hvt).alloc)(hvt, size as usize, 1) };
            let ptr_usize: usize = ptr as usize;
            let arr: Array<'js> = Array::new(ctx.clone())
                .map_err(|_| rquickjs::Exception::throw_message(&ctx, "array creation failed"))?;
            // Store as f64: rquickjs sign-extends u32 > INT32_MAX to negative JS ints,
            // which breaks BigInt reconstruction. f64 preserves the unsigned value exactly.
            let _ = arr.set(0, (ptr_usize as u32) as f64);
            let _ = arr.set(1, ((ptr_usize >> 32) as u32) as f64);
            Ok(arr)
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: alloc function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("alloc", alloc_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: alloc set failed: {e}"),
        })?;

    // arenaAlloc(size, arena_ptr) serves the guest's per-call return buffers from
    // the per-call CallArena whose pointer the dispatch THREADS in as the
    // `arena_ptr` argument (NOT read from a VM global — Rule 12), falling back to
    // host->alloc when that pointer is 0. Returns [lo, hi] f64 halves, matching
    // alloc. Each call carries its own arena on its own frame, so a concurrent or
    // same-VM reentrant dispatch can never perturb this call's arena.
    let arena_alloc_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |ctx: Ctx<'js>, size: u32, arena_ptr: f64| -> Result<Array<'js>, rquickjs::Error> {
            let arena: *mut CallArena = arena_ptr as u64 as usize as *mut CallArena;
            let ptr: *mut u8 = if arena.is_null() {
                match host_from_usize(host_interface_usize) {
                    // SAFETY: hvt points to 'static HostApi data.
                    Some(hvt) => unsafe { ((*hvt).alloc)(hvt, size as usize, 1) },
                    None => core::ptr::null_mut(),
                }
            } else {
                // SAFETY: `arena` is the valid per-call CallArena whose pointer the
                // dispatch threaded in as the arena_ptr argument; alloc bumps within
                // it or chains a host-allocated overflow block.
                unsafe { (*arena).alloc(size as usize, 1) }
            };
            let ptr_usize: usize = ptr as usize;
            let arr: Array<'js> = Array::new(ctx.clone())
                .map_err(|_| rquickjs::Exception::throw_message(&ctx, "array creation failed"))?;
            let _ = arr.set(0, (ptr_usize as u32) as f64);
            let _ = arr.set(1, ((ptr_usize >> 32) as u32) as f64);
            Ok(arr)
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: arenaAlloc function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("arenaAlloc", arena_alloc_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: arenaAlloc set failed: {e}"),
        })?;

    // log(level, scope, message) delivers guest log records to the host's
    // logging funnel (`RuntimeConfig::log` callback or the stderr default)
    // through the instance-owned LoggerHandle copy captured at load time —
    // per-VM captured state, no statics (Rule 12). `level` is validated via
    // LogLevel::from_u32; non-integral, out-of-range, or unknown values clamp
    // to LogLevel::Error, matching HostApi.log semantics. `scope` and `message`
    // are delivered verbatim; the suggested scope convention is
    // "guest.<plugin-name>".
    //
    // Lock analysis (why logging mid-dispatch cannot deadlock): this bridge
    // runs inside guest code, i.e. while js_dispatch's Context::with holds
    // QuickJS's internal `parallel` VM lock on the calling thread
    // (in_dispatch_threads is NOT held there — it is released before
    // Context::with). That is sound: the only code that enters this VM is
    // js_dispatch / the loader's own load path, and the host logging callback
    // is contractually forbidden from re-entering the runtime
    // (`RuntimeBuilder::logger` / `RuntimeConfig::log` callback contract), so
    // no path from inside the callback can reach js_dispatch — or any other
    // loader entry point — and therefore none can attempt the VM lock or any
    // loader Mutex. No runtime lock is held across a guest dispatch either.
    let log_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |level: f64, scope: String, message: String| {
            let log_level: LogLevel = if level.fract() == 0.0 {
                LogLevel::from_u32(level as u32).unwrap_or(LogLevel::Error)
            } else {
                LogLevel::Error
            };
            logger.log(log_level, &scope, || message);
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: log function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("log", log_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: log set failed: {e}"),
        })?;

    // lo/hi are f64 for the same reason as alloc's return values: u32 > INT32_MAX would be
    // sign-extended by rquickjs to a negative JS int, corrupting the pointer reconstruction.
    // size/align must match the original allocation so the host allocator frees the exact
    // region — passing size=0 makes polyplug_host_free a no-op, which leaks every block.
    let free_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |_ctx: Ctx<'js>, lo: f64, hi: f64, size: u32, align: u32| {
            let hvt: *const HostApi = match host_from_usize(host_interface_usize) {
                Some(ptr) => ptr,
                None => return,
            };
            let ptr: *mut u8 = ((hi as u64) << 32 | lo as u64) as usize as *mut u8;
            if ptr.is_null() {
                return;
            }
            // SAFETY: hvt points to 'static HostApi data.
            unsafe { ((*hvt).free)(hvt, ptr, size as usize, align as usize) };
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: free function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("free", free_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: free set failed: {e}"),
        })?;

    let read_i32_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64| -> i32 {
        let ptr_u64: u64 = ptr_num as u64;
        let ptr: *const i32 = ptr_u64 as usize as *const i32;
        if ptr.is_null() {
            return 0;
        }
        // SAFETY: ptr is a valid pointer provided by the host for reading.
        unsafe { *ptr }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: readI32 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("readI32", read_i32_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: readI32 set failed: {e}"),
        })?;

    let write_i32_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64, value: i32| {
        let ptr_u64: u64 = ptr_num as u64;
        let ptr: *mut i32 = ptr_u64 as usize as *mut i32;
        if ptr.is_null() {
            return;
        }
        // SAFETY: ptr is a valid pointer provided by the host for writing.
        unsafe {
            *ptr = value;
        }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: writeI32 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("writeI32", write_i32_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: writeI32 set failed: {e}"),
        })?;

    let read_byte_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64| -> u32 {
        let ptr_u64: u64 = ptr_num as u64;
        let ptr: *const u8 = ptr_u64 as usize as *const u8;
        if ptr.is_null() {
            return 0;
        }
        // SAFETY: ptr is a valid pointer provided by the host for reading.
        unsafe { *ptr as u32 }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: readByte function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("readByte", read_byte_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: readByte set failed: {e}"),
        })?;

    let write_byte_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64, value: u32| {
        let ptr_u64: u64 = ptr_num as u64;
        let ptr: *mut u8 = ptr_u64 as usize as *mut u8;
        if ptr.is_null() {
            return;
        }
        // SAFETY: ptr is a valid pointer provided by the host for writing.
        unsafe {
            *ptr = value as u8;
        }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: writeByte function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("writeByte", write_byte_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: writeByte set failed: {e}"),
        })?;

    let read_memory_fn: Function<'js> = Function::new(
        ctx.clone(),
        // Returns Array<'js> of u8 values instead of ArrayBuffer: a plain Array of integers
        // is unambiguous and Uint8Array(array_of_ints) works correctly in QuickJS.
        |ctx: Ctx<'js>, ptr_num: f64, len: u32| -> Result<Array<'js>, rquickjs::Error> {
            let ptr_u64: u64 = ptr_num as u64;
            let ptr: *const u8 = ptr_u64 as usize as *const u8;
            let len_usize: usize = len as usize;

            let arr: Array<'js> = Array::new(ctx.clone())
                .map_err(|_| rquickjs::Exception::throw_message(&ctx, "Array creation failed"))?;

            if ptr.is_null() || len_usize == 0 {
                return Ok(arr);
            }

            // SAFETY: ptr is a valid pointer provided by the host for reading.
            // The caller guarantees the memory region [ptr, ptr+len) is valid.
            let bytes: &[u8] = unsafe { core::slice::from_raw_parts(ptr, len_usize) };

            for (i, &byte) in bytes.iter().enumerate() {
                // Byte values are 0-255, always fit in 31-bit signed int — no sign-extension issue.
                let _ = arr.set(i, u32::from(byte) as f64);
            }

            Ok(arr)
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: readMemory function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("readMemory", read_memory_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: readMemory set failed: {e}"),
        })?;

    // Return f64 instead of u32: rquickjs sign-extends u32 > INT32_MAX when converting to
    // JavaScript tagged ints. Returning f64 ensures the full unsigned range [0, 2^32) is
    // represented exactly as a JS Number (all u32 values are < 2^53 = float64 mantissa cap).
    let read_u32_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64| -> f64 {
        let ptr_u64: u64 = ptr_num as u64;
        let ptr: *const u32 = ptr_u64 as usize as *const u32;
        if ptr.is_null() {
            return 0.0;
        }
        // SAFETY: ptr is a valid pointer provided by the host for reading.
        unsafe { *ptr as f64 }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: readU32 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("readU32", read_u32_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: readU32 set failed: {e}"),
        })?;

    // Both arguments are f64: same reasoning as readU32 — u32 values > INT32_MAX would be
    // sign-extended by rquickjs if typed as u32, corrupting large pointer halves or values.
    let write_u32_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64, value: f64| {
        let ptr_u64: u64 = ptr_num as u64;
        let ptr: *mut u32 = ptr_u64 as usize as *mut u32;
        if ptr.is_null() {
            return;
        }
        // SAFETY: ptr is a valid pointer provided by the host for writing.
        unsafe {
            *ptr = value as u64 as u32;
        }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: writeU32 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("writeU32", write_u32_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: writeU32 set failed: {e}"),
        })?;

    // ── callHostContract ──────────────────────────────────────────────────────
    // Dispatches a call to a host-provided contract service.  Resolves the
    // HostContractInterface, reads the dispatch type, and invokes either the
    // native function pointer or the VM call hook using the canonical host-caller
    // pattern (null GuestContractInstance, null arena).
    let call_host_contract_fn: Function<'js> = Function::new(
        ctx.clone(),
        move |_ctx: Ctx<'js>,
              contract_id_lo: u32,
              contract_id_hi: u32,
              min_version: u32,
              fn_id: u32,
              args_ptr: u64,
              out_ptr: u64|
              -> u32 {
            let contract_id: u64 = (contract_id_hi as u64) << 32 | contract_id_lo as u64;
            let hvt: *const HostApi = match host_from_usize(host_interface_usize) {
                Some(p) => p,
                None => return AbiErrorCode::Generic as u32,
            };
            // SAFETY: hvt is a valid 'static HostApi pointer stored by register_host_functions;
            // the self-passing ABI pattern is satisfied by passing hvt as the first argument.
            let iface: *const HostContractInterface =
                unsafe { ((*hvt).resolve_host_contract_interface)(hvt, contract_id, min_version) };
            if iface.is_null() {
                return AbiErrorCode::NotFound as u32;
            }
            // SAFETY: hvt is valid (same guarantee as above); hvt and contract_id/min_version
            // match the resolve call that just succeeded so get_host_contract returns a valid
            // HostContractInstance.
            let instance: HostContractInstance =
                unsafe { ((*hvt).get_host_contract)(hvt, contract_id, min_version) };
            let args: *const core::ffi::c_void = args_ptr as usize as *const core::ffi::c_void;
            let out: *mut core::ffi::c_void = out_ptr as usize as *mut core::ffi::c_void;
            // SAFETY: iface is non-null (checked above); `singleton` is a plain bool
            // field that is safe to read through a valid non-null pointer.
            let singleton: bool = unsafe { (*iface).singleton };
            // SAFETY: iface is non-null (checked above); `dispatch_type` is a plain field
            // that is safe to read through a valid non-null pointer.
            let dt: DispatchType = unsafe { (*iface).dispatch_type };
            let code: u32 = match dt {
                DispatchType::Native => {
                    // SAFETY: iface is non-null (checked); dispatch_type == Native guarantees
                    // the `native` union variant is active, so reading it is sound.
                    let native: polyplug_abi::NativeDispatch = unsafe { (*iface).dispatch.native };
                    // Bounds- and null-check the host function table before indexing it,
                    // mirroring the runtime's native-dispatch path.
                    if native.functions.is_null() || fn_id >= native.function_count {
                        // SAFETY: iface produced `instance`; the helper only destroys a
                        // non-singleton instance, releasing it before we bail out.
                        unsafe { destroy_host_instance_if_needed(iface, singleton, instance) };
                        return AbiErrorCode::FunctionNotAvailable as u32;
                    }
                    // SAFETY: fn_id < function_count and functions is non-null, so the slot
                    // at fn_id is within the host's static function-pointer array.
                    let fn_ptr: *const () = unsafe { *native.functions.add(fn_id as usize) };
                    if fn_ptr.is_null() {
                        // SAFETY: iface produced `instance`; the helper only destroys a
                        // non-singleton instance, releasing it before we bail out.
                        unsafe { destroy_host_instance_if_needed(iface, singleton, instance) };
                        return AbiErrorCode::FunctionNotAvailable as u32;
                    }
                    // SAFETY: fn_ptr came from the host's native dispatch table and has the documented
                    // (state, args, out) -> AbiError C signature; instance.data is the contract state.
                    let dispatch_fn: unsafe extern "C" fn(
                        *const core::ffi::c_void,
                        *const core::ffi::c_void,
                        *mut core::ffi::c_void,
                        *mut AbiError,
                    ) = unsafe { core::mem::transmute(fn_ptr) };
                    let mut err: AbiError = AbiError::ok();
                    // SAFETY: dispatch_fn is transmuted from a valid host native function pointer;
                    // instance.data is the contract-state pointer owned by the host; args and out
                    // are caller-supplied buffers aligned by the generated caller via polyplug.alloc;
                    // `err` is a valid, writable out-param for the duration of the call.
                    unsafe {
                        dispatch_fn(
                            instance.data as *const core::ffi::c_void,
                            args,
                            out,
                            &mut err,
                        )
                    };
                    err.code
                }
                DispatchType::VirtualMachine => {
                    let mut err: AbiError = AbiError::ok();
                    // SAFETY: iface is non-null; vm.call + loader_data are the host-provided VM
                    // dispatcher; a null GuestContractInstance + null arena match the canonical
                    // rust host-contract caller (host contracts carry no guest instance / per-call arena);
                    // `err` is a valid, writable out-param for the duration of the call.
                    unsafe {
                        ((*iface).dispatch.vm.call)(
                            (*iface).dispatch.vm.loader_data,
                            GuestContractInstance::null(),
                            fn_id,
                            args as *const (),
                            out as *mut (),
                            core::ptr::null_mut(),
                            &mut err,
                        )
                    };
                    err.code
                }
            };
            // A non-singleton host contract mints a fresh instance per get_host_contract;
            // the caller owns it and must destroy it after the dispatch, or it leaks.
            // Singleton contracts are cached by the runtime — leave them untouched.
            // SAFETY: iface produced `instance` via get_host_contract above; the helper
            // destroys it only for non-singleton contracts.
            unsafe { destroy_host_instance_if_needed(iface, singleton, instance) };
            code
        },
    )
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!(
            "JS runtime js-quickjs error: callHostContract function creation failed: {e}"
        ),
    })?;

    polyplug_obj
        .set("callHostContract", call_host_contract_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: callHostContract set failed: {e}"),
        })?;

    let read_f64_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64| -> f64 {
        let ptr: *const f64 = (ptr_num as u64) as usize as *const f64;
        if ptr.is_null() {
            return 0.0;
        }
        // SAFETY: ptr is a valid host-provided pointer to an 8-byte f64 return slot.
        unsafe { *ptr }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: readF64 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("readF64", read_f64_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: readF64 set failed: {e}"),
        })?;

    let read_f32_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64| -> f64 {
        let ptr: *const f32 = (ptr_num as u64) as usize as *const f32;
        if ptr.is_null() {
            return 0.0;
        }
        // SAFETY: ptr is a valid host-provided pointer to a 4-byte f32 return slot.
        unsafe { *ptr as f64 }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: readF32 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("readF32", read_f32_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: readF32 set failed: {e}"),
        })?;

    // Write counterparts of readF64/readF32: preserve the full float bit pattern
    // instead of routing through writeU32 (which integer-truncates and loses the
    // f32 encoding). Pointer arrives as f64 for the same sign-extension reason
    // as writeU32.
    let write_f64_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64, value: f64| {
        let ptr: *mut f64 = (ptr_num as u64) as usize as *mut f64;
        if ptr.is_null() {
            return;
        }
        // SAFETY: ptr is a valid host-provided pointer to an 8-byte f64 slot.
        unsafe {
            *ptr = value;
        }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: writeF64 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("writeF64", write_f64_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: writeF64 set failed: {e}"),
        })?;

    let write_f32_fn: Function<'js> = Function::new(ctx.clone(), |ptr_num: f64, value: f64| {
        let ptr: *mut f32 = (ptr_num as u64) as usize as *mut f32;
        if ptr.is_null() {
            return;
        }
        // SAFETY: ptr is a valid host-provided pointer to a 4-byte f32 slot.
        unsafe {
            *ptr = value as f32;
        }
    })
    .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
        bundle: bundle_name.to_owned(),
        error: format!("JS runtime js-quickjs error: writeF32 function creation failed: {e}"),
    })?;

    polyplug_obj
        .set("writeF32", write_f32_fn)
        .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
            bundle: bundle_name.to_owned(),
            error: format!("JS runtime js-quickjs error: writeF32 set failed: {e}"),
        })?;

    Ok(())
}

// ─── Init-bundle window guard ────────────────────────────────────────────────

/// RAII guard that keeps the runtime's per-thread init-bundle window open for the
/// duration of `load_inner`'s init **and** registration phases.
///
/// `host_register_guest_contract` attributes each registration to the bundle id at
/// the top of the runtime's init-bundle stack (`current_init_bundle_id`). The JS
/// `polyplug_init` only RETURNS the registrations array; the actual
/// `register_guest_contract` call happens later in `load_inner`. The window must
/// therefore stay open across BOTH phases, and `pop` must run on EVERY exit path —
/// including the `?` early-returns between init and the registration call. Dropping
/// this guard pops exactly once, whether the function returns Ok, returns Err via
/// `?`, or unwinds, so the stack never leaks an entry.
struct InitBundleGuard<'r> {
    runtime: &'r PolyplugRuntime,
}

impl<'r> InitBundleGuard<'r> {
    /// Push `bundle_id` onto the runtime's init-bundle stack and return a guard that
    /// pops it on drop.
    fn enter(runtime: &'r PolyplugRuntime, bundle_id: u64) -> Self {
        runtime.push_init_bundle_id(bundle_id);
        Self { runtime }
    }
}

impl Drop for InitBundleGuard<'_> {
    fn drop(&mut self) {
        self.runtime.pop_init_bundle_id();
    }
}

// ─── JsLoader ────────────────────────────────────────────────────────────────

/// QuickJS in-process JS plugin loader.
pub struct JsLoader {
    _config: JsConfig,
    /// Per-bundle VM state owned by the loader, keyed by [`BundleId`].
    ///
    /// Each loaded bundle contributes one [`JsLoaderData`] (holding its own QuickJS
    /// `Runtime` and `Context`). The boxes are owned here instead of leaked via
    /// `Box::into_raw`, so [`JsLoader::unload`] can drop them and truly reclaim the
    /// VM. The VM dispatch `bridge_data` points at the boxed `JsLoaderData`'s stable
    /// heap address; the box is never moved out of the map while owned, so the
    /// pointer stays valid for as long as the bundle is loaded — exactly the
    /// guarantee the old leak provided. Reload appends rather than replaces so a
    /// superseded VM stays alive for any in-flight dispatch.
    live: Mutex<HashMap<BundleId, Vec<SendVm>>>,
    /// Count of VM-state boxes scheduled for epoch-deferred reclamation.
    ///
    /// Test/diagnostic only: epoch collection timing is non-deterministic, but this
    /// counter is incremented the instant a box is handed to
    /// `crossbeam_epoch::pin().defer(...)`, so it deterministically proves the VM was
    /// scheduled for reclaim — NOT parked alive forever. Instance state (Rule 12).
    scheduled_reclaims: AtomicU64,
}

impl JsLoader {
    pub fn new(config: JsConfig) -> JsLoader {
        JsLoader {
            _config: config,
            live: Mutex::new(HashMap::new()),
            scheduled_reclaims: AtomicU64::new(0),
        }
    }

    /// Schedule one bundle's VM-state boxes for epoch-deferred drop and record the
    /// scheduling.
    ///
    /// SAFETY/why: each `SendVm` box is already unreachable by any *new* dispatch (the
    /// bundle has been removed from `live` / the registry before this is called). Any
    /// in-flight runtime-mediated call holds a crossbeam-epoch pin, so `defer` runs the
    /// drop — freeing the QuickJS `Context` and `Runtime` — only once no such reader
    /// remains; the global epoch coordinates that with the runtime's reader pins. Direct
    /// FFI host→VM callers must quiesce before unload per the documented host contract
    /// (docs/TRUST_MODEL.md). `SendVm` is `Send + 'static` (see its `unsafe impl Send`),
    /// so moving it into the deferred closure is sound — the box is reachable only from
    /// the deferred closure, and rquickjs's `parallel` lock still serializes the drop's
    /// VM teardown.
    fn schedule_reclaim(&self, state: Vec<SendVm>) {
        for vm in state {
            self.scheduled_reclaims.fetch_add(1, Ordering::Relaxed);
            crossbeam_epoch::pin().defer(move || drop(vm));
        }
    }

    /// Read the plugin's JS source from the on-disk bundle directory.
    ///
    /// Used by the [`BundleSource::Path`] flow. The file is resolved from the
    /// manifest's `file` field, defaulting to `bundle.js`.
    fn read_path_source(manifest: &ManifestData) -> Result<String, LoaderError> {
        let bundle_path: PathBuf = if !manifest.file.is_empty() {
            manifest.path.join(&manifest.file)
        } else {
            manifest.path.join("bundle.js")
        };
        std::fs::read_to_string(&bundle_path).map_err(|e: std::io::Error| {
            LoaderError::ManifestParse {
                path: bundle_path.display().to_string(),
                reason: e.to_string(),
            }
        })
    }

    /// Shared load/reload implementation.
    ///
    /// Both `load` and `reload` produce identical behaviour; `reload` only adds a
    /// hot-reload-enabled guard before delegating here.
    ///
    /// `bundle_js` is the plugin's JS source text — read from disk for
    /// [`BundleSource::Path`], or supplied directly for [`BundleSource::Code`] /
    /// [`BundleSource::Bytes`]. `bundle_dir` is the on-disk bundle directory for
    /// path sources, or `None` for in-memory sources, which are single-file and
    /// self-contained (JS bundles are always one flat `bundle.js`, so there is no
    /// bundle directory to provision and no sibling files to resolve). When `None`,
    /// `globalThis.bundlePath` and `BundleInitContext.bundle_path` are an empty
    /// string, matching the "no bundle directory for non-path sources" contract.
    fn load_inner(
        &self,
        manifest: &ManifestData,
        bundle_js: &str,
        bundle_dir: Option<&Path>,
        runtime: &PolyplugRuntime,
    ) -> Result<(), LoaderError> {
        let bundle_id: u64 = manifest.id;

        let qjs_runtime: Runtime =
            Runtime::new().map_err(|e: rquickjs::Error| LoaderError::InitFailed {
                bundle: manifest.name.clone(),
                error: format!("JS runtime init failed: QuickJS runtime init failed: {e}"),
            })?;

        let ctx: Context =
            Context::full(&qjs_runtime).map_err(|e: rquickjs::Error| LoaderError::InitFailed {
                bundle: manifest.name.clone(),
                error: format!("JS runtime js-quickjs error: context creation failed: {e}"),
            })?;

        // Get the HostApi pointer from the runtime.
        // This interface already has the runtime pointer set internally.
        let host_interface: *const HostApi = runtime.as_context_ptr();

        // Open the init-bundle window for BOTH the init call and the registration
        // call below: `host_register_guest_contract` attributes the registration to
        // the bundle id on top of this stack, and `register_guest_contract` runs later
        // in this function (init only returns the registrations array). The
        // guard's Drop pops once on every exit path — including the `?` early-returns
        // between here and the registration call — so the stack never leaks an entry
        // and the registration carries the real bundle id.
        let _init_window: InitBundleGuard<'_> = InitBundleGuard::enter(runtime, bundle_id);

        // In-memory sources (Code/Bytes) carry no bundle directory, so bundlePath
        // and BundleInitContext.bundle_path are empty for them.
        let bundle_dir_str: String = match bundle_dir {
            Some(dir) => dir.to_string_lossy().into_owned(),
            None => String::new(),
        };

        // HostApi pointer split into f64 lo/hi halves, threaded explicitly to
        // polyplug_init and each factory call (NOT set on a VM global — Rule 12).
        // f64 avoids rquickjs sign-extending a u32 > INT32_MAX to a negative tagged int.
        let host_usize: usize = host_interface as usize;
        let host_lo: f64 = (host_usize as u32) as f64;
        let host_hi: f64 = ((host_usize >> 32) as u32) as f64;

        // Build the bridge + call polyplug_init + extract the registration and build
        // the default impl, all under one Context::with. The bridge is persisted and
        // threaded into init / each factory call / every dispatch — it is NEVER set
        // on `globalThis` (Rule 12). The `Persistent` values returned here are
        // 'static, so they leave the closure to populate the JsLoaderData below.
        type InitExtract = (
            JsRegistrationData,
            Persistent<Object<'static>>,
            Persistent<Value<'static>>,
        );
        let init_extract: Result<InitExtract, LoaderError> = ctx.with(|ctx_ref: Ctx<'_>| {
            let polyplug_obj: Object<'_> =
                Object::new(ctx_ref.clone()).map_err(|e: rquickjs::Error| {
                    LoaderError::InitFailed {
                        bundle: manifest.name.clone(),
                        error: format!("JS runtime js-quickjs error: object creation failed: {e}"),
                    }
                })?;
            register_host_functions(
                &ctx_ref,
                &polyplug_obj,
                host_interface,
                &manifest.name,
                runtime.logger(),
            )?;

            let set_bundle: String = format!("globalThis.bundlePath = {:?};", bundle_dir_str);
            ctx_ref
                .eval::<Value<'_>, _>(set_bundle.as_str())
                .map_err(|e: rquickjs::Error| {
                    LoaderError::InitFailed {
                        bundle: manifest.name.clone(),
                        error: format!("JS runtime js-quickjs error: bundlePath injection failed: {e}"),
                    }
                })?;

            ctx_ref
                .eval::<Value<'_>, _>(bundle_js)
                .map_err(|e: rquickjs::Error| {
                    LoaderError::InitFailed {
                        bundle: manifest.name.clone(),
                        error: format!("JS runtime js-quickjs error: bundle eval failed: {e}"),
                    }
                })?;

            let init_fn: Function<'_> = ctx_ref
                .globals()
                .get::<&str, Function<'_>>("polyplug_init")
                .map_err(|_| {
                    LoaderError::InitSymbolMissing {
                        bundle: bundle_dir_str.clone(),
                    }
                })?;

            // SAFETY: Intentionally leaked; bundle_path_static outlives this call.
            let bundle_path_static: &'static str =
                Box::leak(bundle_dir_str.clone().into_boxed_str());
            let plugin_ctx: BundleInitContext = BundleInitContext {
                bundle_path: StringView {
                    ptr: bundle_path_static.as_ptr(),
                    len: bundle_path_static.len(),
                },
                bundle_id,
            };

            // Pass HostApi and BundleInitContext pointers as 4 f64 arguments plus the
            // bridge object: (host_lo, host_hi, ctx_lo, ctx_hi, bridge). The generated
            // polyplug_init RETURNS [registrations, abiError]; nothing is deposited
            // into any global / VM userdata (Rule 12).
            let ctx_usize: usize = &plugin_ctx as *const BundleInitContext as usize;
            let ctx_lo: f64 = (ctx_usize as u32) as f64;
            let ctx_hi: f64 = ((ctx_usize >> 32) as u32) as f64;

            let init_value: Array<'_> = init_fn
                .call::<(f64, f64, f64, f64, Object<'_>), Array<'_>>((
                    host_lo,
                    host_hi,
                    ctx_lo,
                    ctx_hi,
                    polyplug_obj.clone(),
                ))
                .map_err(|e: rquickjs::Error| {
                    let thrown: Value<'_> = ctx_ref.catch();
                    let detail: String = match thrown.as_exception() {
                        Some(exc) => exc.message().unwrap_or_else(|| e.to_string()),
                        None => e.to_string(),
                    };
                    LoaderError::InitFailed {
                        bundle: manifest.name.clone(),
                        error: format!(
                            "JS runtime js-quickjs error: polyplug_init call failed: {detail}"
                        ),
                    }
                })?;

            // init_value = [registrations, abiError]. Honor the AbiError first: a
            // non-Ok code means the guest refused to initialize — fail the load,
            // surfacing the guest's own message when present.
            let abi_error: Object<'_> = init_value.get::<Object<'_>>(1).map_err(|_| {
                LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: "JS runtime js-quickjs error: polyplug_init did not return an AbiError"
                        .to_owned(),
                }
            })?;
            let init_code: u32 = abi_error.get::<&str, f64>("code").unwrap_or(0.0_f64) as u32;
            if init_code != AbiErrorCode::Ok as u32 {
                let message: Option<String> =
                    abi_error.get::<&str, Option<String>>("message").unwrap_or(None);
                let detail: String = match message {
                    Some(msg) if !msg.is_empty() => format!(" ({msg})"),
                    _ => String::new(),
                };
                return Err(LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: format!(
                        "JS runtime js-quickjs error: polyplug_init returned error code {init_code}{detail}"
                    ),
                });
            }

            // Read registrations[0] — the loader registers a single contract per
            // bundle (the single-JsLoaderData / single-live-entry model), exactly as
            // the old registerVtable path did.
            let registrations: Array<'_> = init_value.get::<Array<'_>>(0).map_err(|_| {
                LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: "JS runtime js-quickjs error: polyplug_init did not return a registrations array"
                        .to_owned(),
                }
            })?;
            let entry: Object<'_> = registrations.get::<Object<'_>>(0).map_err(|_| {
                LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: "JS runtime js-quickjs error: polyplug_init returned an empty registrations array"
                        .to_owned(),
                }
            })?;

            let contract_lo: u32 = entry.get::<&str, f64>("contractLo").unwrap_or(0.0_f64) as u32;
            let contract_hi: u32 = entry.get::<&str, f64>("contractHi").unwrap_or(0.0_f64) as u32;
            let contract_id: u64 = (contract_hi as u64) << 32 | contract_lo as u64;
            let fn_count: u32 = entry.get::<&str, f64>("fnCount").unwrap_or(0.0_f64) as u32;
            let fn_count_usize: usize = fn_count as usize;
            let contract_name: String =
                entry.get::<&str, String>("contractName").map_err(|_| {
                    LoaderError::InitFailed {
                        bundle: manifest.name.clone(),
                        error: "JS runtime js-quickjs error: registration entry missing contractName"
                            .to_owned(),
                    }
                })?;
            let contract_version: u32 =
                entry.get::<&str, f64>("version").unwrap_or(0.0_f64) as u32;

            let interface: Object<'_> = entry.get::<&str, Object<'_>>("interface").map_err(|_| {
                LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: "JS runtime js-quickjs error: registration entry missing interface"
                        .to_owned(),
                }
            })?;

            let functions_array: Object<'_> = interface
                .get::<&str, Object<'_>>("functions")
                .map_err(|_| LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: format!(
                        "JS runtime js-quickjs error: interface for contract '{contract_name}' has no 'functions' array"
                    ),
                })?;
            let mut functions: Vec<Persistent<Function<'static>>> =
                Vec::with_capacity(fn_count_usize);
            for i in 0..fn_count_usize {
                let func: Function<'_> = functions_array
                    .get::<u32, Function<'_>>(i as u32)
                    .map_err(|_| LoaderError::InitFailed {
                        bundle: manifest.name.clone(),
                        error: format!(
                            "JS runtime js-quickjs error: interface for contract '{contract_name}' declares fnCount={fn_count} but functions[{i}] is missing or not a function"
                        ),
                    })?;
                functions.push(Persistent::save(&ctx_ref, func));
            }

            let factory_fn: Function<'_> = interface
                .get::<&str, Function<'_>>("factory")
                .map_err(|_| LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: format!(
                        "JS runtime js-quickjs error: interface for contract '{contract_name}' has no 'factory' function (call setXFactory before registering)"
                    ),
                })?;
            let factory: Persistent<Function<'static>> = Persistent::save(&ctx_ref, factory_fn);

            // Persist the bridge so dispatch / create_instance can thread it; build
            // the stateless default impl once via the factory, passing (bridge,
            // host_lo, host_hi). It serves dispatch on a null instance handle.
            let bridge: Persistent<Object<'static>> = Persistent::save(&ctx_ref, polyplug_obj.clone());
            let impl_val: Value<'_> = factory
                .clone()
                .restore(&ctx_ref)
                .and_then(|f: Function<'_>| {
                    f.call::<(Object<'_>, f64, f64), Value<'_>>((polyplug_obj, host_lo, host_hi))
                })
                .map_err(|e: rquickjs::Error| LoaderError::InitFailed {
                    bundle: manifest.name.clone(),
                    error: format!(
                        "JS runtime js-quickjs error: default impl factory call failed: {e}"
                    ),
                })?;
            let default_impl: Persistent<Value<'static>> = Persistent::save(&ctx_ref, impl_val);

            let registration_data: JsRegistrationData = JsRegistrationData {
                contract_id,
                contract_version,
                contract_name,
                functions,
                factory,
            };
            Ok((registration_data, bridge, default_impl))
        });

        let (registration_data, bridge, default_impl): InitExtract = init_extract?;

        let loader_data: SendVm = SendVm(Box::new(JsLoaderData {
            functions: registration_data.functions,
            factory: registration_data.factory,
            bridge,
            host_lo,
            host_hi,
            default_impl,
            instances: Mutex::new(HashMap::new()),
            next_id: AtomicU64::new(1),
            contract_id: registration_data.contract_id,
            ctx,
            _runtime: qjs_runtime,
            in_dispatch_threads: Mutex::new(Vec::new()),
            logger: runtime.logger(),
        }));

        // The box's heap address is stable across later moves of the `SendVm`/`Box`
        // (moving them moves the pointer, not the allocation), so it stays valid
        // once the box is owned by the loader's `live` map below.
        let loader_data_ptr: *const JsLoaderData = loader_data.as_ptr();

        let contract_id: GuestContractId = GuestContractId::from_u64(registration_data.contract_id);
        let major_version: u32 = registration_data.contract_version >> 16;

        let plugin_interface: GuestContractInterface = GuestContractInterface {
            contract_id,
            contract_version: Version {
                major: major_version,
                minor: 0,
                patch: 0,
            },
            dispatch_type: DispatchType::VirtualMachine,
            create_instance: js_create_instance,
            destroy_instance: js_destroy_instance,
            dispatch: DispatchMechanisms {
                vm: VmDispatch {
                    call: js_dispatch,
                    loader_data: VmLoaderData {
                        data: loader_data_ptr as *mut JsLoaderData as *mut core::ffi::c_void,
                    },
                },
            },
        };

        // register_guest_contract COPIES every field into the registry's own
        // `Arc<GuestContractInterface>` during the synchronous call (the copy's
        // `dispatch.vm.bridge_data` still points at our owned `JsLoaderData` box).
        // The registry never retains this pointer, so a stack value valid for the
        // call is sufficient — no leak, which keeps a load→unload→load loop bounded.
        let interface_for_reg: GuestContractInterface = plugin_interface;
        let static_interface: *const GuestContractInterface =
            &interface_for_reg as *const GuestContractInterface;

        // The contract name's StringView is copied into an owned String by the
        // registry during the call, so a stack-owned String suffices — no leak.
        let contract_name_owned: String = registration_data.contract_name;
        let descriptor: PluginDescriptor = PluginDescriptor {
            name: StringView::from_static(b"js-quickjs-plugin"),
            contract_name: StringView {
                ptr: contract_name_owned.as_ptr(),
                len: contract_name_owned.len(),
            },
            version: Version {
                major: major_version,
                minor: 0,
                patch: 0,
            },
        };

        let mut abi_result: AbiError = AbiError::ok();
        // SAFETY: host_interface, descriptor, and static_interface are valid for this call.
        // The register_guest_contract function uses self-passing pattern; `abi_result`
        // is a valid, writable out-param for the duration of the call.
        unsafe {
            ((*host_interface).register_guest_contract)(
                host_interface,
                &descriptor,
                static_interface,
                &mut abi_result,
            )
        };

        if !abi_result.is_ok() {
            // The registry copy made during register_guest_contract may already point
            // at this box's heap address; schedule it for epoch-deferred drop rather
            // than dropping it inline here, which would dangle the registry's
            // bridge_data while a reader is pinned.
            self.schedule_reclaim(vec![loader_data]);
            return Err(LoaderError::InitFailed {
                bundle: manifest.name.clone(),
                error: format!(
                    "JS runtime js-quickjs error: register_guest_contract returned error code {:?}",
                    abi_result.code
                ),
            });
        }

        // Take ownership of this bundle's VM state. A reload of the same bundle id
        // REPLACES the prior VM entry and schedules the superseded VM for epoch-deferred
        // reclaim (mirroring the native loader): the global epoch keeps the old VM alive
        // for any in-flight dispatch and frees it once no reader is pinned, rather than
        // parking it until unload.
        let superseded: Option<Vec<SendVm>> = {
            let mut live: std::sync::MutexGuard<'_, HashMap<BundleId, Vec<SendVm>>> =
                self.live.lock().unwrap_or_else(PoisonError::into_inner);
            live.insert(BundleId::from_u64(bundle_id), vec![loader_data])
        };
        if let Some(old_state) = superseded {
            self.schedule_reclaim(old_state);
        }

        Ok(())
    }

    /// Number of live VM-state entries currently owned for `bundle_id`.
    #[cfg(test)]
    fn live_vm_count(&self, bundle_id: BundleId) -> usize {
        let live: std::sync::MutexGuard<'_, HashMap<BundleId, Vec<SendVm>>> =
            self.live.lock().unwrap_or_else(PoisonError::into_inner);
        live.get(&bundle_id).map(Vec::len).unwrap_or(0)
    }

    /// Number of VM-state boxes scheduled for epoch-deferred reclaim. Deterministic
    /// (incremented at scheduling time), so tests assert the resource was handed to
    /// the epoch collector without depending on its non-deterministic timing.
    #[cfg(test)]
    fn scheduled_reclaim_count(&self) -> u64 {
        self.scheduled_reclaims.load(Ordering::Relaxed)
    }
}

impl BundleLoader for JsLoader {
    fn loader_name(&self) -> &'static str {
        "js-quickjs"
    }

    fn loader_language(&self) -> SupportedLanguage {
        SupportedLanguage::JavaScript
    }

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

    fn load(
        &self,
        manifest: &ManifestData,
        source: &BundleSource,
        runtime: &PolyplugRuntime,
    ) -> Result<(), LoaderError> {
        match source {
            // On-disk source: read bundle.js from the bundle directory and eval it,
            // provisioning bundlePath/bundle_path from that directory.
            BundleSource::Path(_) => {
                let bundle_js: String = JsLoader::read_path_source(manifest)?;
                self.load_inner(manifest, &bundle_js, Some(&manifest.path), runtime)
            }
            // In-memory JS source text: eval it directly in the bundle's fresh
            // QuickJS Context, exactly as the Path flow evals the entry file's
            // contents. There is no bundle directory — JS bundles are always one
            // flat, self-contained bundle.js, so this is a natural fit.
            BundleSource::Code(code) => self.load_inner(manifest, code, None, runtime),
            // Raw bytes: validate UTF-8, then take the same path as Code. JS source
            // must be valid UTF-8 text; invalid bytes are a structured error.
            BundleSource::Bytes(bytes) => {
                let code: &str = core::str::from_utf8(bytes).map_err(|_| {
                    LoaderError::InvalidSourceEncoding {
                        loader: "js-quickjs",
                        source_kind: source.kind(),
                        bundle: manifest.name.clone(),
                    }
                })?;
                self.load_inner(manifest, code, None, runtime)
            }
        }
    }

    fn reload(
        &self,
        manifest: &ManifestData,
        runtime: &PolyplugRuntime,
    ) -> Result<(), LoaderError> {
        // reload is path-based (the watcher only tracks on-disk bundles); the runtime
        // gates hot-reload before calling this.
        let bundle_js: String = JsLoader::read_path_source(manifest)?;
        self.load_inner(manifest, &bundle_js, Some(&manifest.path), runtime)
    }

    /// Reclaim the bundle's QuickJS VM via epoch-deferred drop.
    ///
    /// Called by the runtime AFTER `invalidate_bundle` has removed the bundle from
    /// the registry, so no dispatch can *resolve* this contract anew.
    ///
    /// # Host-coordination contract
    /// The bundle's VM-state boxes are removed from `live` and scheduled for
    /// epoch-deferred drop (see [`JsLoader::schedule_reclaim`]): each box's QuickJS
    /// `Context` and `Runtime` are freed only once no crossbeam-epoch reader is pinned,
    /// so any in-flight *runtime-mediated* call (which holds an epoch pin across
    /// dispatch) keeps the VM alive until it completes. Direct FFI
    /// host→VM callers the runtime does not mediate are covered by the documented
    /// trusted-same-process contract: exactly like hot-reload, the host MUST NOT call a
    /// bundle's contracts concurrently with unloading it (see `Runtime::unload_bundle`
    /// and docs/TRUST_MODEL.md).
    ///
    /// The VM is always epoch-reclaimed (never parked alive forever).
    fn unload(&self, bundle_id: BundleId, _runtime: &PolyplugRuntime) -> Result<(), LoaderError> {
        let state: Vec<SendVm> = {
            let mut live: std::sync::MutexGuard<'_, HashMap<BundleId, Vec<SendVm>>> =
                self.live.lock().unwrap_or_else(PoisonError::into_inner);
            match live.remove(&bundle_id) {
                Some(v) => v,
                None => return Ok(()),
            }
        };

        self.schedule_reclaim(state);

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]
    use core::sync::atomic::AtomicUsize;
    use core::sync::atomic::Ordering;
    use std::sync::Arc;
    use std::sync::Barrier;

    use super::*;

    #[test]
    fn js_quickjs_loader_name() {
        let loader: JsLoader = JsLoader::new(JsConfig {});
        assert_eq!(loader.loader_name(), "js-quickjs");
    }

    /// Minimal JS bundle registering one contract with a single no-op function.
    fn unload_bundle_js(contract_id: u64, contract_name: &str) -> String {
        let contract_lo: u32 = contract_id as u32;
        let contract_hi: u32 = (contract_id >> 32) as u32;
        format!(
            r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var iface = {{
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [ function(impl, args, out, arena, bridge) {{ return 0; }} ]
    }};
    var registrations = [{{
        contractLo: {contract_lo}, contractHi: {contract_hi}, interface: iface,
        fnCount: 1, contractName: "{contract_name}", version: 0x00010000
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#
        )
    }

    /// Build a temp JS bundle directory + ManifestData for the `test.unload@1`
    /// contract and return both (dir kept alive).
    fn write_unload_bundle(name: &str) -> (tempfile::TempDir, ManifestData) {
        let contract_id: u64 = polyplug_utils::guest_contract_id("test.unload", 1);
        let dir: tempfile::TempDir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("bundle.js"),
            unload_bundle_js(contract_id, "test.unload@1"),
        )
        .expect("write bundle.js");
        let manifest: ManifestData = ManifestData {
            id: polyplug_utils::bundle_id(name),
            name: name.to_owned(),
            loader: "js-quickjs".to_owned(),
            file: "bundle.js".to_owned(),
            path: dir.path().to_path_buf(),
            version: String::new(),
            provides: Vec::new(),
            function_count: HashMap::new(),
            dependencies: Vec::new(),
            needs_reinit_on_dep_reload: false,
            bundle_dependencies: Vec::new(),
        };
        (dir, manifest)
    }

    /// Unload removes the bundle from the loader's live map and SCHEDULES its VM state
    /// for epoch-deferred reclaim. Unload is uniform regardless of `in_dispatch_threads`:
    /// every unload epoch-reclaims, so even an in-flight call schedules reclaim (the
    /// epoch keeps the VM alive until that reader's pin clears).
    #[test]
    fn unload_removes_live_and_schedules_reclaim() {
        let loader: JsLoader = JsLoader::new(JsConfig {});
        let runtime: Arc<PolyplugRuntime> = polyplug::runtime::RuntimeBuilder::new()
            .loader(JsLoader::new(JsConfig {}))
            .build()
            .expect("runtime build must succeed");
        let (_dir, manifest): (tempfile::TempDir, ManifestData) =
            write_unload_bundle("js_unload_quiescent");
        let bundle_id: BundleId = BundleId::from_u64(manifest.id);

        loader
            .load(
                &manifest,
                &BundleSource::Path(manifest.path.clone()),
                &runtime,
            )
            .expect("load must succeed");
        assert_eq!(
            loader.live_vm_count(bundle_id),
            1,
            "the bundle's VM state must be owned after load"
        );

        loader
            .unload(bundle_id, &runtime)
            .expect("unload must succeed");
        assert_eq!(
            loader.live_vm_count(bundle_id),
            0,
            "unload must remove the bundle's VM state from the live map"
        );
        assert_eq!(
            loader.scheduled_reclaim_count(),
            1,
            "unload must schedule the VM state for epoch-deferred reclaim"
        );
    }

    /// A load→unload→load loop on the same bundle must not grow the loader's live
    /// map unboundedly: reclaim keeps memory bounded at one entry.
    #[test]
    fn unload_load_loop_is_bounded() {
        let loader: JsLoader = JsLoader::new(JsConfig {});
        let runtime: Arc<PolyplugRuntime> = polyplug::runtime::RuntimeBuilder::new()
            .loader(JsLoader::new(JsConfig {}))
            .build()
            .expect("runtime build must succeed");
        let (_dir, manifest): (tempfile::TempDir, ManifestData) =
            write_unload_bundle("js_unload_loop");
        let bundle_id: BundleId = BundleId::from_u64(manifest.id);

        for _ in 0..5 {
            loader
                .load(
                    &manifest,
                    &BundleSource::Path(manifest.path.clone()),
                    &runtime,
                )
                .expect("load must succeed");
            assert_eq!(
                loader.live_vm_count(bundle_id),
                1,
                "live map must hold exactly one entry per load"
            );
            loader
                .unload(bundle_id, &runtime)
                .expect("unload must succeed");
            // Driving the loader directly bypasses `Runtime::unload_bundle`'s registry
            // invalidation, so the test mirrors it explicitly.
            runtime
                .registry()
                .invalidate_bundle(bundle_id)
                .expect("invalidate must succeed");
            assert_eq!(
                loader.live_vm_count(bundle_id),
                0,
                "unload must reclaim the entry each iteration"
            );
        }
        assert_eq!(
            loader.scheduled_reclaim_count(),
            5,
            "each of the 5 unloads must schedule its VM state for epoch-deferred reclaim"
        );
    }

    /// A reload of the same bundle id must REPLACE the live VM entry and schedule the
    /// superseded VM for epoch-deferred reclaim — not park it in the live map until
    /// unload. This mirrors the native loader's reload-reclaim and keeps a reload loop
    /// from leaking one VM per reload.
    ///
    /// Driving the loader directly bypasses `Runtime`'s reload orchestration, so the
    /// test invalidates the prior registry registration between loads (so the second
    /// `register_guest_contract` is not rejected as a duplicate provider) — exactly the
    /// supersede path a real reload takes.
    #[test]
    fn reload_replaces_live_and_reclaims_superseded_vm() {
        let loader: JsLoader = JsLoader::new(JsConfig {});
        let runtime: Arc<PolyplugRuntime> = polyplug::runtime::RuntimeBuilder::new()
            .loader(JsLoader::new(JsConfig {}))
            .build()
            .expect("runtime build must succeed");
        let (_dir, manifest): (tempfile::TempDir, ManifestData) =
            write_unload_bundle("js_reload_reclaim");
        let bundle_id: BundleId = BundleId::from_u64(manifest.id);

        loader
            .load(
                &manifest,
                &BundleSource::Path(manifest.path.clone()),
                &runtime,
            )
            .expect("first load must succeed");
        assert_eq!(
            loader.live_vm_count(bundle_id),
            1,
            "first load installs exactly one live VM"
        );
        assert_eq!(
            loader.scheduled_reclaim_count(),
            0,
            "nothing is superseded by the first load"
        );

        // Drop the registry-side registration so the second load's
        // register_guest_contract is not a duplicate, exercising the supersede path.
        runtime
            .registry()
            .invalidate_bundle(bundle_id)
            .expect("invalidate must succeed");

        loader
            .load(
                &manifest,
                &BundleSource::Path(manifest.path.clone()),
                &runtime,
            )
            .expect("second load (reload) must succeed");

        assert_eq!(
            loader.live_vm_count(bundle_id),
            1,
            "reload replaces the live VM — the live map must not grow"
        );
        assert_eq!(
            loader.scheduled_reclaim_count(),
            1,
            "reload must schedule the superseded VM for epoch-deferred reclaim"
        );
    }

    /// Even when a dispatch is marked in flight (the bundle's `in_dispatch_threads`
    /// is non-empty), unload behaves uniformly: it removes the bundle from `live` and
    /// SCHEDULES its VM state for epoch-deferred reclaim. The in-flight reader's epoch
    /// pin — not an `in_dispatch_threads`-gated retire branch — is what keeps the VM
    /// alive until the call completes, so unload never parks the state forever.
    #[test]
    fn unload_schedules_reclaim_even_when_in_flight() {
        let loader: JsLoader = JsLoader::new(JsConfig {});
        let runtime: Arc<PolyplugRuntime> = polyplug::runtime::RuntimeBuilder::new()
            .loader(JsLoader::new(JsConfig {}))
            .build()
            .expect("runtime build must succeed");
        let (_dir, manifest): (tempfile::TempDir, ManifestData) =
            write_unload_bundle("js_unload_deferred");
        let bundle_id: BundleId = BundleId::from_u64(manifest.id);

        loader
            .load(
                &manifest,
                &BundleSource::Path(manifest.path.clone()),
                &runtime,
            )
            .expect("load must succeed");

        // Mark a fake in-flight dispatch in the bundle's tracking vec — exactly the
        // state the dispatch guard leaves while a call is mid-flight on another
        // thread. An in-flight mark must not change the uniform epoch-reclaim outcome.
        {
            let live: std::sync::MutexGuard<'_, HashMap<BundleId, Vec<SendVm>>> =
                loader.live.lock().unwrap_or_else(PoisonError::into_inner);
            let state: &Vec<SendVm> = live.get(&bundle_id).expect("bundle must be live");
            let mut threads: std::sync::MutexGuard<'_, Vec<ThreadId>> = state[0]
                .data()
                .in_dispatch_threads
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            threads.push(std::thread::current().id());
        }

        loader
            .unload(bundle_id, &runtime)
            .expect("unload must succeed even when marked in-flight");
        assert_eq!(
            loader.live_vm_count(bundle_id),
            0,
            "unload must remove the bundle from the live map"
        );
        assert_eq!(
            loader.scheduled_reclaim_count(),
            1,
            "unload must schedule epoch-deferred reclaim even when marked in-flight"
        );
    }

    /// f64 params and returns must round-trip through a REAL loaded VM with
    /// full bit-pattern fidelity: the guest reads its argument with
    /// `polyplug.readF64` and writes its result with `polyplug.writeF64`.
    /// Before the writeF64/writeF32 bridge functions existed, the guest had no
    /// way to emit a float result (writeU32 integer-truncates), so this test
    /// is RED on the pre-fix loader.
    #[test]
    fn js_guest_f64_param_and_return_round_trip() {
        let loader: JsLoader = JsLoader::new(JsConfig {});
        let runtime: Arc<PolyplugRuntime> = polyplug::runtime::RuntimeBuilder::new()
            .loader(JsLoader::new(JsConfig {}))
            .build()
            .expect("runtime build must succeed");

        let contract_id: u64 = polyplug_utils::guest_contract_id("test.float", 1);
        let contract_lo: u32 = contract_id as u32;
        let contract_hi: u32 = (contract_id >> 32) as u32;
        let bundle_js: String = format!(
            r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var iface = {{
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [ function(impl, args_ptr, out_ptr, arena, bridge) {{
            var v = bridge.readF64(args_ptr);
            bridge.writeF64(out_ptr, v * 2.0 + 0.25);
            return 0;
        }} ]
    }};
    var registrations = [{{
        contractLo: {contract_lo}, contractHi: {contract_hi}, interface: iface,
        fnCount: 1, contractName: "test.float@1", version: 0x00010000
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#
        );
        let dir: tempfile::TempDir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("bundle.js"), bundle_js).expect("write bundle.js");
        let manifest: ManifestData = ManifestData {
            id: polyplug_utils::bundle_id("js_f64_round_trip"),
            name: "js_f64_round_trip".to_owned(),
            loader: "js-quickjs".to_owned(),
            file: "bundle.js".to_owned(),
            path: dir.path().to_path_buf(),
            version: String::new(),
            provides: Vec::new(),
            function_count: HashMap::new(),
            dependencies: Vec::new(),
            needs_reinit_on_dep_reload: false,
            bundle_dependencies: Vec::new(),
        };

        loader
            .load(
                &manifest,
                &BundleSource::Path(manifest.path.clone()),
                &runtime,
            )
            .expect("load must succeed");

        let handle: GuestContractHandle = runtime
            .find_guest_contract(contract_id, 0)
            .expect("contract must be registered");
        let iface: *const GuestContractInterface = runtime
            .resolve_guest_contract(handle)
            .expect("interface must resolve");
        assert!(!iface.is_null(), "resolved interface must be non-null");

        let arg: f64 = 1234.5625;
        let mut out_val: f64 = 0.0;
        let mut err: AbiError = AbiError::ok();
        // SAFETY: iface is non-null and was just resolved; the JS loader always
        // registers VirtualMachine dispatch, so the vm union variant is active.
        // arg/out_val are valid for the duration of the call; a null arena is
        // the documented host->alloc fallback.
        unsafe {
            assert_eq!((*iface).dispatch_type, DispatchType::VirtualMachine);
            ((*iface).dispatch.vm.call)(
                (*iface).dispatch.vm.loader_data,
                GuestContractInstance::null(),
                0,
                &arg as *const f64 as *const (),
                &mut out_val as *mut f64 as *mut (),
                core::ptr::null_mut(),
                &mut err,
            )
        };
        assert_eq!(
            err.code,
            AbiErrorCode::Ok as u32,
            "f64 dispatch must succeed"
        );
        // 1234.5625 * 2.0 + 0.25 = 2469.375 — exact in binary floating point,
        // so equality (not epsilon) proves the bit pattern survived both
        // directions. The pre-fix writeU32 path would have produced 2469.0
        // (integer truncation) or thrown (missing bridge fn).
        assert_eq!(out_val, 2469.375, "f64 must round-trip exactly");
    }

    /// Build a leaked JsLoaderData holding the given runtime/context and the
    /// persisted functions, returning a VmLoaderData pointing at it plus a
    /// borrow for direct flag inspection.
    ///
    /// The data is intentionally leaked so the raw pointer inside VmLoaderData
    /// stays valid for the whole test, mirroring the loader's `Box::into_raw`.
    fn make_loader_data(
        runtime: Runtime,
        ctx: Context,
        functions: Vec<Persistent<Function<'static>>>,
    ) -> (VmLoaderData, &'static JsLoaderData) {
        // A trivial factory + default impl + empty bridge: the dispatch tests pass a
        // null instance handle, so dispatch resolves the default impl, and the test
        // guest functions ignore the impl/bridge arguments, so an empty object
        // suffices for both. The bridge is threaded as the final dispatch argument
        // (no global — Rule 12); these tests don't call host functions through it.
        type LoaderParts = (
            Persistent<Function<'static>>,
            Persistent<Value<'static>>,
            Persistent<Object<'static>>,
        );
        let (factory, default_impl, bridge): LoaderParts = ctx.with(|ctx_ref: Ctx<'_>| {
            let factory_fn: Function<'_> = ctx_ref
                .eval::<Function<'_>, _>("(function(bridge, hostLo, hostHi) { return {}; })")
                .expect("factory eval should produce a function");
            let default_obj: Object<'_> =
                Object::new(ctx_ref.clone()).expect("default impl object creation");
            let bridge_obj: Object<'_> =
                Object::new(ctx_ref.clone()).expect("bridge object creation");
            (
                Persistent::save(&ctx_ref, factory_fn),
                Persistent::save(&ctx_ref, default_obj.into_value()),
                Persistent::save(&ctx_ref, bridge_obj),
            )
        });
        let boxed: Box<JsLoaderData> = Box::new(JsLoaderData {
            functions,
            factory,
            bridge,
            host_lo: 0.0,
            host_hi: 0.0,
            default_impl,
            instances: Mutex::new(HashMap::new()),
            next_id: AtomicU64::new(1),
            contract_id: 0,
            ctx,
            _runtime: runtime,
            in_dispatch_threads: Mutex::new(Vec::new()),
            logger: LoggerHandle::default_stderr(),
        });
        let ptr: *mut JsLoaderData = Box::into_raw(boxed);
        // SAFETY: ptr was just produced by Box::into_raw and is never freed in the
        // test, so the &'static borrow is valid for the test's lifetime.
        let data_ref: &'static JsLoaderData = unsafe { &*ptr };
        let vm_loader_data: VmLoaderData = VmLoaderData {
            data: ptr as *mut core::ffi::c_void,
        };
        (vm_loader_data, data_ref)
    }

    /// A normal (non-reentrant) JS dispatch succeeds and clears the flag.
    #[test]
    fn js_dispatch_normal_call_succeeds() {
        let runtime: Runtime = Runtime::new().expect("runtime creation should succeed");
        let ctx: Context = Context::full(&runtime).expect("context creation should succeed");

        // A trivial guest function: ignores its (args, out) arguments, returns 0 (Ok).
        let func: Persistent<Function<'static>> = ctx.with(|ctx_ref: Ctx<'_>| {
            let f: Function<'_> = ctx_ref
                .eval::<Function<'_>, _>("(function(a, o) { return 0; })")
                .expect("eval should produce a function");
            Persistent::save(&ctx_ref, f)
        });

        let (vm_loader_data, data_ref): (VmLoaderData, &'static JsLoaderData) =
            make_loader_data(runtime, ctx, vec![func]);

        let mut out_buf: i32 = 0;
        // SAFETY: vm_loader_data wraps a live JsLoaderData; the guest function
        // ignores the forwarded args/out pointers.
        let err: AbiError = unsafe {
            js_dispatch_impl(
                vm_loader_data,
                GuestContractInstance::null(),
                0,
                core::ptr::null(),
                &mut out_buf as *mut i32 as *mut (),
                core::ptr::null_mut(),
            )
        };
        assert!(err.is_ok(), "normal dispatch should return Ok");
        assert!(
            data_ref
                .in_dispatch_threads
                .lock()
                .expect("tracking mutex must not be poisoned")
                .is_empty(),
            "thread tracking must be empty after a normal dispatch"
        );
    }

    /// A genuine same-VM reentrant dispatch — triggered from inside a guest call
    /// via a native `reenter` bridge — returns ReentrantCall, and the VM stays
    /// usable for a later normal dispatch.
    #[test]
    fn js_dispatch_reentrant_call_is_rejected_and_vm_recovers() {
        let runtime: Runtime = Runtime::new().expect("runtime creation should succeed");
        let ctx: Context = Context::full(&runtime).expect("context creation should succeed");

        // The loader_data pointer is shared into the native bridge via an
        // Arc<AtomicUsize>; it is set after construction (below) and read inside.
        let loader_data_cell: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
        let cell_for_fn: Arc<AtomicUsize> = Arc::clone(&loader_data_cell);

        // Register a native `reenter` function that, while the outer dispatch is in
        // flight (flag set, Context::with held), re-invokes js_dispatch on the SAME
        // loader_data — simulating a plugin→plugin cross-call back into this VM.
        // It returns the nested call's AbiError code as f64 so JS can observe it.
        let func: Persistent<Function<'static>> = ctx.with(|ctx_ref: Ctx<'_>| {
            let reenter_fn: Function<'_> = Function::new(ctx_ref.clone(), move || -> f64 {
                let ptr_usize: usize = cell_for_fn.load(Ordering::Acquire);
                let vm_loader_data: VmLoaderData = VmLoaderData {
                    data: ptr_usize as *mut core::ffi::c_void,
                };
                // SAFETY: the cell holds the live leaked JsLoaderData pointer set up
                // by the test before dispatch; the guest ignores the forwarded
                // args/out pointers.
                let nested: AbiError = unsafe {
                    js_dispatch_impl(
                        vm_loader_data,
                        GuestContractInstance::null(),
                        0,
                        core::ptr::null(),
                        core::ptr::null_mut(),
                        core::ptr::null_mut(),
                    )
                };
                nested.code as f64
            })
            .expect("reenter function creation should succeed");
            ctx_ref
                .globals()
                .set("reenter", reenter_fn)
                .expect("reenter global set should succeed");

            // The guest function calls reenter(), stashes the nested code on a global
            // so the test can read it, and returns 0 (Ok) for the outer call.
            let f: Function<'_> = ctx_ref
                .eval::<Function<'_>, _>(
                    "(function(a, o) { globalThis._nestedCode = reenter(); return 0; })",
                )
                .expect("eval should produce a function");
            Persistent::save(&ctx_ref, f)
        });

        let (vm_loader_data, data_ref): (VmLoaderData, &'static JsLoaderData) =
            make_loader_data(runtime, ctx, vec![func]);
        loader_data_cell.store(vm_loader_data.data as usize, Ordering::Release);

        // Outer dispatch: sets the flag, enters Context::with, runs the guest fn,
        // which calls reenter() → js_dispatch on the same VM.
        // SAFETY: vm_loader_data wraps the live leaked JsLoaderData.
        let outer: AbiError = unsafe {
            js_dispatch_impl(
                vm_loader_data,
                GuestContractInstance::null(),
                0,
                core::ptr::null(),
                core::ptr::null_mut(),
                core::ptr::null_mut(),
            )
        };
        assert!(outer.is_ok(), "outer dispatch should complete Ok");

        // The nested dispatch must have been rejected with ReentrantCall.
        let nested_code: f64 = data_ref.ctx.with(|ctx_ref: Ctx<'_>| {
            ctx_ref
                .globals()
                .get::<&str, f64>("_nestedCode")
                .expect("nested code global must be set by the guest fn")
        });
        assert_eq!(
            nested_code as u32,
            AbiErrorCode::ReentrantCall as u32,
            "nested same-VM dispatch must return ReentrantCall"
        );

        // The tracking is cleared and the VM is still usable for a fresh dispatch.
        assert!(
            data_ref
                .in_dispatch_threads
                .lock()
                .expect("tracking mutex must not be poisoned")
                .is_empty(),
            "thread tracking must be empty after the outer dispatch returns"
        );
        // SAFETY: vm_loader_data still wraps the live leaked JsLoaderData.
        let recovered: AbiError = unsafe {
            js_dispatch_impl(
                vm_loader_data,
                GuestContractInstance::null(),
                0,
                core::ptr::null(),
                core::ptr::null_mut(),
                core::ptr::null_mut(),
            )
        };
        assert!(
            recovered.is_ok(),
            "VM must remain usable after a rejected reentrant call"
        );
    }

    /// A concurrent dispatch from ANOTHER thread into the same Context must
    /// SUCCEED, not be rejected as reentrancy. The thread-aware guard only refuses
    /// a same-thread nested call; a cross-thread caller proceeds and rquickjs's
    /// internal `parallel` lock serializes the two calls.
    ///
    /// Choreography proves a true in-flight overlap: thread A's guest fn (running
    /// inside `Context::with`, holding the rquickjs lock) registers thread A in the
    /// tracking vec, then a native `block` bridge parks on a barrier. While A is
    /// parked mid-dispatch, the main thread (a different thread) dispatches into the
    /// SAME Context. That call passes the reentrancy check (different thread id) and
    /// blocks on rquickjs's internal lock held by A. Releasing the barrier lets A
    /// finish, freeing the lock so the concurrent call completes with Ok.
    #[test]
    fn js_dispatch_cross_thread_concurrent_call_succeeds() {
        let runtime: Runtime = Runtime::new().expect("runtime creation should succeed");
        let ctx: Context = Context::full(&runtime).expect("context creation should succeed");

        // `entered` lets the main thread know A is mid-dispatch (lock held);
        // `release` lets A finish only after the main thread launched its call.
        let entered: Arc<Barrier> = Arc::new(Barrier::new(2));
        let release: Arc<Barrier> = Arc::new(Barrier::new(2));
        let entered_for_fn: Arc<Barrier> = Arc::clone(&entered);
        let release_for_fn: Arc<Barrier> = Arc::clone(&release);

        // Native `block` bridge: signals A is inside the dispatch, then parks until
        // released. It runs inside Context::with, so the rquickjs lock is held.
        let func: Persistent<Function<'static>> = ctx.with(|ctx_ref: Ctx<'_>| {
            let block_fn: Function<'_> = Function::new(ctx_ref.clone(), move || {
                entered_for_fn.wait();
                release_for_fn.wait();
            })
            .expect("block function creation should succeed");
            ctx_ref
                .globals()
                .set("block", block_fn)
                .expect("block global set should succeed");

            let f: Function<'_> = ctx_ref
                .eval::<Function<'_>, _>("(function(a, o) { block(); return 0; })")
                .expect("eval should produce a function");
            Persistent::save(&ctx_ref, f)
        });
        // The concurrent caller dispatches THIS function (fn_id 1) — it must not
        // touch the barriers, or it would park with no partner and deadlock.
        let noop_func: Persistent<Function<'static>> = ctx.with(|ctx_ref: Ctx<'_>| {
            let f: Function<'_> = ctx_ref
                .eval::<Function<'_>, _>("(function(a, o) { return 0; })")
                .expect("eval should produce a function");
            Persistent::save(&ctx_ref, f)
        });

        let (vm_loader_data, data_ref): (VmLoaderData, &'static JsLoaderData) =
            make_loader_data(runtime, ctx, vec![func, noop_func]);

        // VmLoaderData is a thin pointer wrapper; move its address across the
        // thread boundary as a usize to satisfy Send, then rebuild it inside.
        let data_addr: usize = vm_loader_data.data as usize;

        let handle: std::thread::JoinHandle<AbiError> = std::thread::spawn(move || {
            let vm_loader_data_a: VmLoaderData = VmLoaderData {
                data: data_addr as *mut core::ffi::c_void,
            };
            // SAFETY: data_addr is the live leaked JsLoaderData pointer; it
            // outlives all threads in this test. The guest fn ignores its args.
            unsafe {
                js_dispatch_impl(
                    vm_loader_data_a,
                    GuestContractInstance::null(),
                    0,
                    core::ptr::null(),
                    core::ptr::null_mut(),
                    core::ptr::null_mut(),
                )
            }
        });

        // Wait until thread A is confirmed inside its dispatch.
        entered.wait();

        // From THIS (different) thread, dispatch into the SAME Context. This must
        // not be rejected; it blocks on rquickjs's lock until A releases it.
        let main_handle: std::thread::JoinHandle<AbiError> = std::thread::spawn(move || {
            let vm_loader_data_b: VmLoaderData = VmLoaderData {
                data: data_addr as *mut core::ffi::c_void,
            };
            // SAFETY: same live leaked pointer as above. fn_id 1 is the no-op
            // function — dispatching fn_id 0 here would re-enter the barrier
            // choreography with no partner and deadlock.
            unsafe {
                js_dispatch_impl(
                    vm_loader_data_b,
                    GuestContractInstance::null(),
                    1,
                    core::ptr::null(),
                    core::ptr::null_mut(),
                    core::ptr::null_mut(),
                )
            }
        });

        // Unblock thread A so it finishes and frees the lock, allowing the
        // concurrent dispatch to complete.
        release.wait();

        let a_result: AbiError = handle.join().expect("thread A must not panic");
        let b_result: AbiError = main_handle
            .join()
            .expect("concurrent thread must not panic");

        assert!(a_result.is_ok(), "the initial dispatch must succeed");
        assert!(
            b_result.is_ok(),
            "a concurrent cross-thread dispatch must succeed, not return ReentrantCall (got code {})",
            b_result.code
        );
        assert!(
            data_ref
                .in_dispatch_threads
                .lock()
                .expect("tracking mutex must not be poisoned")
                .is_empty(),
            "thread tracking must be empty after both dispatches return"
        );
    }
}