ocserve-plugin 0.7.1

opencode plugin host: hook dispatcher with full upstream name table
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
//! ocserve-plugin: opencode plugin compatibility via a Node sidecar (M4b).
//!
//! Gate rationale (PLAN §10, evidence not assumption): the frozen plugins
//! import `bun:sqlite`, `child_process`, `node:fs/crypto/url` and TTY UI
//! modules (import audit of the actual artifacts). A quickjs embed would need
//! a dozen shims with a *synchronous* SQLite bridge — rejected as high-risk;
//! one Node sidecar (v25 present, `node:sqlite` built in) is the low-
//! maintenance host. Isolation: sidecar crash/restart cannot take down the
//! server; protocol = NDJSON on stdio; plugin chatter is forced to stderr by
//! the host so framing cannot corrupt.
#![cfg_attr(not(test), forbid(unsafe_code))]

pub mod normalize;
pub use normalize::{Outcome as NormalizeOutcome, normalize_or_raw_sync};

use anyhow::{Context, Result, anyhow};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::oneshot;

/// Host files (written next to the data dir once; content-addressed by embed).
pub const HOST_FILES: &[(&str, &str)] = &[
    ("host.mjs", include_str!("host/host.mjs")),
    ("v2.mjs", include_str!("host/v2.mjs")),
    (
        "bun-sqlite-loader.mjs",
        include_str!("host/bun-sqlite-loader.mjs"),
    ),
    (
        "shim-bun-sqlite.mjs",
        include_str!("host/shim-bun-sqlite.mjs"),
    ),
    (
        "shim-bun-sqlite.cjs",
        include_str!("host/shim-bun-sqlite.cjs"),
    ),
];

/// Per-RPC timeout (hooks are local JS; anything longer is a runaway plugin).
pub const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Write host files into `dir` (idempotent overwrite — embed is authoritative).
pub fn materialize_host(dir: &Path) -> Result<PathBuf> {
    std::fs::create_dir_all(dir).with_context(|| format!("create host dir {}", dir.display()))?;
    for (name, body) in HOST_FILES {
        let path = dir.join(name);
        std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
    }
    Ok(dir.join("host.mjs"))
}

/// Resolve a plugin spec to an entry file (loader.ts semantics, npm-install
/// stage assumed already done by opencode's cache — we re-use it read-only):
/// - absolute/relative path → direct entry
/// - npm spec (`name`, `@scope/name`, `name@version`) →
///   `~/.cache/opencode/packages/{spec}[@latest]/node_modules/{pkg}/…` entry
///   via package.json exports["."] | main | module
pub fn resolve_entry(spec: &str, home: &Path) -> Result<PathBuf> {
    if spec.starts_with('/') || spec.starts_with("./") || spec.starts_with("../") {
        let p = PathBuf::from(spec);
        if p.exists() {
            return Ok(p);
        }
        anyhow::bail!("plugin file not found: {spec}");
    }
    let cache = home.join(".cache/opencode/packages");
    let pkg_name = strip_version(spec);
    let candidates = [
        cache.join(format!("{spec}@latest")),
        cache.join(spec),
        cache.join(format!("{pkg_name}@latest")),
    ];
    for dir in &candidates {
        if !dir.exists() {
            continue;
        }
        // wrapper package.json → node_modules/<pkg>/package.json
        let direct = dir.join("package.json");
        if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
            return Ok(entry);
        }
        let nested = dir
            .join("node_modules")
            .join(&pkg_name)
            .join("package.json");
        if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
        {
            return Ok(entry);
        }
    }
    anyhow::bail!("plugin target not found in opencode cache: {spec}")
}

fn strip_version(spec: &str) -> String {
    // "@scope/name@latest" → "@scope/name"; "name@1.2.3" → "name"
    let bytes = spec.as_bytes();
    // find the LAST '@' that is NOT at index 0 (scope marker)
    let mut cut = None;
    for (i, b) in bytes.iter().enumerate() {
        if *b == b'@' && i > 0 {
            cut = Some(i);
        }
    }
    match cut {
        Some(i) => spec[..i].to_string(),
        None => spec.to_string(),
    }
}

fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
    let text = std::fs::read_to_string(pkg_json).ok()?;
    let v: Value = serde_json::from_str(&text).ok()?;
    let mut rel: Option<&str> = None;
    if let Some(exp) = v.get("exports")
        && let Some(dot) = exp.get(".")
    {
        rel = match dot {
            Value::String(s) => Some(s.as_str()),
            Value::Object(_) => dot
                .get("import")
                .and_then(|x| x.as_str())
                .or_else(|| dot.get("default").and_then(|x| x.as_str())),
            _ => None,
        };
    }
    rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
    rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
    let rel = rel?;
    let entry = base.join(rel);
    // G6: the package's own `exports`/`main`/`module` may point outside the
    // package (e.g. `../../other`). Lexically normalize and require the entry
    // to stay inside `base`; a plugin entry is loaded only from its package.
    let lex = lexically_normalize(&entry);
    if !lex.starts_with(base)
        && !std::fs::canonicalize(base)
            .ok()
            .is_some_and(|cb| lex.starts_with(&cb))
    {
        tracing::warn!("plugin entry {rel} escapes its package dir — refused");
        return None;
    }
    lex.exists().then_some(lex)
}

fn lexically_normalize(p: &Path) -> PathBuf {
    use std::path::Component;
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    out
}

struct Pending {
    tx: oneshot::Sender<Result<Value, String>>,
}

/// Removes its id from `pending` on every exit path, including a cancelled
/// future. Without this, abort/delete cancel the awaiting task, the entry
/// leaks, and `in_flight()` never returns 0 — the L1 recycle gate wedges.
struct PendingGuard {
    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
    id: i64,
}

impl PendingGuard {
    fn new(pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>, id: i64) -> Self {
        Self { pending, id }
    }
}

impl Drop for PendingGuard {
    fn drop(&mut self) {
        self.pending.lock().remove(&self.id);
    }
}

/// Everything a request needs, shareable WITHOUT the owning `Sidecar` lock.
///
/// Why this exists (2026-10-22): `hook_mutate` held `Arc<Mutex<Sidecar>>` for
/// the whole hook await, so two sessions' hooks fully serialized — the
/// reference interleaves them at `await` points. Writes are serialized by the
/// stdin mutex and responses correlate by id, so nothing needs exclusive
/// access to the process while a hook runs.
///
/// Liveness (2026-10-23 review): a handle is tied to ONE child generation.
/// The reader marks `alive=false` when it stops, and `poisoned=true` when the
/// protocol is no longer trustworthy; both make requests fail fast, and the
/// owner's `ensure_alive` replaces the generation. A stale handle can never
/// deliver a response to the wrong waiter.
pub struct Inner {
    stdin: tokio::sync::Mutex<ChildStdin>,
    /// SHARED with the reader task (it resolves responses by id).
    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
    next_id: std::sync::atomic::AtomicI64,
    /// load results (spec → {hooks,…}) for introspection AND round-trip skips.
    statuses: parking_lot::Mutex<HashMap<String, Value>>,
    /// reader still running; false = requests must not be attempted.
    alive: Arc<std::sync::atomic::AtomicBool>,
    /// the child must be replaced before the next request (framing lost).
    poisoned: Arc<std::sync::atomic::AtomicBool>,
    /// last successfully fetched plugin-tool list. A busy host must not make
    /// plugin tools vanish from the provider schema for a round (M6).
    last_tools: parking_lot::Mutex<Option<Vec<Value>>>,
}

/// Cheap clone handle: hook dispatch drops the owner lock and awaits this.
#[derive(Clone)]
pub struct Handle(Arc<Inner>);

impl Handle {
    /// Is this generation still able to answer? Used by callers to decide
    /// between a fast failure and a recovery attempt.
    pub fn is_alive(&self) -> bool {
        self.0.alive.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Does any loaded plugin register `hook`? Lets the hot path skip the
    /// sidecar round-trip entirely when nobody listens (most installs).
    pub fn registers(&self, hook: &str) -> bool {
        self.0.statuses.lock().values().any(|v| {
            v.get("hooks")
                .and_then(|h| h.as_array())
                .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(hook)))
        })
    }

    pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
        self.request_with_timeout(method, params, Some(RPC_TIMEOUT))
            .await
    }

    pub async fn request_with_timeout(
        &self,
        method: &str,
        params: Value,
        timeout: Option<std::time::Duration>,
    ) -> Result<Value> {
        if !self.is_alive() {
            anyhow::bail!("plugin host is down ({method}); a respawn is required");
        }
        let id = self
            .0
            .next_id
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let (tx, rx) = oneshot::channel();
        self.0.pending.lock().insert(id, Pending { tx });
        let _guard = PendingGuard::new(Arc::clone(&self.0.pending), id);
        let msg = json!({"id": id, "method": method, "params": params});
        let mut line = msg.to_string();
        line.push('\n');
        // The BUDGET COVERS THE WRITE (review C2). Previously only the response
        // wait was timed, so a host that stopped draining blocked every caller
        // on the stdin mutex with no timer. A timeout now also poisons the
        // generation: a partially written frame makes the protocol untrustworthy.
        let exchange = async {
            {
                let mut stdin = self.0.stdin.lock().await;
                stdin.write_all(line.as_bytes()).await?;
                stdin.flush().await?;
            }
            match rx.await {
                Ok(res) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
                Err(_) => Err(anyhow!("plugin host dropped response for {method}")),
            }
        };
        match timeout {
            None => exchange
                .await
                .map_err(|e| e.context("plugin host stdin write")),
            Some(d) => match tokio::time::timeout(d, exchange).await {
                Ok(res) => res,
                Err(_) => {
                    self.0
                        .poisoned
                        .store(true, std::sync::atomic::Ordering::Release);
                    self.0
                        .alive
                        .store(false, std::sync::atomic::Ordering::Release);
                    ocserve_metrics::labeled_counter(
                        "ocserve_plugin_hook_timeout_total",
                        &format!("hook=\"{method}\""),
                        1,
                    );
                    Err(anyhow!(
                        "plugin host {method} timed out after {}ms (runaway hook?)",
                        d.as_millis()
                    ))
                }
            },
        }
    }
}

impl Handle {
    pub async fn trigger_bounded(
        &self,
        name: &str,
        input: Value,
        mut output: Value,
        budget: Option<std::time::Duration>,
    ) -> Result<Value> {
        let res = self
            .request_with_timeout(
                "trigger",
                json!({"name": name, "input": input, "output": output}),
                budget,
            )
            .await?;
        if res.is_object() {
            output = res;
        }
        Ok(output)
    }

    pub async fn trigger_v2_bounded(
        &self,
        domain: &str,
        name: &str,
        input: Value,
        budget: Option<std::time::Duration>,
    ) -> Result<Value> {
        self.request_with_timeout(
            "trigger_v2",
            json!({"domain": domain, "name": name, "input": input}),
            budget,
        )
        .await
    }

    pub async fn emit_event_bounded(
        &self,
        event: Value,
        budget: Option<std::time::Duration>,
    ) -> Result<Value> {
        self.request_with_timeout("event", json!({"event": event}), budget)
            .await
    }
}

/// Per-hook budget. Upstream has NO hook timeout (`Effect.promise(...)` awaits
/// forever); any bound is our safety divergence, recorded as D-HOOK-TIMEOUT.
/// Defaults come from measured maxima on a real install (27 prompts):
/// `v2.session.context` 15.3 s, `tool.execute.after` 30.0 s,
/// `system.transform` 5.4 s. `OCSERVE_HOOK_TIMEOUT_MS=0` restores parity
/// (unbounded) for an operator who needs it.
pub fn hook_budget(hook: &str) -> Option<std::time::Duration> {
    match std::env::var("OCSERVE_HOOK_TIMEOUT_MS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
    {
        Some(0) => None,
        Some(ms) => Some(std::time::Duration::from_millis(ms)),
        None => Some(std::time::Duration::from_secs(
            if hook.contains("tool.execute") {
                180
            } else if hook.contains("transform")
                || hook.contains("context")
                // `experimental.session.compacting` does NOT contain
                // "compaction" (review M1: a substring miss gave it 30 s).
                || hook.contains("compact")
            {
                60
            } else {
                30
            },
        )),
    }
}

impl Handle {
    /// v2 RPC dispatch (see `Sidecar::rpc_call`, which delegates here).
    pub async fn rpc_call(&self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
        self.request(
            "rpc_call",
            json!({"rpcID": rpc_id, "method": method, "input": input}),
        )
        .await
    }

    /// v2 plugin inventory (real — id/dialect per loaded v2 plugin + the
    /// registered RPC ids). Powers `/api/plugin` without fabricating a list.
    pub async fn v2_inventory(&self) -> Result<Value> {
        self.request("v2_inventory", json!({})).await
    }

    /// Pulled v2 command/skill transform (see `Sidecar::transform_commands`).
    pub async fn transform_commands(
        &self,
        commands: Vec<Value>,
    ) -> Result<(Vec<Value>, Vec<Value>)> {
        let r = self
            .request("v2_transform_commands", json!({ "commands": commands }))
            .await?;
        let out = r["commands"]
            .as_array()
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .collect();
        let failures = r["failures"].as_array().cloned().unwrap_or_default();
        Ok((out, failures))
    }
}

impl Handle {
    /// Plugin-declared tools (v1 `hooks.tool`), with JSON Schema generated in
    /// the plugin's own runtime. Empty when no plugin registers one, so the
    /// provider `tools` array is byte-identical for everyone else.
    ///
    /// A failed fetch returns the LAST KNOWN list rather than an empty one
    /// (review M6): dropping tools mid-session made a later call to one fall
    /// through to "unknown tool", a worse failure than a stale schema.
    pub async fn tools(&self) -> Result<Vec<Value>> {
        if !self.registers("tool") {
            return Ok(Vec::new());
        }
        match self.request("tools", json!({})).await {
            Ok(res) => {
                let list = res.as_array().cloned().unwrap_or_default();
                *self.0.last_tools.lock() = Some(list.clone());
                Ok(list)
            }
            Err(e) => {
                if let Some(cached) = self.0.last_tools.lock().clone() {
                    tracing::warn!("plugin tools: {e:#} — serving the last known list");
                    return Ok(cached);
                }
                Err(e)
            }
        }
    }

    /// Execute one plugin tool. `ctx` carries {sessionID, messageID, agent,
    /// directory}. The permission gate ran already for the call as a whole.
    pub async fn execute_tool(&self, name: &str, input: Value, ctx: Value) -> Result<Value> {
        self.request_with_timeout(
            "tool_execute",
            json!({"name": name, "input": input, "ctx": ctx}),
            Some(std::time::Duration::from_secs(300)),
        )
        .await
    }
}

/// Sidecar owner: one Node process, NDJSON request/response, reader task.
pub struct Sidecar {
    inner: Arc<Inner>,
    child: Child,
    /// server/directory context for loads (kept for future reloads)
    server: (String, String),
    /// spawn identity for respawn-after-death
    args: SpawnArgs,
    /// successful loads (spec, entry, input, options) — replayed on respawn
    /// (entries stored RAW; load_raw re-normalizes on replay — D1-PLAN).
    /// `options` is the v1 `[spec, options]` tuple's second element (Null when
    /// the plain-string form was used) — passed to the server factory.
    loads: Vec<(String, PathBuf, Value, Value)>,
    /// normalization output root (`data/normalized`); None = skip (tests,
    /// any sidecar without it — existing behavior untouched, D1-PLAN)
    normalize_root: Option<PathBuf>,
    /// spawn time for the L1 recycle min-uptime guard (SRE §5) — fresh on
    /// every (re)spawn, so a recycled sidecar can't be recycled again until
    /// the guard window passes.
    started_at: std::time::Instant,
    /// L1 recycle marker: set when WE killed the child on purpose; the next
    /// ensure_alive must log that as INFO (planned), not ERROR (crash) —
    /// an intentional action must never read as a failure in the logs.
    recycled: bool,
}

/// Plugin-host runtime: Bun preferred (upstream runs plugins under Bun; real
/// `bun:sqlite`, TS plugins load, lower RSS floor), Node fallback.
/// `OCSERVE_PLUGIN_RUNTIME=node|bun` forces one (lab A/B control).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginRuntime {
    Bun,
    Node,
}

impl PluginRuntime {
    pub fn program(self) -> &'static str {
        match self {
            PluginRuntime::Bun => "bun",
            PluginRuntime::Node => "node",
        }
    }
}

/// Resolve an executable on PATH plus `~/.bun/bin` (the common user-local
/// bun install location — systemd units do not see shell PATH extras).
pub(crate) fn which(prog: &str) -> Option<PathBuf> {
    // Windows resolves executables by suffix; `Path::join("bun")` never finds
    // `bun.exe` (PLATFORM.md §1.2). The suffix lives in one place — ocserve-core
    // — so the plugin host, the MCP client and the tools cannot drift.
    let name = ocserve_store::platform::exe(prog);
    if let Ok(path) = std::env::var("PATH") {
        for dir in std::env::split_paths(&path) {
            let cand = dir.join(&name);
            if ocserve_store::platform::is_executable_file(&cand) {
                return Some(cand);
            }
        }
    }
    for key in ["OCSERVE_HOME", "HOME", "USERPROFILE"] {
        let Some(home) = std::env::var_os(key).filter(|v| !v.is_empty()) else {
            continue;
        };
        let cand = Path::new(&home).join(".bun/bin").join(&name);
        if ocserve_store::platform::is_executable_file(&cand) {
            return Some(cand);
        }
    }
    None
}

pub fn plugin_runtime() -> PluginRuntime {
    match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
        Ok("node") => return PluginRuntime::Node,
        Ok("bun") => return PluginRuntime::Bun,
        _ => {}
    }
    if which("bun").is_some() {
        PluginRuntime::Bun
    } else {
        PluginRuntime::Node
    }
}

#[derive(Clone)]
struct SpawnArgs {
    host_path: PathBuf,
    server_url: String,
    directory: String,
}

impl Sidecar {
    pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
        // A3 (OOM-resilience): same wrapper as ocserve-mcp — the plugin host
        // dies first on memcg pressure (ensure_alive respawns it) instead
        // of the main service.
        let runtime = crate::plugin_runtime();
        // absolute path (systemd PATH may lack ~/.bun/bin); fall back to the
        // bare name so a PATH-only environment still resolves
        let program = which(runtime.program())
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| runtime.program().to_string());
        // Containment (SRE §5.2): the child moves itself into kids/plugin and
        // raises its oom_score_adj before exec, so a memcg kill takes the
        // sidecar (ensure_alive respawns it) instead of the server.
        let shape = ocserve_store::cgroup::contained(&program, "plugin");
        let mut cmd = Command::new(&shape.program);
        cmd.args(&shape.prefix);
        // `ctx.app.version` must match the running server, not a literal in the
        // shim (it said 0.3.1 through 0.6.x). Env keeps the host script
        // version-agnostic.
        cmd.env("OCSERVE_VERSION", env!("CARGO_PKG_VERSION"));
        match &shape.cgroup {
            Some(p) => {
                cmd.env(ocserve_store::cgroup::ENV, p);
            }
            None => {
                cmd.env_remove(ocserve_store::cgroup::ENV);
            }
        }
        match runtime {
            // Bun (upstream's own plugin runtime): real bun:sqlite + TS
            // plugins load; `--smol` trades GC frequency for a lower RSS
            // floor. No V8 --max-old-space knobs exist here.
            PluginRuntime::Bun => {
                cmd.arg("--smol");
            }
            // Node (fallback when bun is absent): V8 heap cap (env-tunable).
            // Default raised64→128 after the LIVE battery (2026-10-03): with
            // the real plugin set the sidecar OOM-killed at64 (observed boot
            // death → hooks broken-piped until restart). Measured
            // 64/128/192/256: RSS flat ~145-148MB either way (native
            // dominates; heap cap only binds when heap actually grows).
            PluginRuntime::Node => {
                cmd.arg(format!(
                    "--max-old-space-size={}",
                    std::env::var("OCSERVE_PLUGIN_HEAP_MB")
                        .ok()
                        .and_then(|v| v.parse().ok())
                        .unwrap_or(128)
                ));
                cmd.arg("--max-semi-space-size=2");
            }
        }
        cmd.arg(host_path)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::inherit())
            .kill_on_drop(true);
        let mut child = cmd
            .spawn()
            .with_context(|| format!("spawn {} plugin host", runtime.program()))?;
        let stdin = child.stdin.take().context("host stdin")?;
        let stdout = child.stdout.take().context("host stdout")?;
        let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
        let pending_task = Arc::clone(&pending);
        let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let alive_task = Arc::clone(&alive);
        let poisoned = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let poisoned_task = Arc::clone(&poisoned);
        tokio::spawn(async move {
            // Bounded line reads: a plugin that prints a giant line (no newline)
            // would otherwise grow `line` unbounded (host.mjs stdout is reserved
            // for RPC, but a runaway plugin can still emit garbage). Cap at the
            // RPC line budget; a longer line is discarded.
            const MAX_HOST_LINE: usize = 8 * 1024 * 1024;
            let mut reader = BufReader::new(stdout);
            let mut line = String::new();
            loop {
                line.clear();
                use tokio::io::AsyncBufReadExt as _;
                let n = {
                    let mut limited =
                        tokio::io::AsyncReadExt::take(&mut reader, MAX_HOST_LINE as u64 + 1);
                    limited.read_line(&mut line).await
                };
                match n {
                    Ok(0) | Err(_) => break,
                    // oversized: the rest of the line is unreadable framing —
                    // stop; in-flight RPCs fail on timeout (never hang the pump).
                    Ok(_) if line.len() > MAX_HOST_LINE => {
                        // Framing is lost. Mark the generation dead AND poisoned
                        // so the owner replaces the child instead of leaving a
                        // live-but-deaf host that times out every request
                        // (review C1/M-6).
                        tracing::warn!("plugin host: oversized line — child marked for respawn");
                        poisoned_task.store(true, std::sync::atomic::Ordering::Release);
                        break;
                    }
                    Ok(_) => {}
                }
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }
                match serde_json::from_str::<Value>(trimmed) {
                    Ok(v) => {
                        if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
                            let result = match v.get("error") {
                                Some(e) if !e.is_null() => {
                                    Err(e["message"].as_str().unwrap_or("host error").to_string())
                                }
                                _ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
                            };
                            if let Some(p) = pending_task.lock().remove(&id) {
                                let _ = p.tx.send(result);
                            }
                        } else if v.get("event").and_then(|e| e.as_str()) == Some("plugin_error") {
                            // Per-plugin internal failure (the class that hid a
                            // configured plugin for weeks: the plugin caught its
                            // own TypeError and returned the input unchanged, so
                            // Rust saw Ok). Counted by name so silence is visible.
                            ocserve_metrics::labeled_counter(
                                "ocserve_plugin_internal_error_total",
                                &format!(
                                    "plugin=\"{}\",hook=\"{}\"",
                                    v["plugin"].as_str().unwrap_or("?"),
                                    v["hook"].as_str().unwrap_or("?")
                                ),
                                1,
                            );
                            tracing::warn!(
                                "plugin internal error: {} {}: {}",
                                v["plugin"].as_str().unwrap_or("?"),
                                v["hook"].as_str().unwrap_or("?"),
                                v["error"].as_str().unwrap_or("?")
                            );
                        }
                        // no id → informational; host routes plugin chatter to stderr
                    }
                    Err(_) => {
                        let head: String = trimmed.chars().take(120).collect();
                        tracing::warn!("plugin host: unparsable line: {head}");
                    }
                }
            }
            // host death (or reader death): fail everything in flight (fail
            // fast, AGENTS §2.4) and tell every handle this generation is gone.
            alive_task.store(false, std::sync::atomic::Ordering::Release);
            for (_, p) in pending_task.lock().drain() {
                let _ = p.tx.send(Err("plugin host exited".into()));
            }
            ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 0);
        });
        ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 1);
        Ok(Self {
            inner: Arc::new(Inner {
                stdin: tokio::sync::Mutex::new(stdin),
                pending,
                next_id: std::sync::atomic::AtomicI64::new(1),
                statuses: parking_lot::Mutex::new(HashMap::new()),
                alive,
                poisoned,
                last_tools: parking_lot::Mutex::new(None),
            }),
            child,
            server: (server_url.to_string(), directory.to_string()),
            args: SpawnArgs {
                host_path: host_path.to_path_buf(),
                server_url: server_url.to_string(),
                directory: directory.to_string(),
            },
            loads: Vec::new(),
            normalize_root: None,
            started_at: std::time::Instant::now(),
            recycled: false,
        })
    }

    /// RPCs currently in flight (the L1 recycle idle gate — a hook must
    /// never be interrupted mid-call).
    pub fn in_flight(&self) -> usize {
        self.inner.pending.lock().len()
    }

    /// Seconds since this sidecar instance was spawned (respawns reset it).
    pub fn uptime(&self) -> std::time::Duration {
        self.started_at.elapsed()
    }

    /// L1 graceful recycle (SRE §5): kill the sidecar child while idle.
    /// State is disk-backed (context.db / pins) and `loads` is kept, so the
    /// next `ensure_alive` respawns + replays hooks (warm-hash normalize is
    /// a no-op). SIGKILL is deliberate: the host has no shutdown protocol
    /// and nothing in it needs flushing. Returns false if already dead.
    pub fn recycle_child(&mut self) -> bool {
        if self.child.try_wait().ok().flatten().is_some() {
            return false;
        }
        let _ = self.child.start_kill();
        // Do NOT clear `statuses`: the loads are still known and will be
        // replayed on respawn. Clearing them made `registers()` false, so every
        // hook short-circuited to "no plugin" forever — the 2026-10-23 review
        // found a recycle silently disabled every plugin (the Magic Context
        // class again). The generation flag says "needs respawn"; the hook
        // path now acts on it.
        self.inner
            .alive
            .store(false, std::sync::atomic::Ordering::Release);
        self.recycled = true;
        true
    }

    /// Enable normalization for this sidecar (set once at boot; carried to
    /// respawns by `ensure_alive`). None/never-set = raw loads (today's
    /// behavior — all existing tests stay on this path).
    pub fn set_normalize_root(&mut self, root: PathBuf) {
        self.normalize_root = Some(root);
    }

    /// Respawn after unexpected death (V8 OOM / crash) and replay every
    /// previously loaded plugin. Without this a dead sidecar leaves ALL
    /// hooks broken-piped until service restart (live battery finding
    /// 2026-10-03: boot-time heap OOM, fail-open hid it in the prompt path).
    pub async fn ensure_alive(&mut self) -> Result<()> {
        // The reader can die while the child is alive (oversized line, lost
        // framing). A live-but-deaf host times out every request, so treat
        // poison as death and replace the whole generation.
        if self
            .inner
            .poisoned
            .load(std::sync::atomic::Ordering::Acquire)
        {
            let _ = self.child.start_kill();
            self.inner
                .alive
                .store(false, std::sync::atomic::Ordering::Release);
        } else if self.inner.alive.load(std::sync::atomic::Ordering::Acquire)
            && let Ok(None) = self.child.try_wait()
        {
            return Ok(());
        }
        ocserve_metrics::labeled_counter(
            "ocserve_plugin_sidecar_respawn_total",
            if self.recycled {
                "reason=\"recycle\""
            } else {
                "reason=\"exit\""
            },
            1,
        );
        let status = self.child.try_wait().ok().flatten();
        if std::mem::take(&mut self.recycled) {
            tracing::info!(
                "plugin sidecar recycled (L1, was {status:?}) — respawning + replaying hooks"
            );
        } else if let Some(status) = status {
            tracing::error!("plugin sidecar exited ({status}) — respawning");
        } else {
            tracing::warn!("plugin sidecar unresponsive — replacing the host");
        }
        let args = self.args.clone();
        let loads = std::mem::take(&mut self.loads);
        // Spawn failure must NOT lose `loads`: `self` is only replaced on
        // success, so restore the taken entries and surface the error. Without
        // this the plugin set is silently empty after a failed respawn — hooks
        // never replay and `in_flight()` stays zero (statuses stale).
        let mut fresh =
            match Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await {
                Ok(f) => f,
                Err(e) => {
                    self.loads = loads;
                    tracing::error!("plugin sidecar respawn failed: {e:#} — plugin set preserved");
                    return Err(e);
                }
            };
        // D1-PLAN: replay must normalize too (warm no-op; rebuilds if outputs
        // were wiped mid-run — A1 stores raw, rebuilds here AND at next boot).
        fresh.normalize_root = self.normalize_root.clone();
        for (spec, entry, input, options) in &loads {
            if let Err(e) = fresh.load_raw(spec, entry, input, options).await {
                tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
            }
        }
        *self = fresh;
        Ok(())
    }

    /// Child pid (test/diag: force-kill to prove respawn).
    pub fn child_pid(&self) -> u32 {
        self.child.id().unwrap_or(0)
    }

    pub fn handle(&self) -> Handle {
        Handle(Arc::clone(&self.inner))
    }

    pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
        self.ensure_alive().await?;
        self.handle().request(method, params).await
    }

    /// Request with an explicit budget; `None` keeps the historical RPC bound.
    pub async fn request_bounded(
        &mut self,
        method: &str,
        params: Value,
        timeout: Option<std::time::Duration>,
    ) -> Result<Value> {
        self.ensure_alive().await?;
        self.handle()
            .request_with_timeout(method, params, timeout)
            .await
    }

    /// Load one plugin (v1 server-factory extraction happens host-side).
    /// `options` is the v1 `[spec, options]` tuple's second element (pass
    /// `Value::Null` for the plain-string form) — delivered to the factory.
    pub async fn load(
        &mut self,
        spec: &str,
        entry: &Path,
        input: &Value,
        options: &Value,
    ) -> Result<Vec<String>> {
        self.ensure_alive().await?;
        self.load_raw(spec, entry, input, options).await
    }

    /// Unguarded load (respawn replay only — fresh child is alive).
    async fn load_raw(
        &mut self,
        spec: &str,
        entry: &Path,
        input: &Value,
        options: &Value,
    ) -> Result<Vec<String>> {
        // D1: normalize for the RPC (CPU on spawn_blocking — A2 class); the
        // RAW entry is what gets recorded for respawn replay (A1).
        let root = self.normalize_root.clone();
        let raw = entry.to_path_buf();
        let raw_for_spawn = raw.clone();
        let (load_path, outcome) = tokio::task::spawn_blocking(move || {
            crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw_for_spawn)
        })
        .await
        .map_err(|e| anyhow!("normalize task: {e}"))?;
        ocserve_metrics::labeled_counter(
            "ocserve_plugin_normalize_total",
            &format!("result=\"{}\"", outcome.label()),
            1,
        );
        match &outcome {
            crate::normalize::Outcome::Built {
                path,
                ms,
                beside,
                rss_before_kb,
                rss_after_kb,
            } => tracing::info!(
                "plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
                path.display(),
                if *beside { "beside-entry" } else { "data-dir" }
            ),
            crate::normalize::Outcome::Fallback { err, .. } => {
                tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
            }
            _ => {}
        }
        // server/directory context defaults from spawn (input may omit them)
        let mut input = input.clone();
        if input
            .get("serverUrl")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .is_empty()
        {
            input["serverUrl"] = json!(self.server.0);
        }
        if input
            .get("directory")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .is_empty()
        {
            input["directory"] = json!(self.server.1);
        }
        let params = json!({
            "spec": spec,
            "entry": load_path.to_string_lossy(),
            // Where the plugin ACTUALLY lives. Normalized bundles are emitted
            // outside the plugin's tree, so `createRequire(entry)` cannot
            // resolve its `zod` from there — and a tool schema that cannot be
            // converted is an invalid JSON Schema the provider 400s.
            "origin": raw.to_string_lossy(),
            "input": input,
            "options": options,
        });
        let res = self.handle().request("load", params).await?;
        let hooks: Vec<String> = res["hooks"]
            .as_array()
            .map(|a| {
                a.iter()
                    .filter_map(|h| h.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        self.inner.statuses.lock().insert(
            spec.to_string(),
            json!({"ok": true, "hooks": hooks, "id": res["id"]}),
        );
        self.loads.push((
            spec.to_string(),
            entry.to_path_buf(),
            input,
            options.clone(),
        ));
        Ok(hooks)
    }

    /// v1 trigger semantics: sequential hooks mutate `output` in place.
    pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
        let params = json!({"name": name, "input": input, "output": output});
        let res = self.request("trigger", params).await?;
        if res.is_object() {
            output = res;
        }
        Ok(output)
    }

    /// v1 event delivery (plugin/index.ts:255-259): per-plugin
    /// `hooks["event"]({event})`. Returns host delivery count.
    pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
        self.request("event", json!({"event": event})).await
    }

    /// v2 domain-hook dispatch (Phase 3): v2 hooks mutate the event object in
    /// place (like v1's output), so this returns `{output, matched}`. `matched`
    /// = 0 means no v2 plugin installed this hook (caller skips mutation).
    pub async fn trigger_v2(&mut self, domain: &str, name: &str, input: Value) -> Result<Value> {
        self.request(
            "trigger_v2",
            json!({"domain": domain, "name": name, "input": input}),
        )
        .await
    }

    /// v2 RPC dispatch (Phase 3): `{rpcID, method, input}` →
    /// `{output}` (success) or `{error:{type,message}}` (unavailable /
    /// method_not_found / handler_error).
    pub async fn rpc_call(&mut self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
        self.ensure_alive().await?;
        self.handle().rpc_call(rpc_id, method, input).await
    }

    /// v2 plugin inventory (real — id/dialect per loaded v2 plugin + the
    /// registered RPC ids). Powers `/api/plugin` without fabricating a list.
    pub async fn v2_inventory(&mut self) -> Result<Value> {
        self.ensure_alive().await?;
        self.handle().v2_inventory().await
    }

    /// Run every registered v2 `command.transform` / `skill.transform` over
    /// `commands` and return the edited list.
    ///
    /// PULLED by the caller on config reload (never pushed by the plugin), so
    /// a payload can only ever serve a list this call actually returned — the
    /// property that kills the push-race where a stale list is served after a
    /// reconcile that never asked. Upstream semantics mirrored from
    /// `State.create` (core/state.ts:172-194): transforms start from the
    /// pristine list each call and a throwing transform is reported, not fatal.
    ///
    /// Returns `(commands, failures)`; a sidecar error propagates so the
    /// caller can fall back to the untransformed list rather than serve an
    /// empty command surface.
    pub async fn transform_commands(
        &mut self,
        commands: Vec<Value>,
    ) -> Result<(Vec<Value>, Vec<Value>)> {
        self.ensure_alive().await?;
        self.handle().transform_commands(commands).await
    }

    pub async fn config(&mut self, cfg: Value) -> Result<Value> {
        self.request("config", json!({"config": cfg})).await
    }

    pub fn statuses(&self) -> Value {
        let mut out = serde_json::Map::new();
        for (spec, v) in self.inner.statuses.lock().iter() {
            out.insert(spec.clone(), v.clone());
        }
        Value::Object(out)
    }

    pub async fn shutdown(&mut self) {
        let _ = self.request("dispose", json!({})).await;
        let _ = self.child.start_kill();
    }
}

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

    #[test]
    fn strip_version_cases() {
        assert_eq!(strip_version("context-mode"), "context-mode");
        assert_eq!(strip_version("context-mode@latest"), "context-mode");
        assert_eq!(
            strip_version("@cortexkit/opencode-magic-context@latest"),
            "@cortexkit/opencode-magic-context"
        );
        assert_eq!(
            strip_version("@iam-brain/opencode-codex-auth@latest"),
            "@iam-brain/opencode-codex-auth"
        );
    }

    #[test]
    fn entry_from_package_shapes() {
        let dir = tempfile::tempdir().unwrap();
        // exports["."] string
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"exports": {".": "./dist/index.js"}}"#,
        )
        .unwrap();
        std::fs::create_dir(dir.path().join("dist")).unwrap();
        std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
        let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
            .expect("exports dot");
        assert!(e.ends_with("dist/index.js"));
        // main fallback
        std::fs::write(
            dir.path().join("package.json"),
            r#"{"main": "./lib/main.js"}"#,
        )
        .unwrap();
        std::fs::create_dir(dir.path().join("lib")).unwrap();
        std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
        let e =
            entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
        assert!(e.ends_with("lib/main.js"));
    }

    #[tokio::test]
    async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        // synthetic v1 plugin: PluginModule.server factory + mutating hook
        std::fs::write(
            dir.path().join("plug.mjs"),
            r#"
export const PluginModule = {
  id: "synthetic",
  server: async () => ({
    "tool.execute.after": async (input, output) => { output.seen = input.tool; },
    "chat.message": async (input, output) => { output.touched = true; },
    "event": async (payload) => {
      if (!payload.event || !payload.event.type) throw new Error("bad event shape");
      if (payload.event.type === "boom.type") throw new Error("event boom");
    },
  }),
};
export default PluginModule.server;
"#,
        )
        .unwrap();
        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
            .await
            .expect("spawn node");
        let ping = sc.request("ping", json!({})).await.expect("ping");
        assert_eq!(ping, "pong");

        let input =
            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
        let hooks = sc
            .load(
                "synthetic",
                &dir.path().join("plug.mjs"),
                &input,
                &Value::Null,
            )
            .await
            .expect("load");
        assert_eq!(
            hooks,
            vec![
                "tool.execute.after".to_string(),
                "chat.message".to_string(),
                "event".to_string()
            ],
            "hook names registered in declaration order"
        );

        // trigger mutates output in place (v1 semantics)
        let out = sc
            .trigger(
                "tool.execute.after",
                json!({"tool": "write", "args": {"filePath": "/x"}}),
                json!({}),
            )
            .await
            .expect("trigger");
        assert_eq!(
            out["seen"], "write",
            "hook observed input and mutated output"
        );
        // unregistered hook name → output unchanged
        let out2 = sc
            .trigger("permission.ask", json!({}), json!({"keep": 1}))
            .await
            .expect("trigger2");
        assert_eq!(out2["keep"], 1);

        // v1 event delivery (plugin/index.ts:255-259): hooks["event"]
        // receives {event:{id,type,properties}}; shape-asserting fixture
        // only succeeds if the wrapper is exact (delivered counts non-
        // throwing hooks), and a throwing event hook fails open.
        let ev = sc
            .emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
            .await
            .expect("emit_event");
        assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
        let ev2 = sc
            .emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
            .await
            .expect("emit_event fail-open");
        assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");

        let st = sc.statuses();
        assert_eq!(st["synthetic"]["ok"], true);
        assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");

        sc.shutdown().await;
        Ok(())
    }

    #[tokio::test]
    async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("plug.mjs"),
            r#"
export const PluginModule = {
  id: "reaper",
  server: async () => ({
    "chat.message": async (_i, output) => { output.alive = true; },
  }),
};
export default PluginModule.server;
"#,
        )
        .unwrap();
        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        sc.load(
            "reaper",
            &dir.path().join("plug.mjs"),
            &json!({}),
            &Value::Null,
        )
        .await
        .expect("load");
        let pid = sc.child_pid();
        // force-kill the child (the live OOM class: sidecar dies, hooks
        // silently broken-piped until a respawn guard exists)
        std::process::Command::new("kill")
            .arg("-9")
            .arg(pid.to_string())
            .status()
            .expect("kill -9");
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        // next RPC must respawn + replay loads + deliver the mutation
        let out = sc
            .trigger("chat.message", json!({"sessionID": "s"}), json!({}))
            .await
            .expect("trigger after respawn");
        assert_eq!(out["alive"], true, "hook must fire after respawn");
        assert_ne!(sc.child_pid(), pid, "child process must be replaced");
        let st = sc.statuses();
        assert_eq!(
            st["reaper"]["ok"], true,
            "previously loaded plugins must be reloaded"
        );
        sc.shutdown().await;
        Ok(())
    }

    /// v2 plugin battery (Phase 3): both dialects through the real sidecar.
    /// A promise-flavor plugin registers a session hook + an RPC; an
    /// effect-flavor plugin (with its own `effect` runtime vendored beside it)
    /// registers a tool hook. Asserts detection, dispatch, RPC round-trip, the
    /// real inventory, and that unregistered/missing RPCs keep exact errors.
    #[tokio::test]
    async fn v2_battery_promise_and_effect_dialects() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("p_v2_promise.mjs"),
            r#"export default {
  id: "v2promise",
  setup: async (ctx) => {
    await ctx.session.hook("context", (ev) => { ev.promiseTouched = true; });
    await ctx.tool.hook("execute.after", (ev) => { ev.result = "mutated-by-promise"; });
    await ctx.rpc.register({ id: "sample" }, {
      hello: async (input) => ({ echoed: input, from: "promise" }),
    });
    await ctx.storage.set("k", 41);
    if ((await ctx.storage.get("k")) !== 41) throw new Error("storage broke");
  },
};"#,
        )
        .unwrap();
        let eff = dir
            .path()
            .join("p_v2_effect")
            .join("node_modules")
            .join("effect");
        std::fs::create_dir_all(eff.join("lib")).unwrap();
        std::fs::write(
            eff.join("package.json"),
            r#"{"name":"effect","version":"3.0.0","type":"module","exports":{".":"./lib/index.js"}}"#,
        )
        .unwrap();
        std::fs::write(
            eff.join("lib/index.js"),
            "export const Effect = { scoped: (p) => p, runPromise: async (p) => { await p; } };\nexport const Scope = {};\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join("p_v2_effect").join("plug.mjs"),
            r#"export default {
  id: "v2effect",
  effect: (ctx) => (async () => {
    await ctx.tool.hook("execute.before", (ev) => { ev.input.before = "effect"; });
  })(),
};"#,
        )
        .unwrap();

        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});

        let h1 = sc
            .load(
                "v2promise",
                &dir.path().join("p_v2_promise.mjs"),
                &input,
                &Value::Null,
            )
            .await?;
        assert!(
            h1.contains(&"session.context".to_string()),
            "promise hooks: {h1:?}"
        );
        assert!(h1.contains(&"tool.execute.after".to_string()));
        let h2 = sc
            .load(
                "v2effect",
                &dir.path().join("p_v2_effect").join("plug.mjs"),
                &input,
                &Value::Null,
            )
            .await?;
        assert!(
            h2.contains(&"tool.execute.before".to_string()),
            "effect hooks: {h2:?}"
        );

        let out = sc.trigger_v2("session", "context", json!({})).await?;
        assert_eq!(out["matched"], 1);
        assert_eq!(out["output"]["promiseTouched"], true);
        let after = sc
            .trigger_v2(
                "tool",
                "execute.after",
                json!({"tool": "read", "result": "orig"}),
            )
            .await?;
        assert_eq!(after["output"]["result"], "mutated-by-promise");
        let before = sc
            .trigger_v2(
                "tool",
                "execute.before",
                json!({"tool": "read", "input": {}}),
            )
            .await?;
        assert_eq!(before["output"]["input"]["before"], "effect");

        let rpc = sc.rpc_call("sample", "hello", json!({"n": 7})).await?;
        assert_eq!(rpc["output"]["echoed"]["n"], 7);
        let miss = sc.rpc_call("sample", "nope", json!({})).await?;
        assert_eq!(miss["error"]["type"], "rpc.method_not_found");
        let unreg = sc.rpc_call("ghost", "hello", json!({})).await?;
        assert_eq!(unreg["error"]["type"], "rpc.unavailable");

        let inv = sc.v2_inventory().await?;
        assert_eq!(inv["plugins"].as_array().unwrap().len(), 2, "{inv}");
        assert!(
            inv["rpcs"]
                .as_array()
                .unwrap()
                .iter()
                .any(|r| r == "sample")
        );

        sc.shutdown().await;
        Ok(())
    }

    /// Every hook upstream declares must be REGISTRABLE. Registering
    /// `experimental.ws.handshake` used to throw `unknown session hook`, which
    /// failed the plugin's whole setup and discarded the hooks ocserve does
    /// dispatch (found 2026-10-23 by diffing bench/v2/hooks.json against the
    /// shim table).
    #[tokio::test]
    async fn v2_accepts_every_declared_hook_at_registration() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        // One plugin registers every hook the extracted surface declares.
        let surface: serde_json::Value =
            serde_json::from_str(include_str!("../tests/fixtures/v2-hooks.json"))?;
        let mut body =
            String::from("export default {\n  id: \"v2allhooks\",\n  setup: async (ctx) => {\n");
        for (domain, hooks) in surface.as_object().unwrap() {
            for hook in hooks.as_array().unwrap() {
                let hook = hook.as_str().unwrap();
                body.push_str(&format!(
                    "    await ctx.{domain}.hook(\"{hook}\", () => {{}});\n"
                ));
            }
        }
        body.push_str("    await ctx.event.subscribe(() => {});\n  },\n};\n");
        std::fs::write(dir.path().join("all_hooks.mjs"), body).unwrap();
        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        let h = sc
            .load(
                "v2allhooks",
                &dir.path().join("all_hooks.mjs"),
                &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
                &Value::Null,
            )
            .await
            .expect("every declared hook must register without failing setup");
        for d in ["session", "tool", "permission", "shell"] {
            assert!(
                h.iter().any(|x| x == d || x.starts_with(&format!("{d}."))),
                "no {d} hook registered: {h:?}"
            );
        }
        sc.shutdown().await;
        Ok(())
    }

    /// A v2 plugin that registers a transform on an UNBRIDGED domain must still
    /// load, and the divergence must be reported.
    ///
    /// The corpus run on 2026-10-21 found four real plugins failing to load with
    /// `D-V2-DOMAIN: ctx.<domain>.transform is not bridged`. They were not
    /// broken plugins: they register transforms during `setup`, which is
    /// upstream's only way to contribute to those domains, and our shim threw on
    /// the registration call. That failed the WHOLE plugin, discarding the hooks
    /// we do bridge — `session.context`, `tool.execute.before`, events. A
    /// divergence must degrade one capability, never the plugin.
    ///
    /// The transform is accepted and recorded, never invoked (calling it would
    /// mean applying an edit ocserve cannot apply), and the domain is reported in
    /// the inventory so the operator can see it.
    #[tokio::test]
    async fn v2_unbridged_transform_registers_instead_of_failing_setup() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("p_v2_edit.mjs"),
            r#"export default {
  id: "v2edit",
  setup: async (ctx) => {
    // A transform on a domain ocserve does not bridge (upstream's registration
    // form, so this is what real plugins do).
    await ctx.tool.transform((editor) => { editor.remove("bash"); });
    await ctx.integration.transform(() => {});
    // The common transform -> reload -> list sequence: reload must resolve.
    await ctx.provider.reload();
    // The hooks we DO bridge must survive.
    await ctx.session.hook("context", (ev) => { ev.survived = true; });
  },
};"#,
        )
        .unwrap();

        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});

        let hooks = sc
            .load(
                "v2edit",
                &dir.path().join("p_v2_edit.mjs"),
                &input,
                &Value::Null,
            )
            .await
            .expect("a transform on an unbridged domain must not fail setup");

        // The bridged hook registered by the same plugin still works.
        assert!(
            hooks.contains(&"session.context".to_string()),
            "the bridged hook must survive: {hooks:?}"
        );
        let out = sc.trigger_v2("session", "context", json!({})).await?;
        assert_eq!(out["matched"], 1);
        assert_eq!(out["output"]["survived"], true);

        // And the unbridged domains are reported, not silently swallowed.
        let inv = sc.v2_inventory().await?;
        let unbridged: Vec<String> = inv["unbridged_transforms"]
            .as_array()
            .expect("inventory must list unbridged transforms")
            .iter()
            .map(|v| v.as_str().unwrap_or_default().to_string())
            .collect();
        assert!(unbridged.contains(&"tool".to_string()), "{inv}");
        assert!(unbridged.contains(&"integration".to_string()), "{inv}");

        // Genuine USE of an unbridged domain still throws its named divergence
        // (the capability really is absent; only registration is tolerated).
        std::fs::write(
            dir.path().join("p_v2_use.mjs"),
            r#"export default {
  id: "v2use",
  setup: async (ctx) => { await ctx.vcs.apply({}); },
};"#,
        )
        .unwrap();
        let err = sc
            .load(
                "v2use",
                &dir.path().join("p_v2_use.mjs"),
                &input,
                &Value::Null,
            )
            .await
            .expect_err("using an unbridged domain must still fail loudly");
        let text = format!("{err:#}");
        assert!(text.contains("D-V2-DOMAIN"), "{text}");
        assert!(text.contains("vcs"), "{text}");

        sc.shutdown().await;
        Ok(())
    }

    /// The v2 REST half of a domain is bound to the route that actually exists —
    /// and an UNBOUND verb keeps the named divergence instead of a bare TypeError.
    ///
    /// The 2026-10-18 finding: `session: { ...registrar("session") }` gave
    /// `ctx.session` only `hook`, so `ctx.session.get(id)` was
    /// `TypeError: ... is not a function` — a crash, not the honest throw the rest
    /// of the shim uses. `ctx.plugin.list()` likewise returned `[]` while
    /// `/api/plugin` serves the real inventory (D-PLUGIN-INVENTORY was closed).
    #[tokio::test]
    async fn v2_domain_rest_methods_bind_real_routes() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        // A real HTTP responder so ctx.session.get() exercises an actual route
        // (stdlib thread; the shim fetches it like any other client would).
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut s) = stream else { continue };
                use std::io::{Read, Write};
                let mut buf = [0u8; 2048];
                let _ = s.read(&mut buf);
                let body = br#"{"id":"ses_bound","title":"bound-route"}"#;
                let _ = s.write_all(
                format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                    body.len()
                )
                .as_bytes(),
            );
                let _ = s.write_all(body);
            }
        });

        let dir = tempfile::tempdir().unwrap();
        // The fixture reports each probe's outcome back over RPC so the test can
        // read real results (not shim internals).
        std::fs::write(
            dir.path().join("rest.mjs"),
            r#"export default {
  id: "restprobe",
  setup: async (ctx) => {
    const results = {};
    // plugin.list must return the REAL inventory, not [].
    results.pluginList = await ctx.plugin.list();
    // session.get must reach the bound route.
    try {
      const s = await ctx.session.get("ses_bound");
      results.sessionGet = { ok: true, id: s && s.id };
    } catch (e) { results.sessionGet = { ok: false, err: String(e && e.message || e) }; }
    // An UNBOUND verb must throw the NAMED divergence, not a TypeError.
    try { await ctx.session.notARealVerb("x"); results.unbound = { threw: false }; }
    catch (e) { results.unbound = { threw: true, msg: String(e && e.message || e) }; }
    await ctx.rpc.register({ id: "probe" }, { results: async () => results });
  },
};"#,
        )
        .unwrap();

        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, &format!("http://127.0.0.1:{port}"), "/work").await?;
        let input = json!({"directory": "/work", "serverUrl": format!("http://127.0.0.1:{port}")});
        sc.load(
            "restprobe",
            &dir.path().join("rest.mjs"),
            &input,
            &Value::Null,
        )
        .await?;

        let r = sc.rpc_call("probe", "results", json!({})).await?;
        let out = &r["output"];

        // 1. plugin.list is real (contains our own id), not empty.
        let listed = out["pluginList"].as_array().cloned().unwrap_or_default();
        assert!(
            listed.iter().any(|p| p["id"] == "restprobe"),
            "ctx.plugin.list() must report the loaded plugin: {out}"
        );

        // 2. session.get hit the bound route (the stub answered ses_bound).
        assert_eq!(
            out["sessionGet"]["ok"], true,
            "ctx.session.get must reach /api/session/{{id}}: {out}"
        );
        assert_eq!(out["sessionGet"]["id"], "ses_bound");

        // 3. an unbound verb throws the NAMED divergence (D-V2-DOMAIN), not a
        //    TypeError and not silently succeeding.
        assert_eq!(
            out["unbound"]["threw"], true,
            "unbound verb must throw: {out}"
        );
        let msg = out["unbound"]["msg"].as_str().unwrap_or_default();
        assert!(
            msg.contains("D-V2-DOMAIN"),
            "unbound verb must name the divergence (D-V2-DOMAIN), got: {msg}"
        );

        sc.shutdown().await;
        Ok(())
    }

    /// A v2 plugin's `command.transform` / `skill.transform` edits are PULLED by
    /// Rust and come back as the list both consumers serve.
    ///
    /// The all-consumers rule (TESTING §1): `skill_entries()` filters
    /// `Payloads.command` on `source=="skill"`, so a skill transform must change
    /// the SYSTEM PROMPT the model reads, not just the `/command` route. A test
    /// that only asserted the RPC round-trip would pass while the prompt kept the
    /// old text — shape without mutation.
    ///
    /// Also covers: add REPLACES a same-named entry (upstream `editor.set`,
    /// core/command.ts:61, so a reload is idempotent), and a THROWING transform is
    /// reported without taking the list down.
    #[tokio::test]
    async fn v2_command_transform_pulls_into_the_served_list() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("tx.mjs"),
            r#"export default {
  id: "tx",
  setup: async (ctx) => {
    // upstream shape: ctx.command.transform((editor) => editor.add({...}))
    await ctx.command.transform((editor) => {
      editor.add({ name: "plugin-cmd", description: "added by plugin" });
    });
    await ctx.skill.transform((editor) => {
      editor.update("demo-skill", (s) => { s.description = "rewritten by plugin"; });
      editor.add({ name: "plugin-skill", description: "skill from plugin", source: "skill" });
    });
    await ctx.command.reload();
    const listed = await ctx.command.list();
    await ctx.rpc.register({ id: "probe" }, {
      afterSetup: async () => ({ listed }),
    });
  },
};"#,
        )
        .unwrap();

        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
        let input = json!({"directory": "/work"});
        sc.load("tx", &dir.path().join("tx.mjs"), &input, &Value::Null)
            .await?;

        // The pristine list: one skill (what ocserve's own config produced) and
        // one config command. Skills and commands share ONE vector.
        let pristine = vec![
            json!({"name": "demo-skill", "description": "original", "source": "skill"}),
            json!({"name": "review", "description": "config command", "source": "config"}),
        ];
        let (edited, failures) = sc.transform_commands(pristine.clone()).await?;

        assert!(
            failures.is_empty(),
            "no transform should have failed: {failures:?}"
        );
        // 1. the command transform's add landed
        let added = edited
            .iter()
            .find(|c| c["name"] == "plugin-cmd")
            .expect("plugin command must be present");
        assert_eq!(added["description"], "added by plugin");
        // 2. the skill transform's update landed — THIS is the prompt-visible half
        let skill = edited
            .iter()
            .find(|c| c["name"] == "demo-skill")
            .expect("demo-skill must still be present");
        assert_eq!(
            skill["description"], "rewritten by plugin",
            "skill.transform must reach the vector skill_entries() reads"
        );
        // 3. the skill add landed with the skill source (so skill_entries picks it up)
        assert!(
            edited
                .iter()
                .any(|c| c["name"] == "plugin-skill" && c["source"] == "skill"),
            "plugin skill must carry source=skill or skill_entries() drops it: {edited:?}"
        );
        // 4. untouched entries survive (the all-consumers rule cuts both ways)
        assert!(edited.iter().any(|c| c["name"] == "review"));

        // 5. IDEMPOTENT: a second pull from pristine yields the same list (add
        //    replaces, never accumulates).
        let (again, _) = sc.transform_commands(pristine.clone()).await?;
        assert_eq!(
            serde_json::to_value(&again).unwrap(),
            serde_json::to_value(&edited).unwrap(),
            "a reload must not accumulate duplicates"
        );

        // 6. a pull over a one-entry list keeps that entry (the plugin's own adds are
        //    additive; the caller must never receive a shorter list than it sent)
        let (kept, _) = sc
            .transform_commands(vec![json!({"name": "keepme"})])
            .await?;
        assert!(kept.iter().any(|c| c["name"] == "keepme"));

        sc.shutdown().await;
        Ok(())
    }

    /// A throwing v2 transform is reported, never fatal — upstream's state machine
    /// disables a failing transform (core/state.ts:178-184) rather than
    /// propagating, because a broken third-party plugin must not take the server's
    /// command surface down with it.
    #[tokio::test]
    async fn v2_command_transform_failure_keeps_the_list() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("boom.mjs"),
            r#"export default {
  id: "boom",
  setup: async (ctx) => {
    await ctx.command.transform(() => { throw new Error("transform exploded"); });
    await ctx.command.transform((editor) => { editor.add({ name: "survivor" }); });
  },
};"#,
        )
        .unwrap();

        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
        let input = json!({"directory": "/work"});
        sc.load("boom", &dir.path().join("boom.mjs"), &input, &Value::Null)
            .await?;

        let (kept, failures) = sc
            .transform_commands(vec![json!({"name": "existing"})])
            .await?;
        // the good transform still ran (a broken one does not abort the rest)
        assert!(
            kept.iter().any(|c| c["name"] == "survivor"),
            "a throwing transform must not stop the others: {kept:?}"
        );
        assert!(kept.iter().any(|c| c["name"] == "existing"));
        // and the failure is reported so the server can log + count it
        assert_eq!(failures.len(), 1, "the throwing transform must be reported");
        assert!(
            failures[0]["message"]
                .as_str()
                .unwrap_or_default()
                .contains("transform exploded"),
            "{failures:?}"
        );

        sc.shutdown().await;
        Ok(())
    }

    /// The `config` hook is dispatched (v1 parity, plugin/index.ts:244-251).
    /// Closes the registered-but-never-called class: a plugin whose `config`
    /// is a real hook must see it run (host `config` used to hard-code "ok").
    #[tokio::test]
    async fn config_hook_is_dispatched() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("cfg.mjs"),
            r#"export const PluginModule = {
  id: "cfg",
  server: async () => ({
    config: async (cfg) => {
      if (typeof cfg !== "object" || cfg === null) throw new Error("config not object");
    },
    "chat.message": async () => {},
  }),
};
export default PluginModule.server;"#,
        )
        .unwrap();
        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        sc.load("cfg", &dir.path().join("cfg.mjs"), &json!({}), &Value::Null)
            .await?;
        let r = sc.config(json!({"model": "x"})).await?;
        assert_eq!(r["matched"], 1, "config hook must be dispatched: {r}");
        sc.shutdown().await;
        Ok(())
    }

    /// Test environment gate: the ACTUAL runtime (bun preferred) must exist.
    fn runtime_available() -> bool {
        crate::which(crate::plugin_runtime().program()).is_some()
    }

    /// Real-plugin battery (V2-EXECUTION-PLAN Phase 2): every v1 authoring
    /// form the frozen client supports (plugin/index.ts readV1Plugin +
    /// getLegacyPlugins) plus the `[spec, options]` tuple. Loads all forms
    /// through ONE sidecar (as production does) and asserts each registered
    /// the expected hook AND that options actually reach the factory (the
    /// silently-dropped-tuple bug this battery exists to pin).
    #[tokio::test]
    async fn battery_all_authoring_forms_and_options() -> anyhow::Result<()> {
        if !runtime_available() {
            panic!(
                "plugin-runtime binary ({}) required for plugin-host tests",
                crate::plugin_runtime().program()
            );
        }
        let dir = tempfile::tempdir().unwrap();
        // 1. PluginModule.server (v1 canonical)
        std::fs::write(
            dir.path().join("p_module.mjs"),
            r#"export const PluginModule = {
  id: "m",
  server: async () => ({ "chat.message": async (_i, o) => { o.module = true; } }),
};"#,
        )
        .unwrap();
        // 2. default object with .server
        std::fs::write(
            dir.path().join("p_default_obj.mjs"),
            r#"export default { server: async () => ({ "chat.params": async (_i, o) => { o.defaultobj = true; } }) };"#,
        )
        .unwrap();
        // 3. default function (legacy)
        std::fs::write(
            dir.path().join("p_default_fn.mjs"),
            r#"export default async () => ({ "tool.execute.after": async (_i, o) => { o.defaultfn = true; } });"#,
        )
        .unwrap();
        // 4. named plain-function export (each IS a server factory)
        std::fs::write(
            dir.path().join("p_named.mjs"),
            r#"export async function MyPlugin() { return { "event": async () => {} }; }"#,
        )
        .unwrap();
        // 5. options tuple: the factory must SEE the second tuple element.
        std::fs::write(
            dir.path().join("p_options.mjs"),
            r#"export const PluginModule = {
  id: "opts",
  server: async (_input, options) => ({
    "chat.message": async (_i, o) => { o.sawOptions = options; },
  }),
};"#,
        )
        .unwrap();

        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        let input =
            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});

        let h1 = sc
            .load("m", &dir.path().join("p_module.mjs"), &input, &Value::Null)
            .await?;
        assert_eq!(h1, vec!["chat.message"], "PluginModule.server form");
        let h2 = sc
            .load(
                "dobj",
                &dir.path().join("p_default_obj.mjs"),
                &input,
                &Value::Null,
            )
            .await?;
        assert_eq!(h2, vec!["chat.params"], "default object with .server form");
        let h3 = sc
            .load(
                "dfn",
                &dir.path().join("p_default_fn.mjs"),
                &input,
                &Value::Null,
            )
            .await?;
        assert_eq!(
            h3,
            vec!["tool.execute.after"],
            "default function (legacy) form"
        );
        let h4 = sc
            .load(
                "named",
                &dir.path().join("p_named.mjs"),
                &input,
                &Value::Null,
            )
            .await?;
        assert_eq!(h4, vec!["event"], "named function export form");

        let opts = json!({"token": "abc", "n": 3});
        let h5 = sc
            .load("opts", &dir.path().join("p_options.mjs"), &input, &opts)
            .await?;
        assert_eq!(
            h5,
            vec!["chat.message"],
            "options-tuple form registers same hook"
        );

        // Dispatch across ALL loaded plugins: each form's hook fires.
        let out = sc.trigger("chat.message", json!({}), json!({})).await?;
        assert_eq!(out["module"], true, "form 1 hook fired");
        // options reached the factory (the tuple was NOT dropped)
        assert_eq!(out["sawOptions"], opts, "factory saw the tuple options");
        let out2 = sc.trigger("chat.params", json!({}), json!({})).await?;
        assert_eq!(out2["defaultobj"], true, "form 2 hook fired");
        let out3 = sc
            .trigger("tool.execute.after", json!({}), json!({}))
            .await?;
        assert_eq!(out3["defaultfn"], true, "form 3 hook fired");

        // statuses carry all five loads (real inventory, not empty).
        let st = sc.statuses();
        for spec in ["m", "dobj", "dfn", "named", "opts"] {
            assert_eq!(st[spec]["ok"], true, "status for {spec}");
        }
        sc.shutdown().await;
        Ok(())
    }
}

#[cfg(test)]
mod runtime_selection_tests {
    /// `OCSERVE_PLUGIN_RUNTIME` forces the runtime (lab A/B control);
    /// unset/unknown → bun-if-present else node. Env is process-local and
    /// restored (this file is the only env mutator in its own process).
    #[test]
    fn runtime_override_and_default_preference() {
        let has_bun = crate::which("bun").is_some();
        let has_node = crate::which("node").is_some();
        if !has_node {
            panic!("node required for the fallback leg (test environment gate)");
        }

        // SAFETY: single-threaded env mutation, restored below.
        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
        assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);

        if has_bun {
            unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
            assert_eq!(
                crate::plugin_runtime(),
                crate::PluginRuntime::Bun,
                "bun present + no override → bun preferred (upstream fidelity)"
            );
        } else {
            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
        }

        // unknown value falls through to preference, never panics
        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
        let _ = crate::plugin_runtime();
        unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
    }
}

#[cfg(test)]
mod oom_wrapper_tests {
    /// A3 proof: the spawn wrapper makes the CHILD report adj=500 so a
    /// memcg OOM kill takes the child (respawnable) — not the main service.
    #[cfg(target_os = "linux")]
    #[test]
    fn wrapper_raises_child_oom_score_adj() {
        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(ocserve_store::cgroup::WRAPPER)
            .arg("sh")
            .arg("cat")
            .arg("/proc/self/oom_score_adj")
            .output()
            .expect("wrapper spawns");
        assert!(
            out.status.success(),
            "wrapper failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(
            String::from_utf8_lossy(&out.stdout).trim(),
            "500",
            "child must run at adj=500"
        );
    }
}

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

    /// A plugin tool's Zod args must become a VALID JSON Schema before it
    /// reaches the provider. The first implementation passed the raw Zod
    /// objects straight through (`{~standard, def, type}`) and the provider
    /// rejected every request in the session with 400 (found live on
    /// `ctx_reduce`, 2026-10-23).
    #[tokio::test]
    async fn plugin_tool_schema_is_valid_json_schema() -> anyhow::Result<()> {
        let dir = tempfile::tempdir()?;
        let entry = dir.path().join("p_schema.mjs");
        std::fs::write(
            &entry,
            r#"import { z } from "zod";
export const hook = async () => ({
  tool: {
    ztool: {
      description: "zod args",
      args: {
        text: z.string(),
        count: z.number(),
      },
      execute: async () => "ok",
    },
  },
});"#,
        )?;
        // `z` is resolved from the plugin's own tree, exactly like a real one.
        std::fs::create_dir_all(dir.path().join("node_modules/zod"))?;
        std::fs::write(
            dir.path().join("node_modules/zod/package.json"),
            r#"{"name":"zod","version":"4.0.0","main":"./index.cjs","exports":{".":"./index.cjs","./v4":"./index.cjs"}}"#,
        )?;
        std::fs::write(
            dir.path().join("node_modules/zod/index.cjs"),
            "exports.object = (shape) => ({ shape }); exports.z = { object: (shape) => ({ shape }), string: () => ({ _zod: 1, type: 'string' }), number: () => ({ _zod: 1, type: 'number' }) }; exports.toJSONSchema = () => ({ type: 'object', properties: { text: { type: 'string' }, count: { type: 'integer' } }, required: ['text'] });",
        )?;
        let host = materialize_host(&dir.path().join("host"))?;
        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
        sc.load(
            "schema-fixture",
            &entry,
            &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
            &Value::Null,
        )
        .await?;
        let tools = sc.handle().tools().await?;
        let tool = tools
            .iter()
            .find(|t| t["name"] == "ztool")
            .expect("ztool advertised");
        let params = &tool["parameters"];
        assert_eq!(params["type"], "object", "{params}");
        assert_eq!(params["properties"]["text"]["type"], "string", "{params}");
        assert!(
            params["properties"]["text"].get("~standard").is_none()
                && params["properties"]["text"].get("def").is_none(),
            "a raw Zod object must never reach the provider: {params}"
        );
        sc.shutdown().await;
        Ok(())
    }
}