barbacane-wasm 0.7.0

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

use std::collections::HashMap;
use std::sync::Arc;

use wasmtime::{Caller, Engine, Instance, Linker, Memory, Store, TypedFunc};

use barbacane_plugin_sdk::types::base64_body;
use serde::Deserialize;
use std::collections::BTreeMap;

use crate::broker::BrokerMessage;
use crate::engine::CompiledModule;
use crate::error::WasmError;
use crate::http_client::{
    HttpClient, HttpRequest as HttpClientRequest, HttpResponse as HttpClientResponse,
};
use crate::limits::PluginLimits;

/// Events sent through the streaming channel by `host_http_stream` (ADR-0023).
///
/// The host function sends `Headers` once (before any chunks), then zero or
/// more `Chunk` events. The sender is dropped when the upstream stream ends,
/// signalling the receiver that the body is complete.
#[derive(Debug)]
pub enum StreamEvent {
    /// Response status and headers from the upstream (sent before body chunks).
    Headers {
        status: u16,
        headers: BTreeMap<String, String>,
    },
    /// Body chunk forwarded from the upstream streaming response.
    Chunk(bytes::Bytes),
}

/// HTTP request format from WASM plugins.
/// This matches the format used by http-upstream plugin.
///
/// The `body` field uses base64 encoding over JSON to support binary payloads
/// (e.g. multipart/form-data with file uploads).
#[derive(Debug, Deserialize)]
pub(crate) struct PluginHttpRequest {
    pub(crate) method: String,
    pub(crate) url: String,
    #[serde(default)]
    pub(crate) headers: BTreeMap<String, String>,
    #[serde(default, with = "base64_body")]
    pub(crate) body: Option<Vec<u8>>,
    #[serde(default)]
    pub(crate) timeout_ms: Option<u64>,
}

/// Per-request context passed to plugins.
#[derive(Debug, Clone, Default)]
pub struct RequestContext {
    /// Key-value store for inter-middleware communication.
    pub values: HashMap<String, String>,

    /// Result buffer for host_context_get.
    pub last_get_result: Option<String>,

    /// Trace ID for distributed tracing.
    pub trace_id: String,

    /// Request ID.
    pub request_id: String,
}

impl RequestContext {
    /// Create a new request context.
    pub fn new(trace_id: String, request_id: String) -> Self {
        Self {
            values: HashMap::new(),
            last_get_result: None,
            trace_id,
            request_id,
        }
    }
}

/// State attached to each WASM store.
pub struct PluginState {
    /// Plugin name for logging.
    pub plugin_name: String,

    /// Output buffer for plugin results.
    pub output_buffer: Vec<u8>,

    /// Per-request context.
    pub context: RequestContext,

    /// Maximum memory in bytes.
    pub max_memory: usize,

    /// HTTP client for outbound requests (shared).
    pub http_client: Option<Arc<HttpClient>>,

    /// Result buffer for host_http_read_result.
    pub last_http_result: Option<Vec<u8>>,

    /// Resolved secrets store (shared across instances).
    pub secrets: crate::secrets::SecretsStore,

    /// Result buffer for host_secret_read_result.
    pub last_secret_result: Option<Vec<u8>>,

    /// Rate limiter (shared across instances).
    pub rate_limiter: Option<crate::rate_limiter::RateLimiter>,

    /// Result buffer for host_rate_limit_read_result.
    pub last_rate_limit_result: Option<Vec<u8>>,

    /// Response cache (shared across instances).
    pub response_cache: Option<crate::cache::ResponseCache>,

    /// Result buffer for host_cache_read_result.
    pub last_cache_result: Option<Vec<u8>>,

    /// Metrics registry for plugin telemetry (shared).
    pub metrics: Option<Arc<barbacane_telemetry::MetricsRegistry>>,

    /// Kafka publisher for host_kafka_publish (shared).
    pub kafka_publisher: Option<Arc<crate::kafka_client::KafkaPublisher>>,

    /// NATS publisher for host_nats_publish (shared).
    pub nats_publisher: Option<Arc<crate::nats_client::NatsPublisher>>,

    /// Result buffer for host_kafka_publish / host_nats_publish.
    pub last_broker_result: Option<Vec<u8>>,

    /// Result buffer for host_uuid_read_result.
    pub last_uuid_result: Option<Vec<u8>>,

    /// Channel sender for host_http_stream (ADR-0023).
    ///
    /// Set by the host before calling a streaming-capable dispatcher. The host
    /// function sends `StreamEvent::Headers` once, then `StreamEvent::Chunk` for
    /// each body chunk, then drops the sender to signal end-of-stream.
    pub stream_sender: Option<Arc<tokio::sync::mpsc::UnboundedSender<StreamEvent>>>,

    /// Upstream WebSocket upgrade request from `host_ws_upgrade` (ADR-0026).
    ///
    /// After a successful `host_ws_upgrade`, the request params are stored here.
    /// The actual connection is deferred to the async relay task on the main
    /// runtime, because the TcpStream must be created on the runtime that will
    /// drive it (a temporary runtime's I/O driver dies when the runtime drops).
    pub ws_upgrade_request: Option<crate::ws_client::WsUpgradeRequest>,

    // --- Side-channel body buffers ---
    // Bodies travel as raw bytes via dedicated host functions instead of
    // base64-encoded inside JSON. This eliminates the ~3.65× memory overhead
    // and allows 10MB+ bodies within the default 16MB WASM memory limit.
    /// Request/response body held by the host, set before calling the handler.
    /// Plugins read it via `host_body_len()` + `host_body_read()`.
    pub request_body: Option<Vec<u8>>,

    /// Output body set by the plugin via `host_body_set()` or `host_body_clear()`.
    /// Outer Option: was the function called? Inner Option: body or None.
    pub output_body: Option<Option<Vec<u8>>>,

    /// HTTP response body from `host_http_call`, held separately from the
    /// JSON metadata in `last_http_result`. Plugins read it via
    /// `host_http_response_body_len()` + `host_http_response_body_read()`.
    pub http_response_body: Option<Vec<u8>>,

    /// Outbound HTTP request body set by the plugin via
    /// `host_http_request_body_set()`. Consumed by `host_http_call`.
    pub http_request_body: Option<Vec<u8>>,
}

#[allow(dead_code)] // Constructors used by different pool configurations
impl PluginState {
    /// Create new plugin state.
    pub fn new(plugin_name: String, limits: &PluginLimits) -> Self {
        Self {
            plugin_name,
            output_buffer: Vec::new(),
            context: RequestContext::default(),
            max_memory: limits.max_memory_bytes,
            http_client: None,
            last_http_result: None,
            secrets: crate::secrets::SecretsStore::new(),
            last_secret_result: None,
            rate_limiter: None,
            last_rate_limit_result: None,
            response_cache: None,
            last_cache_result: None,
            metrics: None,
            kafka_publisher: None,
            nats_publisher: None,
            last_broker_result: None,
            last_uuid_result: None,
            stream_sender: None,
            ws_upgrade_request: None,
            request_body: None,
            output_body: None,
            http_response_body: None,
            http_request_body: None,
        }
    }

    /// Create new plugin state with HTTP client.
    pub fn with_http_client(
        plugin_name: String,
        limits: &PluginLimits,
        http_client: Arc<HttpClient>,
    ) -> Self {
        Self {
            plugin_name,
            output_buffer: Vec::new(),
            context: RequestContext::default(),
            max_memory: limits.max_memory_bytes,
            http_client: Some(http_client),
            last_http_result: None,
            secrets: crate::secrets::SecretsStore::new(),
            last_secret_result: None,
            rate_limiter: None,
            last_rate_limit_result: None,
            response_cache: None,
            last_cache_result: None,
            metrics: None,
            kafka_publisher: None,
            nats_publisher: None,
            last_broker_result: None,
            last_uuid_result: None,
            stream_sender: None,
            ws_upgrade_request: None,
            request_body: None,
            output_body: None,
            http_response_body: None,
            http_request_body: None,
        }
    }

    /// Create new plugin state with HTTP client and secrets.
    pub fn with_http_client_and_secrets(
        plugin_name: String,
        limits: &PluginLimits,
        http_client: Arc<HttpClient>,
        secrets: crate::secrets::SecretsStore,
    ) -> Self {
        Self {
            plugin_name,
            output_buffer: Vec::new(),
            context: RequestContext::default(),
            max_memory: limits.max_memory_bytes,
            http_client: Some(http_client),
            last_http_result: None,
            secrets,
            last_secret_result: None,
            rate_limiter: None,
            last_rate_limit_result: None,
            response_cache: None,
            last_cache_result: None,
            metrics: None,
            kafka_publisher: None,
            nats_publisher: None,
            last_broker_result: None,
            last_uuid_result: None,
            stream_sender: None,
            ws_upgrade_request: None,
            request_body: None,
            output_body: None,
            http_response_body: None,
            http_request_body: None,
        }
    }

    /// Create new plugin state with all options.
    #[allow(clippy::too_many_arguments)]
    pub fn with_all_options(
        plugin_name: String,
        limits: &PluginLimits,
        http_client: Option<Arc<HttpClient>>,
        secrets: crate::secrets::SecretsStore,
        rate_limiter: Option<crate::rate_limiter::RateLimiter>,
        response_cache: Option<crate::cache::ResponseCache>,
        nats_publisher: Option<Arc<crate::nats_client::NatsPublisher>>,
        kafka_publisher: Option<Arc<crate::kafka_client::KafkaPublisher>>,
    ) -> Self {
        Self {
            plugin_name,
            output_buffer: Vec::new(),
            context: RequestContext::default(),
            max_memory: limits.max_memory_bytes,
            http_client,
            last_http_result: None,
            secrets,
            last_secret_result: None,
            rate_limiter,
            last_rate_limit_result: None,
            response_cache,
            last_cache_result: None,
            metrics: None,
            kafka_publisher,
            nats_publisher,
            last_broker_result: None,
            last_uuid_result: None,
            stream_sender: None,
            ws_upgrade_request: None,
            request_body: None,
            output_body: None,
            http_response_body: None,
            http_request_body: None,
        }
    }

    /// Create new plugin state with all options including metrics.
    #[allow(clippy::too_many_arguments)]
    pub fn with_all_options_and_metrics(
        plugin_name: String,
        limits: &PluginLimits,
        http_client: Option<Arc<HttpClient>>,
        secrets: crate::secrets::SecretsStore,
        rate_limiter: Option<crate::rate_limiter::RateLimiter>,
        response_cache: Option<crate::cache::ResponseCache>,
        nats_publisher: Option<Arc<crate::nats_client::NatsPublisher>>,
        kafka_publisher: Option<Arc<crate::kafka_client::KafkaPublisher>>,
        metrics: Option<Arc<barbacane_telemetry::MetricsRegistry>>,
    ) -> Self {
        Self {
            plugin_name,
            output_buffer: Vec::new(),
            context: RequestContext::default(),
            max_memory: limits.max_memory_bytes,
            http_client,
            last_http_result: None,
            secrets,
            last_secret_result: None,
            rate_limiter,
            last_rate_limit_result: None,
            response_cache,
            last_cache_result: None,
            metrics,
            kafka_publisher,
            nats_publisher,
            last_broker_result: None,
            last_uuid_result: None,
            stream_sender: None,
            ws_upgrade_request: None,
            request_body: None,
            output_body: None,
            http_response_body: None,
            http_request_body: None,
        }
    }

    /// Get the output buffer contents.
    pub fn take_output(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.output_buffer)
    }

    /// Set the request context for this call.
    pub fn set_context(&mut self, context: RequestContext) {
        self.context = context;
    }

    /// Set the stream sender for host_http_stream (ADR-0023).
    pub fn set_stream_sender(
        &mut self,
        sender: Arc<tokio::sync::mpsc::UnboundedSender<StreamEvent>>,
    ) {
        self.stream_sender = Some(sender);
    }

    /// Take the upstream WebSocket upgrade request from host_ws_upgrade (ADR-0026).
    pub fn take_ws_upgrade_request(&mut self) -> Option<crate::ws_client::WsUpgradeRequest> {
        self.ws_upgrade_request.take()
    }

    /// Set the request body for the next handler call (side-channel).
    pub fn set_request_body(&mut self, body: Option<Vec<u8>>) {
        self.request_body = body;
    }

    /// Take the output body set by the plugin via host_body_set/host_body_clear.
    /// Returns `None` if the plugin didn't call either function (body unchanged).
    /// Returns `Some(None)` if the plugin called host_body_clear.
    /// Returns `Some(Some(bytes))` if the plugin called host_body_set.
    pub fn take_output_body(&mut self) -> Option<Option<Vec<u8>>> {
        self.output_body.take()
    }
}

impl wasmtime::ResourceLimiter for PluginState {
    fn memory_growing(
        &mut self,
        _current: usize,
        desired: usize,
        _maximum: Option<usize>,
    ) -> Result<bool, wasmtime::Error> {
        Ok(desired <= self.max_memory)
    }

    fn table_growing(
        &mut self,
        _current: usize,
        desired: usize,
        _maximum: Option<usize>,
    ) -> Result<bool, wasmtime::Error> {
        // Allow reasonable table growth
        Ok(desired <= 10_000)
    }
}

/// A WASM plugin instance ready for execution.
pub struct PluginInstance {
    store: Store<PluginState>,
    _instance: Instance,
    limits: PluginLimits,

    // Cached function references
    init_func: Option<TypedFunc<(i32, i32), i32>>,
    on_request_func: Option<TypedFunc<(i32, i32), i32>>,
    on_response_func: Option<TypedFunc<(i32, i32), i32>>,
    dispatch_func: Option<TypedFunc<(i32, i32), i32>>,
    alloc_func: Option<TypedFunc<i32, i32>>,
    memory: Memory,
}

impl PluginInstance {
    /// Create a new plugin instance from a compiled module.
    pub fn new(
        engine: &Engine,
        module: &CompiledModule,
        limits: PluginLimits,
    ) -> Result<Self, WasmError> {
        Self::new_with_options(engine, module, limits, None, None)
    }

    /// Create a new plugin instance with an HTTP client for outbound calls.
    pub fn new_with_http_client(
        engine: &Engine,
        module: &CompiledModule,
        limits: PluginLimits,
        http_client: Option<Arc<HttpClient>>,
    ) -> Result<Self, WasmError> {
        Self::new_with_options(engine, module, limits, http_client, None)
    }

    /// Create a new plugin instance with HTTP client and secrets.
    pub fn new_with_options(
        engine: &Engine,
        module: &CompiledModule,
        limits: PluginLimits,
        http_client: Option<Arc<HttpClient>>,
        secrets: Option<crate::secrets::SecretsStore>,
    ) -> Result<Self, WasmError> {
        Self::new_with_all_options(
            engine,
            module,
            limits,
            http_client,
            secrets,
            None,
            None,
            None,
            None,
        )
    }

    /// Create a new plugin instance with all options including rate limiter and cache.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_all_options(
        engine: &Engine,
        module: &CompiledModule,
        limits: PluginLimits,
        http_client: Option<Arc<HttpClient>>,
        secrets: Option<crate::secrets::SecretsStore>,
        rate_limiter: Option<crate::rate_limiter::RateLimiter>,
        response_cache: Option<crate::cache::ResponseCache>,
        nats_publisher: Option<Arc<crate::nats_client::NatsPublisher>>,
        kafka_publisher: Option<Arc<crate::kafka_client::KafkaPublisher>>,
    ) -> Result<Self, WasmError> {
        let state = PluginState::with_all_options(
            module.name.clone(),
            &limits,
            http_client,
            secrets.unwrap_or_default(),
            rate_limiter,
            response_cache,
            nats_publisher,
            kafka_publisher,
        );
        let mut store = Store::new(engine, state);

        // Set fuel for execution limiting
        store
            .set_fuel(limits.max_fuel)
            .map_err(|e| WasmError::Instantiation(format!("failed to set fuel: {}", e)))?;

        // Enable resource limiting
        store.limiter(|state| state);

        // Create linker and add host functions
        let mut linker = Linker::new(engine);
        add_host_functions(&mut linker)?;

        // Instantiate the module
        let instance = linker
            .instantiate(&mut store, module.module())
            .map_err(|e| WasmError::Instantiation(e.to_string()))?;

        // Get memory
        let memory = instance
            .get_memory(&mut store, "memory")
            .ok_or_else(|| WasmError::MissingExport("memory".into()))?;

        // Cache function references
        let init_func = instance
            .get_typed_func::<(i32, i32), i32>(&mut store, "init")
            .ok();
        let on_request_func = instance
            .get_typed_func::<(i32, i32), i32>(&mut store, "on_request")
            .ok();
        let on_response_func = instance
            .get_typed_func::<(i32, i32), i32>(&mut store, "on_response")
            .ok();
        let dispatch_func = instance
            .get_typed_func::<(i32, i32), i32>(&mut store, "dispatch")
            .ok();
        let alloc_func = instance
            .get_typed_func::<i32, i32>(&mut store, "alloc")
            .ok();

        Ok(Self {
            store,
            _instance: instance,
            limits,
            init_func,
            on_request_func,
            on_response_func,
            dispatch_func,
            alloc_func,
            memory,
        })
    }

    /// Get the plugin name.
    pub fn name(&self) -> &str {
        &self.store.data().plugin_name
    }

    /// Write data to the plugin's linear memory and return the pointer.
    ///
    /// Uses the plugin's exported `alloc` function so that dlmalloc is aware
    /// of the allocation and will not reuse the region during deserialization.
    /// Falls back to growing memory directly for legacy plugins that lack the
    /// `alloc` export (only safe for very small payloads like config JSON).
    pub fn write_to_memory(&mut self, data: &[u8]) -> Result<i32, WasmError> {
        if data.is_empty() {
            return Ok(0);
        }

        if let Some(alloc_func) = self.alloc_func.clone() {
            // Allocate via the plugin's own allocator — dlmalloc tracks this
            // region and will not hand it out again during deserialization.
            let ptr = alloc_func
                .call(&mut self.store, data.len() as i32)
                .map_err(|e| WasmError::Trap(format!("alloc failed: {}", e)))?;

            if ptr == 0 {
                let current_size = self.memory.data_size(&self.store);
                return Err(WasmError::MemoryLimitExceeded {
                    requested: data.len(),
                    limit: self.limits.max_memory_bytes.saturating_sub(current_size),
                });
            }

            self.memory
                .write(&mut self.store, ptr as usize, data)
                .map_err(|e| WasmError::Trap(format!("memory write failed: {}", e)))?;

            Ok(ptr)
        } else {
            // Legacy fallback: grow memory and write at the new region.
            // Only safe for small payloads (e.g. config JSON during init).
            let current_size = self.memory.data_size(&self.store);
            let needed = current_size + data.len();

            if needed > self.limits.max_memory_bytes {
                return Err(WasmError::MemoryLimitExceeded {
                    requested: data.len(),
                    limit: self.limits.max_memory_bytes.saturating_sub(current_size),
                });
            }

            const PAGE_SIZE: usize = 65_536;
            let pages_needed = data.len().div_ceil(PAGE_SIZE);

            self.memory
                .grow(&mut self.store, pages_needed as u64)
                .map_err(|_| WasmError::MemoryLimitExceeded {
                    requested: data.len(),
                    limit: self.limits.max_memory_bytes.saturating_sub(current_size),
                })?;

            let ptr = current_size;
            self.memory
                .write(&mut self.store, ptr, data)
                .map_err(|e| WasmError::Trap(format!("memory write failed: {}", e)))?;

            Ok(ptr as i32)
        }
    }

    /// Call the init function with the given config.
    pub fn init(&mut self, config_json: &[u8]) -> Result<i32, WasmError> {
        let init_func = self
            .init_func
            .clone()
            .ok_or_else(|| WasmError::MissingExport("init".into()))?;

        // Write config to memory
        let ptr = self.write_to_memory(config_json)?;
        let len = config_json.len() as i32;

        // Reset fuel for this call
        if let Err(e) = self.store.set_fuel(self.limits.max_fuel) {
            tracing::warn!(error = %e, "failed to reset WASM fuel");
        }

        // Call init
        let result = init_func
            .call(&mut self.store, (ptr, len))
            .map_err(|e| WasmError::Trap(e.to_string()))?;

        Ok(result)
    }

    /// Call on_request with the given request data.
    pub fn on_request(&mut self, request_json: &[u8]) -> Result<i32, WasmError> {
        let func = self
            .on_request_func
            .clone()
            .ok_or_else(|| WasmError::MissingExport("on_request".into()))?;

        self.call_handler(func, request_json)
    }

    /// Call on_response with the given response data.
    pub fn on_response(&mut self, response_json: &[u8]) -> Result<i32, WasmError> {
        let func = self
            .on_response_func
            .clone()
            .ok_or_else(|| WasmError::MissingExport("on_response".into()))?;

        self.call_handler(func, response_json)
    }

    /// Call dispatch with the given request data.
    pub fn dispatch(&mut self, request_json: &[u8]) -> Result<i32, WasmError> {
        let func = self
            .dispatch_func
            .clone()
            .ok_or_else(|| WasmError::MissingExport("dispatch".into()))?;

        self.call_handler(func, request_json)
    }

    /// Call a handler function with data.
    fn call_handler(
        &mut self,
        func: TypedFunc<(i32, i32), i32>,
        data: &[u8],
    ) -> Result<i32, WasmError> {
        // Clear output buffer
        self.store.data_mut().output_buffer.clear();

        // Reset fuel before write_to_memory — the `alloc` call runs plugin
        // code and needs fuel. Scale fuel with payload size: large bodies
        // require proportionally more instructions for serde + base64.
        let fuel = self.limits.max_fuel.max(data.len() as u64 * 100);
        if let Err(e) = self.store.set_fuel(fuel) {
            tracing::warn!(error = %e, "failed to reset WASM fuel");
        }

        // Write data to memory (may call plugin's `alloc` export)
        let ptr = self.write_to_memory(data)?;
        let len = data.len() as i32;

        // Call function
        let result = func
            .call(&mut self.store, (ptr, len))
            .map_err(|e| WasmError::Trap(e.to_string()))?;

        Ok(result)
    }

    /// Get the output buffer contents.
    pub fn take_output(&mut self) -> Vec<u8> {
        self.store.data_mut().take_output()
    }

    /// Set the request context for the next call.
    pub fn set_context(&mut self, context: RequestContext) {
        self.store.data_mut().set_context(context);
    }

    /// Get the current request context (after modifications by host functions).
    pub fn get_context(&self) -> RequestContext {
        self.store.data().context.clone()
    }

    /// Take the last HTTP result buffer (from `host_http_call` or `host_http_stream`).
    ///
    /// Returns `None` if no HTTP call was made or the result was already taken.
    pub fn take_last_http_result(&mut self) -> Option<Vec<u8>> {
        self.store.data_mut().last_http_result.take()
    }

    /// Inject a stream sender for `host_http_stream` before calling `dispatch`.
    ///
    /// The sender is wrapped in an `Arc` so host functions can clone it for
    /// use inside `std::thread::scope` without lifetime conflicts.
    pub fn set_stream_sender(
        &mut self,
        sender: Arc<tokio::sync::mpsc::UnboundedSender<StreamEvent>>,
    ) {
        self.store.data_mut().set_stream_sender(sender);
    }

    /// Take the upstream WebSocket upgrade request from `host_ws_upgrade` (ADR-0026).
    ///
    /// Returns `None` if no WebSocket upgrade was requested or the request
    /// was already taken.
    pub fn take_ws_upgrade_request(&mut self) -> Option<crate::ws_client::WsUpgradeRequest> {
        self.store.data_mut().take_ws_upgrade_request()
    }

    /// Set the request/response body for the next handler call (side-channel).
    pub fn set_request_body(&mut self, body: Option<Vec<u8>>) {
        self.store.data_mut().set_request_body(body);
    }

    /// Take the output body set by the plugin via host_body_set/host_body_clear.
    pub fn take_output_body(&mut self) -> Option<Option<Vec<u8>>> {
        self.store.data_mut().take_output_body()
    }
}

/// Register a `host_*_read_result` function that copies data from plugin state to WASM memory.
///
/// All read_result host functions follow the same pattern: take a result buffer from state,
/// get the WASM memory export, copy bytes into the provided buffer, return bytes written.
fn add_read_result_fn(
    linker: &mut Linker<PluginState>,
    name: &str,
    extract: impl Fn(&mut PluginState) -> Option<Vec<u8>> + Send + Sync + 'static,
) -> Result<(), WasmError> {
    linker
        .func_wrap(
            "barbacane",
            name,
            move |mut caller: Caller<'_, PluginState>, buf_ptr: i32, buf_len: i32| -> i32 {
                let result = extract(caller.data_mut());
                if let Some(data) = result {
                    let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                        Some(m) => m,
                        None => return 0,
                    };
                    let copy_len = std::cmp::min(data.len(), buf_len as usize);
                    if memory
                        .write(&mut caller, buf_ptr as usize, &data[..copy_len])
                        .is_ok()
                    {
                        return copy_len as i32;
                    }
                }
                0
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add {}: {}", name, e)))?;
    Ok(())
}

/// Add host functions to the linker.
fn add_host_functions(linker: &mut Linker<PluginState>) -> Result<(), WasmError> {
    // host_set_output - always available
    linker
        .func_wrap(
            "barbacane",
            "host_set_output",
            |mut caller: Caller<'_, PluginState>, ptr: i32, len: i32| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let start = ptr as usize;
                let end = start + len as usize;
                let data = memory.data(&caller);

                if end <= data.len() {
                    let bytes = data[start..end].to_vec();
                    caller.data_mut().output_buffer = bytes;
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_set_output: {}", e)))?;

    // --- Side-channel body host functions ---
    // Bodies travel as raw bytes instead of base64-in-JSON, eliminating
    // the ~3.65× memory overhead per boundary crossing.

    // host_body_len — returns the length of the held body, or -1 if None.
    linker
        .func_wrap(
            "barbacane",
            "host_body_len",
            |caller: Caller<'_, PluginState>| -> i64 {
                match &caller.data().request_body {
                    Some(body) => body.len() as i64,
                    None => -1,
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_body_len: {}", e)))?;

    // host_body_read — copy the held body into WASM memory at ptr.
    add_read_result_fn(linker, "host_body_read", |state| state.request_body.take())?;

    // host_body_set — set the output body from raw bytes in WASM memory.
    linker
        .func_wrap(
            "barbacane",
            "host_body_set",
            |mut caller: Caller<'_, PluginState>, ptr: i32, len: i32| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let start = ptr as usize;
                let end = start + len as usize;
                let data = memory.data(&caller);

                if end <= data.len() {
                    let bytes = data[start..end].to_vec();
                    caller.data_mut().output_body = Some(Some(bytes));
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_body_set: {}", e)))?;

    // host_body_clear — explicitly set the output body to None.
    linker
        .func_wrap(
            "barbacane",
            "host_body_clear",
            |mut caller: Caller<'_, PluginState>| {
                caller.data_mut().output_body = Some(None);
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_body_clear: {}", e)))?;

    // host_http_response_body_len — length of the HTTP response body from host_http_call.
    linker
        .func_wrap(
            "barbacane",
            "host_http_response_body_len",
            |caller: Caller<'_, PluginState>| -> i64 {
                match &caller.data().http_response_body {
                    Some(body) => body.len() as i64,
                    None => -1,
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_http_response_body_len: {}", e))
        })?;

    // host_http_response_body_read — copy HTTP response body into WASM memory.
    add_read_result_fn(linker, "host_http_response_body_read", |state| {
        state.http_response_body.take()
    })?;

    // host_http_request_body_set — set the outbound HTTP request body from WASM memory.
    linker
        .func_wrap(
            "barbacane",
            "host_http_request_body_set",
            |mut caller: Caller<'_, PluginState>, ptr: i32, len: i32| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let start = ptr as usize;
                let end = start + len as usize;
                let data = memory.data(&caller);

                if end <= data.len() {
                    let bytes = data[start..end].to_vec();
                    caller.data_mut().http_request_body = Some(bytes);
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_http_request_body_set: {}", e))
        })?;

    // host_log
    linker
        .func_wrap(
            "barbacane",
            "host_log",
            |mut caller: Caller<'_, PluginState>, level: i32, msg_ptr: i32, msg_len: i32| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let start = msg_ptr as usize;
                let end = start + msg_len as usize;
                let data = memory.data(&caller);

                if end <= data.len() {
                    if let Ok(message) = std::str::from_utf8(&data[start..end]) {
                        let plugin_name = caller.data().plugin_name.clone();
                        match level {
                            0 => tracing::error!(plugin = %plugin_name, "{}", message),
                            1 => tracing::warn!(plugin = %plugin_name, "{}", message),
                            2 => tracing::info!(plugin = %plugin_name, "{}", message),
                            _ => tracing::debug!(plugin = %plugin_name, "{}", message),
                        }
                    }
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_log: {}", e)))?;

    // host_context_get
    linker
        .func_wrap(
            "barbacane",
            "host_context_get",
            |mut caller: Caller<'_, PluginState>, key_ptr: i32, key_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = key_ptr as usize;
                let end = start + key_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                let key = match std::str::from_utf8(&data[start..end]) {
                    Ok(k) => k.to_string(),
                    Err(_) => return -1,
                };

                match caller.data().context.values.get(&key).cloned() {
                    Some(value) => {
                        let len = value.len() as i32;
                        caller.data_mut().context.last_get_result = Some(value);
                        len
                    }
                    None => -1,
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_context_get: {}", e)))?;

    // host_context_read_result
    add_read_result_fn(linker, "host_context_read_result", |state| {
        state.context.last_get_result.take().map(String::into_bytes)
    })?;

    // host_context_set
    linker
        .func_wrap(
            "barbacane",
            "host_context_set",
            |mut caller: Caller<'_, PluginState>,
             key_ptr: i32,
             key_len: i32,
             val_ptr: i32,
             val_len: i32| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let key_start = key_ptr as usize;
                let key_end = key_start + key_len as usize;
                let val_start = val_ptr as usize;
                let val_end = val_start + val_len as usize;

                // Read data first, then mutate
                let data = memory.data(&caller);
                if key_end <= data.len() && val_end <= data.len() {
                    let key_result =
                        std::str::from_utf8(&data[key_start..key_end]).map(String::from);
                    let val_result =
                        std::str::from_utf8(&data[val_start..val_end]).map(String::from);

                    if let (Ok(key), Ok(value)) = (key_result, val_result) {
                        caller.data_mut().context.values.insert(key, value);
                    }
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_context_set: {}", e)))?;

    // host_clock_now
    linker
        .func_wrap(
            "barbacane",
            "host_clock_now",
            |_caller: Caller<'_, PluginState>| -> i64 {
                use std::time::Instant;

                static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
                let start = START.get_or_init(Instant::now);

                start.elapsed().as_millis() as i64
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_clock_now: {}", e)))?;

    // host_time_now - alias for host_clock_now (deprecated, use host_clock_now)
    linker
        .func_wrap(
            "barbacane",
            "host_time_now",
            |_caller: Caller<'_, PluginState>| -> i64 {
                use std::time::Instant;

                static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
                let start = START.get_or_init(Instant::now);

                start.elapsed().as_millis() as i64
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_time_now: {}", e)))?;

    // host_get_unix_timestamp - returns current Unix timestamp in seconds
    linker
        .func_wrap(
            "barbacane",
            "host_get_unix_timestamp",
            |_caller: Caller<'_, PluginState>| -> u64 {
                use std::time::{SystemTime, UNIX_EPOCH};

                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0)
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_get_unix_timestamp: {}", e))
        })?;

    // host_uuid_generate - generates UUID v7 and returns length
    linker
        .func_wrap(
            "barbacane",
            "host_uuid_generate",
            |mut caller: Caller<'_, PluginState>| -> i32 {
                let uuid = uuid::Uuid::now_v7().to_string();
                let len = uuid.len() as i32;
                caller.data_mut().last_uuid_result = Some(uuid.into_bytes());
                len
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_uuid_generate: {}", e))
        })?;

    // host_uuid_read_result - copies generated UUID to WASM memory
    add_read_result_fn(linker, "host_uuid_read_result", |state| {
        state.last_uuid_result.take()
    })?;

    // host_http_call - make outbound HTTP request
    linker
        .func_wrap(
            "barbacane",
            "host_http_call",
            |mut caller: Caller<'_, PluginState>, req_ptr: i32, req_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = req_ptr as usize;
                let end = start + req_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Parse the request JSON from plugin format
                let plugin_request: PluginHttpRequest =
                    match serde_json::from_slice(&data[start..end]) {
                        Ok(r) => r,
                        Err(e) => {
                            tracing::error!("failed to parse HTTP request: {}", e);
                            return -1;
                        }
                    };

                // Body priority: side-channel (host_http_request_body_set) > JSON body.
                // Side-channel avoids base64 overhead for large payloads.
                let body = caller
                    .data_mut()
                    .http_request_body
                    .take()
                    .or(plugin_request.body);

                let request = HttpClientRequest {
                    method: plugin_request.method,
                    url: plugin_request.url,
                    headers: plugin_request.headers.into_iter().collect(),
                    body,
                    timeout: plugin_request
                        .timeout_ms
                        .map(std::time::Duration::from_millis),
                };

                // Get the HTTP client
                let http_client = match caller.data().http_client.clone() {
                    Some(c) => c,
                    None => {
                        tracing::error!("HTTP client not available");
                        return -1;
                    }
                };

                // Use a separate runtime to avoid deadlock with the main runtime.
                // The main runtime is blocked waiting for the WASM call to complete,
                // so we can't schedule work on it. Create a new runtime just for this call.
                // TODO: Optimize by using a thread-local runtime or worker pool instead of
                // creating a new runtime per call (performance improvement for high throughput).
                let response_result = std::thread::scope(|s| {
                    let handle = s.spawn(|| {
                        let rt = match tokio::runtime::Builder::new_current_thread()
                            .enable_all()
                            .build()
                        {
                            Ok(rt) => rt,
                            Err(e) => {
                                tracing::error!("failed to create runtime: {}", e);
                                return None;
                            }
                        };

                        rt.block_on(async {
                            match http_client.call(request).await {
                                Ok(mut response) => {
                                    // Strip body into side-channel to avoid base64
                                    // encoding in the JSON metadata.
                                    let body = response.body.take();
                                    let json = serde_json::to_vec(&response).ok();
                                    Some((json, body))
                                }
                                Err(e) => {
                                    tracing::error!("HTTP call failed: {}", e);
                                    // Return error response
                                    let error_response = match e {
                                        crate::http_client::HttpClientError::Timeout => {
                                            HttpClientResponse::error(
                                                504,
                                                "urn:barbacane:error:upstream-timeout",
                                                "Gateway Timeout",
                                                "Upstream request timed out",
                                            )
                                        }
                                        crate::http_client::HttpClientError::CircuitOpen(host) => {
                                            HttpClientResponse::error(
                                                503,
                                                "urn:barbacane:error:circuit-open",
                                                "Service Unavailable",
                                                &format!("Circuit breaker open for {}", host),
                                            )
                                        }
                                        crate::http_client::HttpClientError::ConnectionFailed(
                                            _,
                                        ) => HttpClientResponse::error(
                                            502,
                                            "urn:barbacane:error:upstream-unavailable",
                                            "Bad Gateway",
                                            "Failed to connect to upstream",
                                        ),
                                        _ => HttpClientResponse::error(
                                            502,
                                            "urn:barbacane:error:upstream-unavailable",
                                            "Bad Gateway",
                                            &e.to_string(),
                                        ),
                                    };
                                    let json = serde_json::to_vec(&error_response).ok();
                                    Some((json, None))
                                }
                            }
                        })
                    });

                    match handle.join() {
                        Ok(result) => result,
                        Err(e) => {
                            tracing::error!("worker thread panicked: {:?}", e);
                            None
                        }
                    }
                });

                match response_result {
                    Some((Some(json), body)) => {
                        let len = json.len() as i32;
                        caller.data_mut().last_http_result = Some(json);
                        caller.data_mut().http_response_body = body;
                        len
                    }
                    _ => -1,
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_http_call: {}", e)))?;

    // host_http_read_result - read HTTP response (works for both host_http_call and host_http_stream)
    add_read_result_fn(linker, "host_http_read_result", |state| {
        state.last_http_result.take()
    })?;

    // host_http_stream - streaming HTTP request (ADR-0023)
    //
    // Same request format as host_http_call. The host immediately begins
    // forwarding response chunks to the client via the stream_sender channel
    // while buffering the complete body in last_http_result.
    // Returns the length of the buffered response, or -1 on error.
    linker
        .func_wrap(
            "barbacane",
            "host_http_stream",
            |mut caller: Caller<'_, PluginState>, req_ptr: i32, req_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = req_ptr as usize;
                let end = start + req_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                let plugin_request: PluginHttpRequest =
                    match serde_json::from_slice(&data[start..end]) {
                        Ok(r) => r,
                        Err(e) => {
                            tracing::error!("host_http_stream: failed to parse request: {}", e);
                            return -1;
                        }
                    };

                // Body priority: side-channel (host_http_request_body_set) > JSON body.
                let body = caller
                    .data_mut()
                    .http_request_body
                    .take()
                    .or(plugin_request.body);

                let request = HttpClientRequest {
                    method: plugin_request.method,
                    url: plugin_request.url,
                    headers: plugin_request.headers.into_iter().collect(),
                    body,
                    timeout: plugin_request
                        .timeout_ms
                        .map(std::time::Duration::from_millis),
                };

                let http_client = match caller.data().http_client.clone() {
                    Some(c) => c,
                    None => {
                        tracing::error!("host_http_stream: HTTP client not available");
                        return -1;
                    }
                };

                // Clone the stream sender (Arc makes this cheap).
                let stream_sender = caller.data().stream_sender.clone();

                let response_result = std::thread::scope(|s| {
                    let handle = s.spawn(|| {
                        let rt = match tokio::runtime::Builder::new_current_thread()
                            .enable_all()
                            .build()
                        {
                            Ok(rt) => rt,
                            Err(e) => {
                                tracing::error!(
                                    "host_http_stream: failed to create runtime: {}",
                                    e
                                );
                                return None;
                            }
                        };

                        rt.block_on(async {
                            use futures_util::StreamExt;

                            match http_client.stream_raw(request).await {
                                Ok(upstream) => {
                                    let status = upstream.status().as_u16();
                                    let upstream_headers: BTreeMap<String, String> = upstream
                                        .headers()
                                        .iter()
                                        .filter_map(|(k, v)| {
                                            v.to_str()
                                                .ok()
                                                .map(|v| (k.as_str().to_lowercase(), v.to_string()))
                                        })
                                        .collect();

                                    // Send headers through the streaming channel.
                                    if let Some(tx) = &stream_sender {
                                        let _ = tx.send(StreamEvent::Headers {
                                            status,
                                            headers: upstream_headers.clone(),
                                        });
                                    }

                                    // Stream body chunks, sending each through the channel
                                    // while building the complete buffer for last_http_result.
                                    let mut buffer: Vec<u8> = Vec::new();
                                    let mut byte_stream = upstream.bytes_stream();

                                    while let Some(chunk_result) = byte_stream.next().await {
                                        match chunk_result {
                                            Ok(chunk) => {
                                                if let Some(tx) = &stream_sender {
                                                    let _ =
                                                        tx.send(StreamEvent::Chunk(chunk.clone()));
                                                }
                                                buffer.extend_from_slice(&chunk);
                                            }
                                            Err(e) => {
                                                tracing::error!(
                                                    "host_http_stream: upstream read error: {}",
                                                    e
                                                );
                                                return None;
                                            }
                                        }
                                    }

                                    // Strip body into side-channel, serialize
                                    // metadata-only JSON for host_http_read_result.
                                    let complete = HttpClientResponse {
                                        status,
                                        headers: upstream_headers.into_iter().collect(),
                                        body: None,
                                    };
                                    let json = serde_json::to_vec(&complete).ok();
                                    Some((json, Some(buffer)))
                                }
                                Err(e) => {
                                    tracing::error!("host_http_stream: request failed: {}", e);
                                    None
                                }
                            }
                        })
                    });

                    match handle.join() {
                        Ok(result) => result,
                        Err(e) => {
                            tracing::error!("host_http_stream: worker thread panicked: {:?}", e);
                            None
                        }
                    }
                });

                match response_result {
                    Some((Some(json), body)) => {
                        let len = json.len() as i32;
                        caller.data_mut().last_http_result = Some(json);
                        caller.data_mut().http_response_body = body;
                        len
                    }
                    _ => -1,
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_http_stream: {}", e)))?;

    // host_ws_upgrade - request an upstream WebSocket connection (ADR-0026)
    //
    // The plugin sends a JSON payload: { url, connect_timeout_ms, headers }.
    // The request is validated and stored in PluginState. The actual TCP
    // connection is deferred to the async relay task on the main tokio runtime,
    // because a TcpStream must be created on the runtime that will drive it
    // (a temporary runtime's I/O driver dies when the runtime drops).
    // Returns 0 on success (valid request), -1 on parse failure.
    linker
        .func_wrap(
            "barbacane",
            "host_ws_upgrade",
            |mut caller: Caller<'_, PluginState>, req_ptr: i32, req_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = req_ptr as usize;
                let end = start + req_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                let ws_request: crate::ws_client::WsUpgradeRequest =
                    match serde_json::from_slice(&data[start..end]) {
                        Ok(r) => r,
                        Err(e) => {
                            tracing::error!("host_ws_upgrade: failed to parse request: {}", e);
                            let err_msg = format!("invalid upgrade request: {}", e);
                            caller.data_mut().last_http_result = Some(err_msg.into_bytes());
                            return -1;
                        }
                    };

                let plugin_name = caller.data().plugin_name.clone();
                tracing::debug!(
                    plugin = %plugin_name,
                    url = %ws_request.url,
                    "host_ws_upgrade: storing request for deferred connection"
                );

                // Store the request; the actual connection happens on the main
                // runtime inside the relay task (see relay_websocket).
                caller.data_mut().ws_upgrade_request = Some(ws_request);
                0
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_ws_upgrade: {}", e)))?;

    // host_verify_signature - verify a cryptographic signature using a JWK
    linker
        .func_wrap(
            "barbacane",
            "host_verify_signature",
            |mut caller: Caller<'_, PluginState>, req_ptr: i32, req_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = req_ptr as usize;
                let end = start + req_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Parse the verification request
                let request: crate::crypto::VerifySignatureRequest =
                    match serde_json::from_slice(&data[start..end]) {
                        Ok(r) => r,
                        Err(e) => {
                            tracing::error!(
                                plugin = %caller.data_mut().plugin_name,
                                "failed to parse verify_signature request: {}", e
                            );
                            return -1;
                        }
                    };

                // Perform verification
                match crate::crypto::verify_signature(&request) {
                    Ok(true) => 1,
                    Ok(false) => 0,
                    Err(e) => {
                        tracing::error!(
                            plugin = %caller.data_mut().plugin_name,
                            "signature verification error: {}", e
                        );
                        -1
                    }
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_verify_signature: {}", e))
        })?;

    // host_get_secret - get a secret by reference
    linker
        .func_wrap(
            "barbacane",
            "host_get_secret",
            |mut caller: Caller<'_, PluginState>, ref_ptr: i32, ref_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = ref_ptr as usize;
                let end = start + ref_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Read the secret reference from plugin memory
                let secret_ref = match std::str::from_utf8(&data[start..end]) {
                    Ok(r) => r.to_string(),
                    Err(_) => return -1,
                };

                // Look up in secrets store
                match caller.data().secrets.get(&secret_ref) {
                    Some(value) => {
                        let bytes = value.as_bytes().to_vec();
                        let len = bytes.len() as i32;
                        caller.data_mut().last_secret_result = Some(bytes);
                        len
                    }
                    None => {
                        tracing::warn!(
                            plugin = %caller.data().plugin_name,
                            reference = %secret_ref,
                            "secret not found in store"
                        );
                        -1
                    }
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_get_secret: {}", e)))?;

    // host_secret_read_result - read secret value into plugin memory
    add_read_result_fn(linker, "host_secret_read_result", |state| {
        state.last_secret_result.take()
    })?;

    // host_rate_limit_check - check rate limit for a key
    linker
        .func_wrap(
            "barbacane",
            "host_rate_limit_check",
            |mut caller: Caller<'_, PluginState>,
             key_ptr: i32,
             key_len: i32,
             quota: u32,
             window_secs: u32|
             -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = key_ptr as usize;
                let end = start + key_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Read the partition key from plugin memory
                let key = match std::str::from_utf8(&data[start..end]) {
                    Ok(k) => k.to_string(),
                    Err(_) => return -1,
                };

                // Get the rate limiter
                let rate_limiter = match &caller.data().rate_limiter {
                    Some(rl) => rl.clone(),
                    None => {
                        tracing::error!("rate limiter not available");
                        return -1;
                    }
                };

                // Check the rate limit
                let result = rate_limiter.check(&key, quota, window_secs as u64);

                // Serialize the result
                match serde_json::to_vec(&result) {
                    Ok(json) => {
                        let len = json.len() as i32;
                        caller.data_mut().last_rate_limit_result = Some(json);
                        len
                    }
                    Err(e) => {
                        tracing::error!("failed to serialize rate limit result: {}", e);
                        -1
                    }
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_rate_limit_check: {}", e))
        })?;

    // host_rate_limit_read_result - read rate limit result into plugin memory
    add_read_result_fn(linker, "host_rate_limit_read_result", |state| {
        state.last_rate_limit_result.take()
    })?;

    // host_cache_get - look up a cached response
    linker
        .func_wrap(
            "barbacane",
            "host_cache_get",
            |mut caller: Caller<'_, PluginState>, key_ptr: i32, key_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = key_ptr as usize;
                let end = start + key_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Read the cache key from plugin memory
                let key = match std::str::from_utf8(&data[start..end]) {
                    Ok(k) => k.to_string(),
                    Err(_) => return -1,
                };

                // Get the response cache
                let cache = match &caller.data().response_cache {
                    Some(c) => c.clone(),
                    None => {
                        tracing::error!("response cache not available");
                        return -1;
                    }
                };

                // Check the cache
                let result = cache.get(&key);

                // Serialize the result
                match serde_json::to_vec(&result) {
                    Ok(json) => {
                        let len = json.len() as i32;
                        caller.data_mut().last_cache_result = Some(json);
                        len
                    }
                    Err(e) => {
                        tracing::error!("failed to serialize cache result: {}", e);
                        -1
                    }
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_cache_get: {}", e)))?;

    // host_cache_set - store a response in the cache
    linker
        .func_wrap(
            "barbacane",
            "host_cache_set",
            |mut caller: Caller<'_, PluginState>,
             key_ptr: i32,
             key_len: i32,
             entry_ptr: i32,
             entry_len: i32,
             ttl_secs: u32|
             -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let key_start = key_ptr as usize;
                let key_end = key_start + key_len as usize;
                let entry_start = entry_ptr as usize;
                let entry_end = entry_start + entry_len as usize;
                let data = memory.data(&caller);

                if key_end > data.len() || entry_end > data.len() {
                    return -1;
                }

                // Read the cache key
                let key = match std::str::from_utf8(&data[key_start..key_end]) {
                    Ok(k) => k.to_string(),
                    Err(_) => return -1,
                };

                // Parse the cache entry JSON
                let entry: crate::cache::CacheEntry =
                    match serde_json::from_slice(&data[entry_start..entry_end]) {
                        Ok(e) => e,
                        Err(e) => {
                            tracing::error!("failed to parse cache entry: {}", e);
                            return -1;
                        }
                    };

                // Get the response cache
                let cache = match &caller.data().response_cache {
                    Some(c) => c.clone(),
                    None => {
                        tracing::error!("response cache not available");
                        return -1;
                    }
                };

                // Store in cache
                cache.set(&key, entry, ttl_secs as u64);
                0 // Success
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_cache_set: {}", e)))?;

    // host_cache_read_result - read cache lookup result into plugin memory
    add_read_result_fn(linker, "host_cache_read_result", |state| {
        state.last_cache_result.take()
    })?;

    // === Telemetry Host Functions ===

    // host_metric_counter_inc - increment a plugin counter metric
    linker
        .func_wrap(
            "barbacane",
            "host_metric_counter_inc",
            |mut caller: Caller<'_, PluginState>,
             name_ptr: i32,
             name_len: i32,
             labels_ptr: i32,
             labels_len: i32,
             value: f64| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let data = memory.data(&caller);
                let name_start = name_ptr as usize;
                let name_end = name_start + name_len as usize;
                let labels_start = labels_ptr as usize;
                let labels_end = labels_start + labels_len as usize;

                if name_end > data.len() || labels_end > data.len() {
                    return;
                }

                let name = match std::str::from_utf8(&data[name_start..name_end]) {
                    Ok(n) => n.to_string(),
                    Err(_) => return,
                };

                let labels_json = match std::str::from_utf8(&data[labels_start..labels_end]) {
                    Ok(l) => l.to_string(),
                    Err(_) => return,
                };

                let plugin_name = caller.data().plugin_name.clone();
                if let Some(metrics) = &caller.data().metrics {
                    metrics.plugin_counter_inc(&plugin_name, &name, &labels_json, value as u64);
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_metric_counter_inc: {}", e))
        })?;

    // host_metric_histogram_observe - observe a plugin histogram metric
    linker
        .func_wrap(
            "barbacane",
            "host_metric_histogram_observe",
            |mut caller: Caller<'_, PluginState>,
             name_ptr: i32,
             name_len: i32,
             labels_ptr: i32,
             labels_len: i32,
             value: f64| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let data = memory.data(&caller);
                let name_start = name_ptr as usize;
                let name_end = name_start + name_len as usize;
                let labels_start = labels_ptr as usize;
                let labels_end = labels_start + labels_len as usize;

                if name_end > data.len() || labels_end > data.len() {
                    return;
                }

                let name = match std::str::from_utf8(&data[name_start..name_end]) {
                    Ok(n) => n.to_string(),
                    Err(_) => return,
                };

                let labels_json = match std::str::from_utf8(&data[labels_start..labels_end]) {
                    Ok(l) => l.to_string(),
                    Err(_) => return,
                };

                let plugin_name = caller.data().plugin_name.clone();
                if let Some(metrics) = &caller.data().metrics {
                    metrics.plugin_histogram_observe(&plugin_name, &name, &labels_json, value);
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!(
                "failed to add host_metric_histogram_observe: {}",
                e
            ))
        })?;

    // host_span_start - start a child span (stub - returns span ID)
    // Full implementation requires passing span context through RequestContext
    linker
        .func_wrap(
            "barbacane",
            "host_span_start",
            |mut caller: Caller<'_, PluginState>, name_ptr: i32, name_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let data = memory.data(&caller);
                let start = name_ptr as usize;
                let end = start + name_len as usize;

                if end > data.len() {
                    return -1;
                }

                let span_name = match std::str::from_utf8(&data[start..end]) {
                    Ok(n) => n,
                    Err(_) => return -1,
                };

                // Log the span start for now (full tracing integration in Phase 9)
                let plugin_name = &caller.data().plugin_name;
                tracing::debug!(plugin = %plugin_name, span = %span_name, "plugin span started");

                // Return a placeholder span ID
                1
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_span_start: {}", e)))?;

    // host_span_end - end the current span
    linker
        .func_wrap(
            "barbacane",
            "host_span_end",
            |caller: Caller<'_, PluginState>| {
                let plugin_name = &caller.data().plugin_name;
                tracing::debug!(plugin = %plugin_name, "plugin span ended");
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_span_end: {}", e)))?;

    // host_span_set_attribute - set an attribute on the current span
    linker
        .func_wrap(
            "barbacane",
            "host_span_set_attribute",
            |mut caller: Caller<'_, PluginState>,
             key_ptr: i32,
             key_len: i32,
             val_ptr: i32,
             val_len: i32| {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return,
                };

                let data = memory.data(&caller);
                let key_start = key_ptr as usize;
                let key_end = key_start + key_len as usize;
                let val_start = val_ptr as usize;
                let val_end = val_start + val_len as usize;

                if key_end > data.len() || val_end > data.len() {
                    return;
                }

                let key = match std::str::from_utf8(&data[key_start..key_end]) {
                    Ok(k) => k,
                    Err(_) => return,
                };

                let value = match std::str::from_utf8(&data[val_start..val_end]) {
                    Ok(v) => v,
                    Err(_) => return,
                };

                let plugin_name = &caller.data().plugin_name;
                tracing::debug!(plugin = %plugin_name, %key, %value, "plugin span attribute set");
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_span_set_attribute: {}", e))
        })?;

    // === Broker Host Functions (M10) ===

    // host_kafka_publish - publish a message to Kafka
    linker
        .func_wrap(
            "barbacane",
            "host_kafka_publish",
            |mut caller: Caller<'_, PluginState>, msg_ptr: i32, msg_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = msg_ptr as usize;
                let end = start + msg_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Parse the broker message from plugin memory
                let message: BrokerMessage = match serde_json::from_slice(&data[start..end]) {
                    Ok(m) => m,
                    Err(e) => {
                        tracing::error!("failed to parse broker message: {}", e);
                        return -1;
                    }
                };

                // Extract URL (broker addresses) from the message
                let brokers = match &message.url {
                    Some(u) => u.clone(),
                    None => {
                        tracing::error!("Kafka publish: missing url in broker message");
                        return -1;
                    }
                };

                // Get the Kafka publisher
                let publisher = match caller.data().kafka_publisher.clone() {
                    Some(p) => p,
                    None => {
                        tracing::error!("Kafka publisher not available");
                        return -1;
                    }
                };

                let topic = message.topic.clone();
                let key = message.key.clone();
                let payload = message.payload.clone();
                let headers = message.headers.clone();

                // Use thread::scope to escape the main tokio runtime context,
                // then call publish_blocking which uses the publisher's own runtime.
                let result = std::thread::scope(|s| {
                    let handle = s.spawn(|| {
                        publisher.publish_blocking(&brokers, &topic, key, &payload, headers)
                    });

                    match handle.join() {
                        Ok(result) => Some(result),
                        Err(e) => {
                            tracing::error!("Kafka publish thread panicked: {:?}", e);
                            None
                        }
                    }
                });

                // Serialize the result
                let result_json = match result {
                    Some(Ok(r)) => serde_json::to_vec(&r),
                    Some(Err(e)) => {
                        let error_result =
                            crate::broker::PublishResult::failure(message.topic, e.to_string());
                        serde_json::to_vec(&error_result)
                    }
                    None => {
                        let error_result = crate::broker::PublishResult::failure(
                            message.topic,
                            "Kafka publish failed".to_string(),
                        );
                        serde_json::to_vec(&error_result)
                    }
                };

                match result_json {
                    Ok(json) => {
                        let len = json.len() as i32;
                        caller.data_mut().last_broker_result = Some(json);
                        len
                    }
                    Err(e) => {
                        tracing::error!("failed to serialize broker result: {}", e);
                        -1
                    }
                }
            },
        )
        .map_err(|e| {
            WasmError::Instantiation(format!("failed to add host_kafka_publish: {}", e))
        })?;

    // host_nats_publish - publish a message to NATS
    linker
        .func_wrap(
            "barbacane",
            "host_nats_publish",
            |mut caller: Caller<'_, PluginState>, msg_ptr: i32, msg_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return -1,
                };

                let start = msg_ptr as usize;
                let end = start + msg_len as usize;
                let data = memory.data(&caller);

                if end > data.len() {
                    return -1;
                }

                // Parse the broker message from plugin memory
                let message: BrokerMessage = match serde_json::from_slice(&data[start..end]) {
                    Ok(m) => m,
                    Err(e) => {
                        tracing::error!("failed to parse broker message: {}", e);
                        return -1;
                    }
                };

                // Extract URL from the message
                let url = match &message.url {
                    Some(u) => u.clone(),
                    None => {
                        tracing::error!("NATS publish: missing url in broker message");
                        return -1;
                    }
                };

                // Get the NATS publisher
                let publisher = match caller.data().nats_publisher.clone() {
                    Some(p) => p,
                    None => {
                        tracing::error!("NATS publisher not available");
                        return -1;
                    }
                };

                let subject = message.topic.clone();
                let payload = bytes::Bytes::from(message.payload.clone());
                let headers = message.headers.clone();

                // Use thread::scope to escape the main tokio runtime context,
                // then call publish_blocking which uses the publisher's own runtime.
                let result = std::thread::scope(|s| {
                    let handle =
                        s.spawn(|| publisher.publish_blocking(&url, &subject, payload, headers));

                    match handle.join() {
                        Ok(result) => Some(result),
                        Err(e) => {
                            tracing::error!("NATS publish thread panicked: {:?}", e);
                            None
                        }
                    }
                });

                // Serialize the result
                let result_json = match result {
                    Some(Ok(r)) => serde_json::to_vec(&r),
                    Some(Err(e)) => {
                        let error_result =
                            crate::broker::PublishResult::failure(message.topic, e.to_string());
                        serde_json::to_vec(&error_result)
                    }
                    None => {
                        let error_result = crate::broker::PublishResult::failure(
                            message.topic,
                            "NATS publish failed".to_string(),
                        );
                        serde_json::to_vec(&error_result)
                    }
                };

                match result_json {
                    Ok(json) => {
                        let len = json.len() as i32;
                        caller.data_mut().last_broker_result = Some(json);
                        len
                    }
                    Err(e) => {
                        tracing::error!("failed to serialize broker result: {}", e);
                        -1
                    }
                }
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("failed to add host_nats_publish: {}", e)))?;

    // host_broker_read_result - read broker publish result into plugin memory
    add_read_result_fn(linker, "host_broker_read_result", |state| {
        state.last_broker_result.take()
    })?;

    // ── Minimal WASI stubs ──────────────────────────────────────────────
    // Some plugins (e.g. cel) compile with wasm32-wasip1 and import WASI
    // functions even though Barbacane provides its own host ABI. We add
    // lightweight stubs so the linker can resolve these imports.
    // Full WASI support (wasmtime-wasi) can replace these if needed.

    // random_get — deterministic bytes for HashMap seed initialisation.
    // Acceptable in a sandboxed single-request context (no HashDoS risk).
    linker
        .func_wrap(
            "wasi_snapshot_preview1",
            "random_get",
            |mut caller: Caller<'_, PluginState>, buf_ptr: i32, buf_len: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return 1,
                };
                let start = buf_ptr as usize;
                let end = start + buf_len as usize;
                let data = memory.data_mut(&mut caller);
                if end > data.len() {
                    return 1;
                }
                for (i, byte) in data[start..end].iter_mut().enumerate() {
                    *byte = (i.wrapping_mul(0x9E3779B9) >> 24) as u8;
                }
                0
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    // sched_yield — no-op, always succeeds.
    linker
        .func_wrap("wasi_snapshot_preview1", "sched_yield", || -> i32 { 0 })
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    // clock_time_get — returns current time in nanoseconds.
    linker
        .func_wrap(
            "wasi_snapshot_preview1",
            "clock_time_get",
            |mut caller: Caller<'_, PluginState>,
             _clock_id: i32,
             _precision: i64,
             time_ptr: i32|
             -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return 1,
                };
                let nanos = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_nanos() as u64)
                    .unwrap_or(0);
                let ptr = time_ptr as usize;
                let data = memory.data_mut(&mut caller);
                if ptr + 8 > data.len() {
                    return 1;
                }
                data[ptr..ptr + 8].copy_from_slice(&nanos.to_le_bytes());
                0
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    // fd_write — silently discards output (plugins use host_log instead).
    linker
        .func_wrap(
            "wasi_snapshot_preview1",
            "fd_write",
            |mut caller: Caller<'_, PluginState>,
             _fd: i32,
             iovs_ptr: i32,
             iovs_len: i32,
             nwritten_ptr: i32|
             -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return 1,
                };
                let data = memory.data_mut(&mut caller);
                let mut total: u32 = 0;
                for i in 0..iovs_len as usize {
                    let base = (iovs_ptr as usize) + i * 8;
                    if base + 8 > data.len() {
                        return 1;
                    }
                    let len =
                        u32::from_le_bytes(data[base + 4..base + 8].try_into().unwrap_or([0; 4]));
                    total = total.saturating_add(len);
                }
                let ptr = nwritten_ptr as usize;
                if ptr + 4 > data.len() {
                    return 1;
                }
                data[ptr..ptr + 4].copy_from_slice(&total.to_le_bytes());
                0
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    // environ_get — no environment variables exposed.
    linker
        .func_wrap(
            "wasi_snapshot_preview1",
            "environ_get",
            |_caller: Caller<'_, PluginState>, _environ: i32, _environ_buf: i32| -> i32 { 0 },
        )
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    // environ_sizes_get — reports 0 vars, 0 bytes.
    linker
        .func_wrap(
            "wasi_snapshot_preview1",
            "environ_sizes_get",
            |mut caller: Caller<'_, PluginState>, num_ptr: i32, buf_size_ptr: i32| -> i32 {
                let memory = match caller.get_export("memory").and_then(|e| e.into_memory()) {
                    Some(m) => m,
                    None => return 1,
                };
                let data = memory.data_mut(&mut caller);
                let np = num_ptr as usize;
                let bp = buf_size_ptr as usize;
                if np + 4 > data.len() || bp + 4 > data.len() {
                    return 1;
                }
                data[np..np + 4].copy_from_slice(&0u32.to_le_bytes());
                data[bp..bp + 4].copy_from_slice(&0u32.to_le_bytes());
                0
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    // proc_exit — traps the module (should never be reached).
    linker
        .func_wrap(
            "wasi_snapshot_preview1",
            "proc_exit",
            |_caller: Caller<'_, PluginState>, _code: i32| {
                // Intentional trap — WASM execution stops here
            },
        )
        .map_err(|e| WasmError::Instantiation(format!("wasi stub: {e}")))?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_context_new() {
        let ctx = RequestContext::new("trace-123".into(), "req-456".into());
        assert_eq!(ctx.trace_id, "trace-123");
        assert_eq!(ctx.request_id, "req-456");
        assert!(ctx.values.is_empty());
    }

    #[test]
    fn plugin_state_take_output() {
        let limits = PluginLimits::default();
        let mut state = PluginState::new("test".into(), &limits);
        state.output_buffer = vec![1, 2, 3];

        let output = state.take_output();
        assert_eq!(output, vec![1, 2, 3]);
        assert!(state.output_buffer.is_empty());
    }

    #[test]
    fn plugin_state_uuid_result_initialized() {
        let limits = PluginLimits::default();
        let state = PluginState::new("test".into(), &limits);
        assert!(state.last_uuid_result.is_none());
    }

    #[test]
    fn uuid_v7_format() {
        // Test that UUID v7 generates valid format
        let uuid = uuid::Uuid::now_v7().to_string();
        assert_eq!(uuid.len(), 36); // UUID string format: 8-4-4-4-12
        assert!(uuid.chars().nth(14) == Some('7')); // Version 7 marker
    }

    #[test]
    fn plugin_state_nats_publisher_default() {
        let limits = PluginLimits::default();
        let state = PluginState::new("test".into(), &limits);
        assert!(state.nats_publisher.is_none());
    }

    #[test]
    fn plugin_state_broker_result_default() {
        let limits = PluginLimits::default();
        let state = PluginState::new("test".into(), &limits);
        assert!(state.last_broker_result.is_none());
    }

    #[test]
    fn plugin_state_kafka_publisher_default() {
        let limits = PluginLimits::default();
        let state = PluginState::new("test".into(), &limits);
        assert!(state.kafka_publisher.is_none());
    }

    // ── streaming (ADR-0023) ──────────────────────────────────────────────────

    #[test]
    fn plugin_state_stream_sender_default_is_none() {
        let limits = PluginLimits::default();
        let state = PluginState::new("test".into(), &limits);
        assert!(state.stream_sender.is_none());
    }

    #[test]
    fn plugin_state_set_stream_sender() {
        let limits = PluginLimits::default();
        let mut state = PluginState::new("test".into(), &limits);
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel::<crate::instance::StreamEvent>();
        state.set_stream_sender(Arc::new(tx));
        assert!(state.stream_sender.is_some());
    }

    #[test]
    fn plugin_state_take_last_http_result_default_is_none() {
        let limits = PluginLimits::default();
        let state = PluginState::new("test".into(), &limits);
        assert!(state.last_http_result.is_none());
    }

    #[test]
    fn plugin_state_take_last_http_result_takes_value() {
        let limits = PluginLimits::default();
        let mut state = PluginState::new("test".into(), &limits);
        state.last_http_result = Some(vec![1, 2, 3]);

        let taken = state.last_http_result.take();
        assert_eq!(taken, Some(vec![1, 2, 3]));
        assert!(state.last_http_result.is_none());
    }

    #[test]
    fn stream_event_headers_fields() {
        let event = StreamEvent::Headers {
            status: 200,
            headers: std::collections::BTreeMap::from([(
                "content-type".to_string(),
                "text/event-stream".to_string(),
            )]),
        };
        if let StreamEvent::Headers { status, headers } = event {
            assert_eq!(status, 200);
            assert_eq!(
                headers.get("content-type").map(String::as_str),
                Some("text/event-stream")
            );
        } else {
            panic!("expected Headers variant");
        }
    }

    #[test]
    fn stream_event_chunk_contains_bytes() {
        let data = bytes::Bytes::from_static(b"data: hello\n\n");
        let event = StreamEvent::Chunk(data.clone());
        if let StreamEvent::Chunk(b) = event {
            assert_eq!(b, data);
        } else {
            panic!("expected Chunk variant");
        }
    }

    #[test]
    fn plugin_state_with_all_options_sets_publishers() {
        let limits = PluginLimits::default();
        let nats = Arc::new(crate::nats_client::NatsPublisher::new());
        let kafka = Arc::new(crate::kafka_client::KafkaPublisher::new());
        let state = PluginState::with_all_options(
            "test".into(),
            &limits,
            None,
            crate::secrets::SecretsStore::new(),
            None,
            None,
            Some(nats),
            Some(kafka),
        );
        assert!(state.nats_publisher.is_some());
        assert!(state.kafka_publisher.is_some());
    }
}