Skip to main content

ocserve_plugin/
lib.rs

1//! ocserve-plugin: opencode plugin compatibility via a Node sidecar (M4b).
2//!
3//! Gate rationale (PLAN §10, evidence not assumption): the frozen plugins
4//! import `bun:sqlite`, `child_process`, `node:fs/crypto/url` and TTY UI
5//! modules (import audit of the actual artifacts). A quickjs embed would need
6//! a dozen shims with a *synchronous* SQLite bridge — rejected as high-risk;
7//! one Node sidecar (v25 present, `node:sqlite` built in) is the low-
8//! maintenance host. Isolation: sidecar crash/restart cannot take down the
9//! server; protocol = NDJSON on stdio; plugin chatter is forced to stderr by
10//! the host so framing cannot corrupt.
11#![cfg_attr(not(test), forbid(unsafe_code))]
12
13pub mod normalize;
14pub use normalize::{Outcome as NormalizeOutcome, normalize_or_raw_sync};
15
16use anyhow::{Context, Result, anyhow};
17use serde_json::{Value, json};
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use tokio::io::{AsyncWriteExt, BufReader};
22use tokio::process::{Child, ChildStdin, Command};
23use tokio::sync::oneshot;
24
25/// Host files (written next to the data dir once; content-addressed by embed).
26pub const HOST_FILES: &[(&str, &str)] = &[
27    ("host.mjs", include_str!("host/host.mjs")),
28    ("v2.mjs", include_str!("host/v2.mjs")),
29    (
30        "bun-sqlite-loader.mjs",
31        include_str!("host/bun-sqlite-loader.mjs"),
32    ),
33    (
34        "shim-bun-sqlite.mjs",
35        include_str!("host/shim-bun-sqlite.mjs"),
36    ),
37    (
38        "shim-bun-sqlite.cjs",
39        include_str!("host/shim-bun-sqlite.cjs"),
40    ),
41];
42
43/// Per-RPC timeout (hooks are local JS; anything longer is a runaway plugin).
44pub const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
45
46/// Write host files into `dir` (idempotent overwrite — embed is authoritative).
47pub fn materialize_host(dir: &Path) -> Result<PathBuf> {
48    std::fs::create_dir_all(dir).with_context(|| format!("create host dir {}", dir.display()))?;
49    for (name, body) in HOST_FILES {
50        let path = dir.join(name);
51        std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
52    }
53    Ok(dir.join("host.mjs"))
54}
55
56/// Resolve a plugin spec to an entry file (loader.ts semantics, npm-install
57/// stage assumed already done by opencode's cache — we re-use it read-only):
58/// - `file://` URL (what upstream configs and launchers inject) → path
59/// - absolute/relative path → direct entry (a directory resolves through its
60///   package.json or conventional `index`/`server` files, v2 config semantics)
61/// - npm spec (`name`, `@scope/name`, `name@version`) →
62///   `~/.cache/opencode/packages/{spec}[@latest]/node_modules/{pkg}/…` entry
63///   via package.json exports["."] | main | module
64pub fn resolve_entry(spec: &str, home: &Path) -> Result<PathBuf> {
65    if let Some(p) = file_url_path(spec) {
66        return entry_from_path(&p);
67    }
68    // Upstream config paths are allowed to start with `~/`; a literal tilde
69    // otherwise falls through to the npm cache and reports "not found".
70    if let Some(rest) = spec.strip_prefix("~/") {
71        return entry_from_path(&home.join(rest));
72    }
73    if is_path_spec(spec) {
74        return entry_from_path(Path::new(spec));
75    }
76    let cache = home.join(".cache/opencode/packages");
77    let pkg_name = strip_version(spec);
78    let candidates = [
79        cache.join(format!("{spec}@latest")),
80        cache.join(spec),
81        cache.join(format!("{pkg_name}@latest")),
82    ];
83    for dir in &candidates {
84        if !dir.exists() {
85            continue;
86        }
87        // wrapper package.json → node_modules/<pkg>/package.json
88        let direct = dir.join("package.json");
89        if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
90            return Ok(entry);
91        }
92        let nested = dir
93            .join("node_modules")
94            .join(&pkg_name)
95            .join("package.json");
96        if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
97        {
98            return Ok(entry);
99        }
100    }
101    anyhow::bail!("plugin target not found in opencode cache: {spec}")
102}
103
104/// Upstream `isPathPluginSpec`: `file://`, dot-relative, absolute, or a
105/// Windows drive path (`C:\…` / `C:/…`).
106fn is_path_spec(spec: &str) -> bool {
107    let b = spec.as_bytes();
108    let drive = b.len() >= 3
109        && b[0].is_ascii_alphabetic()
110        && b[1] == b':'
111        && (b[2] == b'\\' || b[2] == b'/');
112    spec.starts_with('/')
113        || spec.starts_with("./")
114        || spec.starts_with("../")
115        || Path::new(spec).is_absolute()
116        || drive
117}
118
119/// Resolve a concrete path: a file IS the entry; a directory resolves to its
120/// package entry (v2 `plugins` entries point at package directories).
121fn entry_from_path(p: &Path) -> Result<PathBuf> {
122    // Absolutize before the containment check: a relative base containing
123    // `..` otherwise makes `entry_from_package`'s normalized entry look like
124    // an escape (`../pkg` + `dist/x.js` → `pkg/dist/x.js`).
125    let abs;
126    let p = if p.is_absolute() {
127        p
128    } else {
129        match std::env::current_dir() {
130            Ok(cwd) => {
131                abs = cwd.join(p);
132                &abs
133            }
134            Err(_) => p,
135        }
136    };
137    if p.is_file() {
138        return Ok(p.to_path_buf());
139    }
140    if p.is_dir() {
141        return dir_entry(p)
142            .ok_or_else(|| anyhow!("plugin directory has no entrypoint: {}", p.display()));
143    }
144    anyhow::bail!("plugin file not found: {}", p.display())
145}
146
147/// Entry file of a plugin DIRECTORY. Upstream `resolvePathPluginTarget`
148/// (`plugin/shared.ts`): package.json first (`exports["./server"]`, then
149/// `main`/`module`), else `index.{ts,tsx,js,mjs,cjs}`.
150fn dir_entry(dir: &Path) -> Option<PathBuf> {
151    if let Some(entry) = entry_from_package(&dir.join("package.json"), dir, "") {
152        return Some(entry);
153    }
154    for name in [
155        "index.ts",
156        "index.tsx",
157        "index.js",
158        "index.mjs",
159        "index.cjs",
160    ] {
161        let p = dir.join(name);
162        if p.is_file() {
163            return Some(p);
164        }
165    }
166    None
167}
168
169/// `file://` URL → local path (Paseo and other launchers configure plugins as
170/// `pathToFileURL(...)`). Percent-decoding is required: a temp path with a
171/// space is otherwise "not found". Returns None for non-file specs; a
172/// non-localhost authority is not supported (there is no local path).
173fn file_url_path(spec: &str) -> Option<PathBuf> {
174    let rest = spec.strip_prefix("file://")?;
175    // `file:///tmp/x` (empty authority) or `file://localhost/tmp/x`.
176    let rest = match rest.strip_prefix("localhost") {
177        Some(r) if r.starts_with('/') => r,
178        _ => rest,
179    };
180    if !rest.starts_with('/') {
181        return None;
182    }
183    let decoded = percent_decode(rest);
184    if decoded.is_empty() {
185        return None;
186    }
187    #[cfg(windows)]
188    let decoded = decoded.trim_start_matches('/').to_string();
189    Some(PathBuf::from(decoded))
190}
191
192fn percent_decode(s: &str) -> String {
193    let bytes = s.as_bytes();
194    let mut out = Vec::with_capacity(bytes.len());
195    let mut i = 0;
196    while i < bytes.len() {
197        if bytes[i] == b'%'
198            && i + 2 < bytes.len()
199            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
200        {
201            out.push(hi * 16 + lo);
202            i += 3;
203            continue;
204        }
205        out.push(bytes[i]);
206        i += 1;
207    }
208    String::from_utf8_lossy(&out).into_owned()
209}
210
211fn hex_nibble(b: u8) -> Option<u8> {
212    match b {
213        b'0'..=b'9' => Some(b - b'0'),
214        b'a'..=b'f' => Some(b - b'a' + 10),
215        b'A'..=b'F' => Some(b - b'A' + 10),
216        _ => None,
217    }
218}
219
220/// Auto-discovered plugin targets under `<config_dir>/{plugin,plugins}`.
221///
222/// Upstream v2 `PluginSourceDirectory.discover`: a FILE ending `.ts`/`.js`, or
223/// ANY directory (a package with its own entrypoint). Sorted, deduped and
224/// CAPPED — a hostile/huge config dir must not make every `/api/plugin` poll
225/// pay an unbounded scan (AGENTS §2.3). `.mjs` files are deliberately not
226/// discovered (upstream does not); an explicitly configured spec may still
227/// name one.
228pub fn discover_plugin_specs(config_dir: &Path) -> Vec<String> {
229    const MAX_DISCOVERED: usize = 64;
230    let mut out = Vec::new();
231    for sub in ["plugin", "plugins"] {
232        let dir = config_dir.join(sub);
233        let Ok(entries) = std::fs::read_dir(&dir) else {
234            continue;
235        };
236        let mut entries: Vec<_> = entries.flatten().collect();
237        entries.sort_by_key(|e| e.file_name());
238        for entry in entries {
239            if out.len() >= MAX_DISCOVERED {
240                break;
241            }
242            let path = entry.path();
243            // `metadata` follows symlinks: a linked plugin file/dir loads like
244            // the target, matching upstream's isFile/isDir checks.
245            let Ok(meta) = std::fs::metadata(&path) else {
246                continue;
247            };
248            let is_source = meta.is_file()
249                && matches!(
250                    path.extension().and_then(|e| e.to_str()),
251                    Some("ts") | Some("js")
252                );
253            if (is_source || meta.is_dir())
254                && let Some(s) = path.to_str()
255            {
256                out.push(s.to_string());
257            }
258        }
259    }
260    out.sort();
261    out.dedup();
262    out.truncate(MAX_DISCOVERED);
263    out
264}
265
266fn strip_version(spec: &str) -> String {
267    // "@scope/name@latest" → "@scope/name"; "name@1.2.3" → "name"
268    let bytes = spec.as_bytes();
269    // find the LAST '@' that is NOT at index 0 (scope marker)
270    let mut cut = None;
271    for (i, b) in bytes.iter().enumerate() {
272        if *b == b'@' && i > 0 {
273            cut = Some(i);
274        }
275    }
276    match cut {
277        Some(i) => spec[..i].to_string(),
278        None => spec.to_string(),
279    }
280}
281
282fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
283    let text = std::fs::read_to_string(pkg_json).ok()?;
284    let v: Value = serde_json::from_str(&text).ok()?;
285    let mut rel: Option<&str> = None;
286    if let Some(exp) = v.get("exports") {
287        // `exports["."]` is the npm entry; v2 plugin packages name their
288        // server part `exports["./server"]` (upstream `resolvePathPluginTarget`
289        // tries that first for a directory target).
290        for key in [".", "./server"] {
291            let Some(dot) = exp.get(key) else { continue };
292            rel = match dot {
293                Value::String(s) => Some(s.as_str()),
294                Value::Object(_) => dot
295                    .get("import")
296                    .and_then(|x| x.as_str())
297                    .or_else(|| dot.get("default").and_then(|x| x.as_str())),
298                _ => None,
299            };
300            if rel.is_some() {
301                break;
302            }
303        }
304    }
305    rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
306    rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
307    let rel = rel?;
308    let entry = base.join(rel);
309    // G6: the package's own `exports`/`main`/`module` may point outside the
310    // package (e.g. `../../other`). Lexically normalize and require the entry
311    // to stay inside `base`; a plugin entry is loaded only from its package.
312    let lex = lexically_normalize(&entry);
313    if !lex.starts_with(base)
314        && !std::fs::canonicalize(base)
315            .ok()
316            .is_some_and(|cb| lex.starts_with(&cb))
317    {
318        tracing::warn!("plugin entry {rel} escapes its package dir — refused");
319        return None;
320    }
321    lex.exists().then_some(lex)
322}
323
324fn lexically_normalize(p: &Path) -> PathBuf {
325    use std::path::Component;
326    let mut out = PathBuf::new();
327    for c in p.components() {
328        match c {
329            Component::ParentDir => {
330                out.pop();
331            }
332            Component::CurDir => {}
333            other => out.push(other.as_os_str()),
334        }
335    }
336    out
337}
338
339struct Pending {
340    tx: oneshot::Sender<Result<Value, String>>,
341}
342
343/// Removes its id from `pending` on every exit path, including a cancelled
344/// future. Without this, abort/delete cancel the awaiting task, the entry
345/// leaks, and `in_flight()` never returns 0 — the L1 recycle gate wedges.
346struct PendingGuard {
347    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
348    id: i64,
349}
350
351impl PendingGuard {
352    fn new(pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>, id: i64) -> Self {
353        Self { pending, id }
354    }
355}
356
357impl Drop for PendingGuard {
358    fn drop(&mut self) {
359        self.pending.lock().remove(&self.id);
360    }
361}
362
363/// Everything a request needs, shareable WITHOUT the owning `Sidecar` lock.
364///
365/// Why this exists (2026-10-22): `hook_mutate` held `Arc<Mutex<Sidecar>>` for
366/// the whole hook await, so two sessions' hooks fully serialized — the
367/// reference interleaves them at `await` points. Writes are serialized by the
368/// stdin mutex and responses correlate by id, so nothing needs exclusive
369/// access to the process while a hook runs.
370///
371/// Liveness (2026-10-23 review): a handle is tied to ONE child generation.
372/// The reader marks `alive=false` when it stops, and `poisoned=true` when the
373/// protocol is no longer trustworthy; both make requests fail fast, and the
374/// owner's `ensure_alive` replaces the generation. A stale handle can never
375/// deliver a response to the wrong waiter.
376pub struct Inner {
377    stdin: tokio::sync::Mutex<ChildStdin>,
378    /// SHARED with the reader task (it resolves responses by id).
379    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
380    next_id: std::sync::atomic::AtomicI64,
381    /// load results (spec → {hooks,…}) for introspection AND round-trip skips.
382    statuses: parking_lot::Mutex<HashMap<String, Value>>,
383    /// reader still running; false = requests must not be attempted.
384    alive: Arc<std::sync::atomic::AtomicBool>,
385    /// the child must be replaced before the next request (framing lost).
386    poisoned: Arc<std::sync::atomic::AtomicBool>,
387    /// last successfully fetched plugin-tool list. A busy host must not make
388    /// plugin tools vanish from the provider schema for a round (M6).
389    last_tools: parking_lot::Mutex<Option<Vec<Value>>>,
390}
391
392/// Cheap clone handle: hook dispatch drops the owner lock and awaits this.
393#[derive(Clone)]
394pub struct Handle(Arc<Inner>);
395
396impl Handle {
397    /// Is this generation still able to answer? Used by callers to decide
398    /// between a fast failure and a recovery attempt.
399    pub fn is_alive(&self) -> bool {
400        self.0.alive.load(std::sync::atomic::Ordering::Acquire)
401    }
402
403    /// Does any loaded plugin register `hook`? Lets the hot path skip the
404    /// sidecar round-trip entirely when nobody listens (most installs).
405    pub fn registers(&self, hook: &str) -> bool {
406        self.0.statuses.lock().values().any(|v| {
407            v.get("hooks")
408                .and_then(|h| h.as_array())
409                .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(hook)))
410        })
411    }
412
413    /// Any v1 or v2 plugin loaded successfully. The tool fetch is gated on
414    /// this (not on a specific hook/tool count) because v2 tools can be added
415    /// after load.
416    pub fn any_loaded(&self) -> bool {
417        self.0
418            .statuses
419            .lock()
420            .values()
421            .any(|v| v.get("ok").and_then(|b| b.as_bool()).unwrap_or(false))
422    }
423
424    /// Did any loaded plugin contribute tools outside the v1 `tool` hook
425    /// (v2 `tool.transform`)? Observability only; a v2 plugin may add more
426    /// tools later, so this must not gate `tools()`.
427    pub fn has_tools(&self) -> bool {
428        self.0.statuses.lock().values().any(|v| {
429            v.get("has_tools")
430                .and_then(|b| b.as_bool())
431                .unwrap_or(false)
432        })
433    }
434
435    pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
436        self.request_with_timeout(method, params, Some(RPC_TIMEOUT))
437            .await
438    }
439
440    pub async fn request_with_timeout(
441        &self,
442        method: &str,
443        params: Value,
444        timeout: Option<std::time::Duration>,
445    ) -> Result<Value> {
446        if !self.is_alive() {
447            anyhow::bail!("plugin host is down ({method}); a respawn is required");
448        }
449        let id = self
450            .0
451            .next_id
452            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
453        let (tx, rx) = oneshot::channel();
454        self.0.pending.lock().insert(id, Pending { tx });
455        let _guard = PendingGuard::new(Arc::clone(&self.0.pending), id);
456        let msg = json!({"id": id, "method": method, "params": params});
457        let mut line = msg.to_string();
458        line.push('\n');
459        // The BUDGET COVERS THE WRITE (review C2). Previously only the response
460        // wait was timed, so a host that stopped draining blocked every caller
461        // on the stdin mutex with no timer. A timeout now also poisons the
462        // generation: a partially written frame makes the protocol untrustworthy.
463        let exchange = async {
464            {
465                let mut stdin = self.0.stdin.lock().await;
466                stdin.write_all(line.as_bytes()).await?;
467                stdin.flush().await?;
468            }
469            match rx.await {
470                Ok(res) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
471                Err(_) => Err(anyhow!("plugin host dropped response for {method}")),
472            }
473        };
474        match timeout {
475            None => exchange
476                .await
477                .map_err(|e| e.context("plugin host stdin write")),
478            Some(d) => match tokio::time::timeout(d, exchange).await {
479                Ok(res) => res,
480                Err(_) => {
481                    self.0
482                        .poisoned
483                        .store(true, std::sync::atomic::Ordering::Release);
484                    self.0
485                        .alive
486                        .store(false, std::sync::atomic::Ordering::Release);
487                    ocserve_metrics::labeled_counter(
488                        "ocserve_plugin_hook_timeout_total",
489                        &format!("hook=\"{method}\""),
490                        1,
491                    );
492                    Err(anyhow!(
493                        "plugin host {method} timed out after {}ms (runaway hook?)",
494                        d.as_millis()
495                    ))
496                }
497            },
498        }
499    }
500}
501
502impl Handle {
503    pub async fn trigger_bounded(
504        &self,
505        name: &str,
506        input: Value,
507        mut output: Value,
508        budget: Option<std::time::Duration>,
509    ) -> Result<Value> {
510        let res = self
511            .request_with_timeout(
512                "trigger",
513                json!({"name": name, "input": input, "output": output}),
514                budget,
515            )
516            .await?;
517        if res.is_object() {
518            output = res;
519        }
520        Ok(output)
521    }
522
523    pub async fn trigger_v2_bounded(
524        &self,
525        domain: &str,
526        name: &str,
527        input: Value,
528        budget: Option<std::time::Duration>,
529    ) -> Result<Value> {
530        self.request_with_timeout(
531            "trigger_v2",
532            json!({"domain": domain, "name": name, "input": input}),
533            budget,
534        )
535        .await
536    }
537
538    pub async fn emit_event_bounded(
539        &self,
540        event: Value,
541        budget: Option<std::time::Duration>,
542    ) -> Result<Value> {
543        self.request_with_timeout("event", json!({"event": event}), budget)
544            .await
545    }
546}
547
548/// Per-hook budget. Upstream has NO hook timeout (`Effect.promise(...)` awaits
549/// forever); any bound is our safety divergence, recorded as D-HOOK-TIMEOUT.
550/// Defaults come from measured maxima on a real install (27 prompts):
551/// `v2.session.context` 15.3 s, `tool.execute.after` 30.0 s,
552/// `system.transform` 5.4 s. `OCSERVE_HOOK_TIMEOUT_MS=0` restores parity
553/// (unbounded) for an operator who needs it.
554pub fn hook_budget(hook: &str) -> Option<std::time::Duration> {
555    match std::env::var("OCSERVE_HOOK_TIMEOUT_MS")
556        .ok()
557        .and_then(|v| v.parse::<u64>().ok())
558    {
559        Some(0) => None,
560        Some(ms) => Some(std::time::Duration::from_millis(ms)),
561        None => Some(std::time::Duration::from_secs(
562            if hook.contains("tool.execute") {
563                180
564            } else if hook.contains("transform")
565                || hook.contains("context")
566                // `experimental.session.compacting` does NOT contain
567                // "compaction" (review M1: a substring miss gave it 30 s).
568                || hook.contains("compact")
569            {
570                60
571            } else {
572                30
573            },
574        )),
575    }
576}
577
578impl Handle {
579    /// v2 RPC dispatch (see `Sidecar::rpc_call`, which delegates here).
580    pub async fn rpc_call(&self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
581        self.request(
582            "rpc_call",
583            json!({"rpcID": rpc_id, "method": method, "input": input}),
584        )
585        .await
586    }
587
588    /// v2 plugin inventory (real — id/dialect per loaded v2 plugin + the
589    /// registered RPC ids). Powers `/api/plugin` without fabricating a list.
590    pub async fn v2_inventory(&self) -> Result<Value> {
591        self.request("v2_inventory", json!({})).await
592    }
593
594    /// Pulled v2 command/skill transform (see `Sidecar::transform_commands`).
595    pub async fn transform_commands(
596        &self,
597        commands: Vec<Value>,
598    ) -> Result<(Vec<Value>, Vec<Value>)> {
599        let r = self
600            .request("v2_transform_commands", json!({ "commands": commands }))
601            .await?;
602        let out = r["commands"]
603            .as_array()
604            .cloned()
605            .unwrap_or_default()
606            .into_iter()
607            .collect();
608        let failures = r["failures"].as_array().cloned().unwrap_or_default();
609        Ok((out, failures))
610    }
611}
612
613impl Handle {
614    /// Plugin-declared tools (v1 `hooks.tool`), with JSON Schema generated in
615    /// the plugin's own runtime. Empty when no plugin registers one, so the
616    /// provider `tools` array is byte-identical for everyone else.
617    ///
618    /// A failed fetch returns the LAST KNOWN list rather than an empty one
619    /// (review M6): dropping tools mid-session made a later call to one fall
620    /// through to "unknown tool", a worse failure than a stale schema.
621    pub async fn tools(&self) -> Result<Vec<Value>> {
622        // Any loaded plugin may advertise tools — v1 via the `tool` hook, v2
623        // via `tool.transform`, which a launcher can call LATER (Paseo installs
624        // its `paseo_*` tools on `rpc.bind`, after load). A load-time tool
625        // count would therefore short-circuit exactly the tools that matter.
626        // The RPC only happens when a plugin host exists at all (most installs
627        // have none; `tools()` then returns before this).
628        if !self.any_loaded() {
629            return Ok(Vec::new());
630        }
631        match self.request("tools", json!({})).await {
632            Ok(res) => {
633                let list = res.as_array().cloned().unwrap_or_default();
634                *self.0.last_tools.lock() = Some(list.clone());
635                Ok(list)
636            }
637            Err(e) => {
638                if let Some(cached) = self.0.last_tools.lock().clone() {
639                    tracing::warn!("plugin tools: {e:#} — serving the last known list");
640                    return Ok(cached);
641                }
642                Err(e)
643            }
644        }
645    }
646
647    /// Execute one plugin tool. `ctx` carries {sessionID, messageID, agent,
648    /// directory}. The permission gate ran already for the call as a whole.
649    pub async fn execute_tool(&self, name: &str, input: Value, ctx: Value) -> Result<Value> {
650        self.request_with_timeout(
651            "tool_execute",
652            json!({"name": name, "input": input, "ctx": ctx}),
653            Some(std::time::Duration::from_secs(300)),
654        )
655        .await
656    }
657}
658
659/// Sidecar owner: one Node process, NDJSON request/response, reader task.
660pub struct Sidecar {
661    inner: Arc<Inner>,
662    child: Child,
663    /// server/directory context for loads (kept for future reloads)
664    server: (String, String),
665    /// spawn identity for respawn-after-death
666    args: SpawnArgs,
667    /// successful loads (spec, entry, input, options) — replayed on respawn
668    /// (entries stored RAW; load_raw re-normalizes on replay — D1-PLAN).
669    /// `options` is the v1 `[spec, options]` tuple's second element (Null when
670    /// the plain-string form was used) — passed to the server factory.
671    loads: Vec<(String, PathBuf, Value, Value)>,
672    /// normalization output root (`data/normalized`); None = skip (tests,
673    /// any sidecar without it — existing behavior untouched, D1-PLAN)
674    normalize_root: Option<PathBuf>,
675    /// spawn time for the L1 recycle min-uptime guard (SRE §5) — fresh on
676    /// every (re)spawn, so a recycled sidecar can't be recycled again until
677    /// the guard window passes.
678    started_at: std::time::Instant,
679    /// L1 recycle marker: set when WE killed the child on purpose; the next
680    /// ensure_alive must log that as INFO (planned), not ERROR (crash) —
681    /// an intentional action must never read as a failure in the logs.
682    recycled: bool,
683}
684
685/// Plugin-host runtime: Bun preferred (upstream runs plugins under Bun; real
686/// `bun:sqlite`, TS plugins load, lower RSS floor), Node fallback.
687/// `OCSERVE_PLUGIN_RUNTIME=node|bun` forces one (lab A/B control).
688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
689pub enum PluginRuntime {
690    Bun,
691    Node,
692}
693
694impl PluginRuntime {
695    pub fn program(self) -> &'static str {
696        match self {
697            PluginRuntime::Bun => "bun",
698            PluginRuntime::Node => "node",
699        }
700    }
701}
702
703/// Resolve an executable on PATH plus `~/.bun/bin` (the common user-local
704/// bun install location — systemd units do not see shell PATH extras).
705pub(crate) fn which(prog: &str) -> Option<PathBuf> {
706    // Windows resolves executables by suffix; `Path::join("bun")` never finds
707    // `bun.exe` (PLATFORM.md §1.2). The suffix lives in one place — ocserve-core
708    // — so the plugin host, the MCP client and the tools cannot drift.
709    let name = ocserve_store::platform::exe(prog);
710    if let Ok(path) = std::env::var("PATH") {
711        for dir in std::env::split_paths(&path) {
712            let cand = dir.join(&name);
713            if ocserve_store::platform::is_executable_file(&cand) {
714                return Some(cand);
715            }
716        }
717    }
718    for key in ["OCSERVE_HOME", "HOME", "USERPROFILE"] {
719        let Some(home) = std::env::var_os(key).filter(|v| !v.is_empty()) else {
720            continue;
721        };
722        let cand = Path::new(&home).join(".bun/bin").join(&name);
723        if ocserve_store::platform::is_executable_file(&cand) {
724            return Some(cand);
725        }
726    }
727    None
728}
729
730pub fn plugin_runtime() -> PluginRuntime {
731    match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
732        Ok("node") => return PluginRuntime::Node,
733        Ok("bun") => return PluginRuntime::Bun,
734        _ => {}
735    }
736    if which("bun").is_some() {
737        PluginRuntime::Bun
738    } else {
739        PluginRuntime::Node
740    }
741}
742
743#[derive(Clone)]
744struct SpawnArgs {
745    host_path: PathBuf,
746    server_url: String,
747    directory: String,
748}
749
750impl Sidecar {
751    pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
752        // A3 (OOM-resilience): same wrapper as ocserve-mcp — the plugin host
753        // dies first on memcg pressure (ensure_alive respawns it) instead
754        // of the main service.
755        let runtime = crate::plugin_runtime();
756        // absolute path (systemd PATH may lack ~/.bun/bin); fall back to the
757        // bare name so a PATH-only environment still resolves
758        let program = which(runtime.program())
759            .map(|p| p.to_string_lossy().into_owned())
760            .unwrap_or_else(|| runtime.program().to_string());
761        // Containment (SRE §5.2): the child moves itself into kids/plugin and
762        // raises its oom_score_adj before exec, so a memcg kill takes the
763        // sidecar (ensure_alive respawns it) instead of the server.
764        let shape = ocserve_store::cgroup::contained(&program, "plugin");
765        let mut cmd = Command::new(&shape.program);
766        cmd.args(&shape.prefix);
767        // `ctx.app.version` must match the running server, not a literal in the
768        // shim (it said 0.3.1 through 0.6.x). Env keeps the host script
769        // version-agnostic.
770        cmd.env("OCSERVE_VERSION", env!("CARGO_PKG_VERSION"));
771        match &shape.cgroup {
772            Some(p) => {
773                cmd.env(ocserve_store::cgroup::ENV, p);
774            }
775            None => {
776                cmd.env_remove(ocserve_store::cgroup::ENV);
777            }
778        }
779        match runtime {
780            // Bun (upstream's own plugin runtime): real bun:sqlite + TS
781            // plugins load; `--smol` trades GC frequency for a lower RSS
782            // floor. No V8 --max-old-space knobs exist here.
783            PluginRuntime::Bun => {
784                cmd.arg("--smol");
785            }
786            // Node (fallback when bun is absent): V8 heap cap (env-tunable).
787            // Default raised64→128 after the LIVE battery (2026-10-03): with
788            // the real plugin set the sidecar OOM-killed at64 (observed boot
789            // death → hooks broken-piped until restart). Measured
790            // 64/128/192/256: RSS flat ~145-148MB either way (native
791            // dominates; heap cap only binds when heap actually grows).
792            PluginRuntime::Node => {
793                cmd.arg(format!(
794                    "--max-old-space-size={}",
795                    std::env::var("OCSERVE_PLUGIN_HEAP_MB")
796                        .ok()
797                        .and_then(|v| v.parse().ok())
798                        .unwrap_or(128)
799                ));
800                cmd.arg("--max-semi-space-size=2");
801            }
802        }
803        cmd.arg(host_path)
804            .stdin(std::process::Stdio::piped())
805            .stdout(std::process::Stdio::piped())
806            .stderr(std::process::Stdio::inherit())
807            .kill_on_drop(true);
808        let mut child = cmd
809            .spawn()
810            .with_context(|| format!("spawn {} plugin host", runtime.program()))?;
811        let stdin = child.stdin.take().context("host stdin")?;
812        let stdout = child.stdout.take().context("host stdout")?;
813        let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
814        let pending_task = Arc::clone(&pending);
815        let alive = Arc::new(std::sync::atomic::AtomicBool::new(true));
816        let alive_task = Arc::clone(&alive);
817        let poisoned = Arc::new(std::sync::atomic::AtomicBool::new(false));
818        let poisoned_task = Arc::clone(&poisoned);
819        tokio::spawn(async move {
820            // Bounded line reads: a plugin that prints a giant line (no newline)
821            // would otherwise grow `line` unbounded (host.mjs stdout is reserved
822            // for RPC, but a runaway plugin can still emit garbage). Cap at the
823            // RPC line budget; a longer line is discarded.
824            const MAX_HOST_LINE: usize = 8 * 1024 * 1024;
825            let mut reader = BufReader::new(stdout);
826            let mut line = String::new();
827            loop {
828                line.clear();
829                use tokio::io::AsyncBufReadExt as _;
830                let n = {
831                    let mut limited =
832                        tokio::io::AsyncReadExt::take(&mut reader, MAX_HOST_LINE as u64 + 1);
833                    limited.read_line(&mut line).await
834                };
835                match n {
836                    Ok(0) | Err(_) => break,
837                    // oversized: the rest of the line is unreadable framing —
838                    // stop; in-flight RPCs fail on timeout (never hang the pump).
839                    Ok(_) if line.len() > MAX_HOST_LINE => {
840                        // Framing is lost. Mark the generation dead AND poisoned
841                        // so the owner replaces the child instead of leaving a
842                        // live-but-deaf host that times out every request
843                        // (review C1/M-6).
844                        tracing::warn!("plugin host: oversized line — child marked for respawn");
845                        poisoned_task.store(true, std::sync::atomic::Ordering::Release);
846                        break;
847                    }
848                    Ok(_) => {}
849                }
850                let trimmed = line.trim();
851                if trimmed.is_empty() {
852                    continue;
853                }
854                match serde_json::from_str::<Value>(trimmed) {
855                    Ok(v) => {
856                        if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
857                            let result = match v.get("error") {
858                                Some(e) if !e.is_null() => {
859                                    Err(e["message"].as_str().unwrap_or("host error").to_string())
860                                }
861                                _ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
862                            };
863                            if let Some(p) = pending_task.lock().remove(&id) {
864                                let _ = p.tx.send(result);
865                            }
866                        } else if v.get("event").and_then(|e| e.as_str()) == Some("plugin_error") {
867                            // Per-plugin internal failure (the class that hid a
868                            // configured plugin for weeks: the plugin caught its
869                            // own TypeError and returned the input unchanged, so
870                            // Rust saw Ok). Counted by name so silence is visible.
871                            ocserve_metrics::labeled_counter(
872                                "ocserve_plugin_internal_error_total",
873                                &format!(
874                                    "plugin=\"{}\",hook=\"{}\"",
875                                    v["plugin"].as_str().unwrap_or("?"),
876                                    v["hook"].as_str().unwrap_or("?")
877                                ),
878                                1,
879                            );
880                            tracing::warn!(
881                                "plugin internal error: {} {}: {}",
882                                v["plugin"].as_str().unwrap_or("?"),
883                                v["hook"].as_str().unwrap_or("?"),
884                                v["error"].as_str().unwrap_or("?")
885                            );
886                        }
887                        // no id → informational; host routes plugin chatter to stderr
888                    }
889                    Err(_) => {
890                        let head: String = trimmed.chars().take(120).collect();
891                        tracing::warn!("plugin host: unparsable line: {head}");
892                    }
893                }
894            }
895            // host death (or reader death): fail everything in flight (fail
896            // fast, AGENTS §2.4) and tell every handle this generation is gone.
897            alive_task.store(false, std::sync::atomic::Ordering::Release);
898            for (_, p) in pending_task.lock().drain() {
899                let _ = p.tx.send(Err("plugin host exited".into()));
900            }
901            ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 0);
902        });
903        ocserve_metrics::gauge("ocserve_plugin_sidecar_up", 1);
904        Ok(Self {
905            inner: Arc::new(Inner {
906                stdin: tokio::sync::Mutex::new(stdin),
907                pending,
908                next_id: std::sync::atomic::AtomicI64::new(1),
909                statuses: parking_lot::Mutex::new(HashMap::new()),
910                alive,
911                poisoned,
912                last_tools: parking_lot::Mutex::new(None),
913            }),
914            child,
915            server: (server_url.to_string(), directory.to_string()),
916            args: SpawnArgs {
917                host_path: host_path.to_path_buf(),
918                server_url: server_url.to_string(),
919                directory: directory.to_string(),
920            },
921            loads: Vec::new(),
922            normalize_root: None,
923            started_at: std::time::Instant::now(),
924            recycled: false,
925        })
926    }
927
928    /// RPCs currently in flight (the L1 recycle idle gate — a hook must
929    /// never be interrupted mid-call).
930    pub fn in_flight(&self) -> usize {
931        self.inner.pending.lock().len()
932    }
933
934    /// Seconds since this sidecar instance was spawned (respawns reset it).
935    pub fn uptime(&self) -> std::time::Duration {
936        self.started_at.elapsed()
937    }
938
939    /// L1 graceful recycle (SRE §5): kill the sidecar child while idle.
940    /// State is disk-backed (context.db / pins) and `loads` is kept, so the
941    /// next `ensure_alive` respawns + replays hooks (warm-hash normalize is
942    /// a no-op). SIGKILL is deliberate: the host has no shutdown protocol
943    /// and nothing in it needs flushing. Returns false if already dead.
944    pub fn recycle_child(&mut self) -> bool {
945        if self.child.try_wait().ok().flatten().is_some() {
946            return false;
947        }
948        let _ = self.child.start_kill();
949        // Do NOT clear `statuses`: the loads are still known and will be
950        // replayed on respawn. Clearing them made `registers()` false, so every
951        // hook short-circuited to "no plugin" forever — the 2026-10-23 review
952        // found a recycle silently disabled every plugin (the Magic Context
953        // class again). The generation flag says "needs respawn"; the hook
954        // path now acts on it.
955        self.inner
956            .alive
957            .store(false, std::sync::atomic::Ordering::Release);
958        self.recycled = true;
959        true
960    }
961
962    /// Enable normalization for this sidecar (set once at boot; carried to
963    /// respawns by `ensure_alive`). None/never-set = raw loads (today's
964    /// behavior — all existing tests stay on this path).
965    pub fn set_normalize_root(&mut self, root: PathBuf) {
966        self.normalize_root = Some(root);
967    }
968
969    /// Respawn after unexpected death (V8 OOM / crash) and replay every
970    /// previously loaded plugin. Without this a dead sidecar leaves ALL
971    /// hooks broken-piped until service restart (live battery finding
972    /// 2026-10-03: boot-time heap OOM, fail-open hid it in the prompt path).
973    pub async fn ensure_alive(&mut self) -> Result<()> {
974        // The reader can die while the child is alive (oversized line, lost
975        // framing). A live-but-deaf host times out every request, so treat
976        // poison as death and replace the whole generation.
977        if self
978            .inner
979            .poisoned
980            .load(std::sync::atomic::Ordering::Acquire)
981        {
982            let _ = self.child.start_kill();
983            self.inner
984                .alive
985                .store(false, std::sync::atomic::Ordering::Release);
986        } else if self.inner.alive.load(std::sync::atomic::Ordering::Acquire)
987            && let Ok(None) = self.child.try_wait()
988        {
989            return Ok(());
990        }
991        ocserve_metrics::labeled_counter(
992            "ocserve_plugin_sidecar_respawn_total",
993            if self.recycled {
994                "reason=\"recycle\""
995            } else {
996                "reason=\"exit\""
997            },
998            1,
999        );
1000        let status = self.child.try_wait().ok().flatten();
1001        if std::mem::take(&mut self.recycled) {
1002            tracing::info!(
1003                "plugin sidecar recycled (L1, was {status:?}) — respawning + replaying hooks"
1004            );
1005        } else if let Some(status) = status {
1006            tracing::error!("plugin sidecar exited ({status}) — respawning");
1007        } else {
1008            tracing::warn!("plugin sidecar unresponsive — replacing the host");
1009        }
1010        let args = self.args.clone();
1011        let loads = std::mem::take(&mut self.loads);
1012        // Spawn failure must NOT lose `loads`: `self` is only replaced on
1013        // success, so restore the taken entries and surface the error. Without
1014        // this the plugin set is silently empty after a failed respawn — hooks
1015        // never replay and `in_flight()` stays zero (statuses stale).
1016        let mut fresh =
1017            match Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await {
1018                Ok(f) => f,
1019                Err(e) => {
1020                    self.loads = loads;
1021                    tracing::error!("plugin sidecar respawn failed: {e:#} — plugin set preserved");
1022                    return Err(e);
1023                }
1024            };
1025        // D1-PLAN: replay must normalize too (warm no-op; rebuilds if outputs
1026        // were wiped mid-run — A1 stores raw, rebuilds here AND at next boot).
1027        fresh.normalize_root = self.normalize_root.clone();
1028        for (spec, entry, input, options) in &loads {
1029            if let Err(e) = fresh.load_raw(spec, entry, input, options).await {
1030                tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
1031            }
1032        }
1033        *self = fresh;
1034        Ok(())
1035    }
1036
1037    /// Child pid (test/diag: force-kill to prove respawn).
1038    pub fn child_pid(&self) -> u32 {
1039        self.child.id().unwrap_or(0)
1040    }
1041
1042    pub fn handle(&self) -> Handle {
1043        Handle(Arc::clone(&self.inner))
1044    }
1045
1046    pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
1047        self.ensure_alive().await?;
1048        self.handle().request(method, params).await
1049    }
1050
1051    /// Request with an explicit budget; `None` keeps the historical RPC bound.
1052    pub async fn request_bounded(
1053        &mut self,
1054        method: &str,
1055        params: Value,
1056        timeout: Option<std::time::Duration>,
1057    ) -> Result<Value> {
1058        self.ensure_alive().await?;
1059        self.handle()
1060            .request_with_timeout(method, params, timeout)
1061            .await
1062    }
1063
1064    /// Load one plugin (v1 server-factory extraction happens host-side).
1065    /// `options` is the v1 `[spec, options]` tuple's second element (pass
1066    /// `Value::Null` for the plain-string form) — delivered to the factory.
1067    pub async fn load(
1068        &mut self,
1069        spec: &str,
1070        entry: &Path,
1071        input: &Value,
1072        options: &Value,
1073    ) -> Result<Vec<String>> {
1074        self.ensure_alive().await?;
1075        self.load_raw(spec, entry, input, options).await
1076    }
1077
1078    /// Unguarded load (respawn replay only — fresh child is alive).
1079    async fn load_raw(
1080        &mut self,
1081        spec: &str,
1082        entry: &Path,
1083        input: &Value,
1084        options: &Value,
1085    ) -> Result<Vec<String>> {
1086        // D1: normalize for the RPC (CPU on spawn_blocking — A2 class); the
1087        // RAW entry is what gets recorded for respawn replay (A1).
1088        let root = self.normalize_root.clone();
1089        let raw = entry.to_path_buf();
1090        let raw_for_spawn = raw.clone();
1091        let (load_path, outcome) = tokio::task::spawn_blocking(move || {
1092            crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw_for_spawn)
1093        })
1094        .await
1095        .map_err(|e| anyhow!("normalize task: {e}"))?;
1096        ocserve_metrics::labeled_counter(
1097            "ocserve_plugin_normalize_total",
1098            &format!("result=\"{}\"", outcome.label()),
1099            1,
1100        );
1101        match &outcome {
1102            crate::normalize::Outcome::Built {
1103                path,
1104                ms,
1105                beside,
1106                rss_before_kb,
1107                rss_after_kb,
1108            } => tracing::info!(
1109                "plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
1110                path.display(),
1111                if *beside { "beside-entry" } else { "data-dir" }
1112            ),
1113            crate::normalize::Outcome::Fallback { err, .. } => {
1114                tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
1115            }
1116            _ => {}
1117        }
1118        // server/directory context defaults from spawn (input may omit them)
1119        let mut input = input.clone();
1120        if input
1121            .get("serverUrl")
1122            .and_then(|v| v.as_str())
1123            .unwrap_or("")
1124            .is_empty()
1125        {
1126            input["serverUrl"] = json!(self.server.0);
1127        }
1128        if input
1129            .get("directory")
1130            .and_then(|v| v.as_str())
1131            .unwrap_or("")
1132            .is_empty()
1133        {
1134            input["directory"] = json!(self.server.1);
1135        }
1136        let params = json!({
1137            "spec": spec,
1138            "entry": load_path.to_string_lossy(),
1139            // Where the plugin ACTUALLY lives. Normalized bundles are emitted
1140            // outside the plugin's tree, so `createRequire(entry)` cannot
1141            // resolve its `zod` from there — and a tool schema that cannot be
1142            // converted is an invalid JSON Schema the provider 400s.
1143            "origin": raw.to_string_lossy(),
1144            "input": input,
1145            "options": options,
1146        });
1147        let res = self.handle().request("load", params).await?;
1148        let hooks: Vec<String> = res["hooks"]
1149            .as_array()
1150            .map(|a| {
1151                a.iter()
1152                    .filter_map(|h| h.as_str().map(String::from))
1153                    .collect()
1154            })
1155            .unwrap_or_default();
1156        self.inner.statuses.lock().insert(
1157            spec.to_string(),
1158            json!({
1159                "ok": true,
1160                "hooks": hooks,
1161                "id": res["id"],
1162                // v2 tools are registered through `tool.transform`, not a hook
1163                // name; this flag is what lets `tools()` skip the RPC when
1164                // nobody advertises one (v1 keeps the `tool` hook).
1165                "has_tools": res["has_tools"].as_bool().unwrap_or(false),
1166            }),
1167        );
1168        self.loads.push((
1169            spec.to_string(),
1170            entry.to_path_buf(),
1171            input,
1172            options.clone(),
1173        ));
1174        Ok(hooks)
1175    }
1176
1177    /// Was this spec already attempted (loaded OR failed)? Failures stay
1178    /// recorded so a launcher polling `/api/plugin` every 50 ms cannot re-run a
1179    /// crashing plugin thousands of times.
1180    pub fn attempted(&self, spec: &str) -> bool {
1181        self.inner.statuses.lock().contains_key(spec)
1182    }
1183
1184    /// Load one auto-discovered plugin on demand (hot pickup for a launcher
1185    /// that provisions `<config_dir>/plugins/…` after the server booted, as
1186    /// Paseo does). Idempotent; a resolve/load failure is recorded as a failed
1187    /// status instead of being retried on every poll.
1188    pub async fn load_discovered(&mut self, spec: &str, home: &Path) -> Result<Vec<String>> {
1189        if self.attempted(spec) {
1190            return Ok(Vec::new());
1191        }
1192        let entry = match resolve_entry(spec, home) {
1193            Ok(entry) => entry,
1194            Err(e) => {
1195                self.note_failure(spec, &e);
1196                return Err(e);
1197            }
1198        };
1199        self.ensure_alive().await?;
1200        let input = json!({
1201            "directory": self.server.1,
1202            "projectID": "global",
1203            "worktree": "/",
1204            "serverUrl": self.server.0,
1205        });
1206        match self.load(spec, &entry, &input, &json!({})).await {
1207            Ok(hooks) => Ok(hooks),
1208            Err(e) => {
1209                self.note_failure(spec, &e);
1210                Err(e)
1211            }
1212        }
1213    }
1214
1215    /// Record a failed attempt so `/api/plugin` reports `failed` instead of
1216    /// pretending the plugin is absent, and the discovery poll does not retry
1217    /// forever.
1218    pub fn note_failure(&self, spec: &str, e: &anyhow::Error) {
1219        self.inner.statuses.lock().insert(
1220            spec.to_string(),
1221            json!({"ok": false, "hooks": [], "error": format!("{e:#}")}),
1222        );
1223    }
1224
1225    /// v1 trigger semantics: sequential hooks mutate `output` in place.
1226    pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
1227        let params = json!({"name": name, "input": input, "output": output});
1228        let res = self.request("trigger", params).await?;
1229        if res.is_object() {
1230            output = res;
1231        }
1232        Ok(output)
1233    }
1234
1235    /// v1 event delivery (plugin/index.ts:255-259): per-plugin
1236    /// `hooks["event"]({event})`. Returns host delivery count.
1237    pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
1238        self.request("event", json!({"event": event})).await
1239    }
1240
1241    /// v2 domain-hook dispatch (Phase 3): v2 hooks mutate the event object in
1242    /// place (like v1's output), so this returns `{output, matched}`. `matched`
1243    /// = 0 means no v2 plugin installed this hook (caller skips mutation).
1244    pub async fn trigger_v2(&mut self, domain: &str, name: &str, input: Value) -> Result<Value> {
1245        self.request(
1246            "trigger_v2",
1247            json!({"domain": domain, "name": name, "input": input}),
1248        )
1249        .await
1250    }
1251
1252    /// v2 RPC dispatch (Phase 3): `{rpcID, method, input}` →
1253    /// `{output}` (success) or `{error:{type,message}}` (unavailable /
1254    /// method_not_found / handler_error).
1255    pub async fn rpc_call(&mut self, rpc_id: &str, method: &str, input: Value) -> Result<Value> {
1256        self.ensure_alive().await?;
1257        self.handle().rpc_call(rpc_id, method, input).await
1258    }
1259
1260    /// v2 plugin inventory (real — id/dialect per loaded v2 plugin + the
1261    /// registered RPC ids). Powers `/api/plugin` without fabricating a list.
1262    pub async fn v2_inventory(&mut self) -> Result<Value> {
1263        self.ensure_alive().await?;
1264        self.handle().v2_inventory().await
1265    }
1266
1267    /// Run every registered v2 `command.transform` / `skill.transform` over
1268    /// `commands` and return the edited list.
1269    ///
1270    /// PULLED by the caller on config reload (never pushed by the plugin), so
1271    /// a payload can only ever serve a list this call actually returned — the
1272    /// property that kills the push-race where a stale list is served after a
1273    /// reconcile that never asked. Upstream semantics mirrored from
1274    /// `State.create` (core/state.ts:172-194): transforms start from the
1275    /// pristine list each call and a throwing transform is reported, not fatal.
1276    ///
1277    /// Returns `(commands, failures)`; a sidecar error propagates so the
1278    /// caller can fall back to the untransformed list rather than serve an
1279    /// empty command surface.
1280    pub async fn transform_commands(
1281        &mut self,
1282        commands: Vec<Value>,
1283    ) -> Result<(Vec<Value>, Vec<Value>)> {
1284        self.ensure_alive().await?;
1285        self.handle().transform_commands(commands).await
1286    }
1287
1288    pub async fn config(&mut self, cfg: Value) -> Result<Value> {
1289        self.request("config", json!({"config": cfg})).await
1290    }
1291
1292    pub fn statuses(&self) -> Value {
1293        let mut out = serde_json::Map::new();
1294        for (spec, v) in self.inner.statuses.lock().iter() {
1295            out.insert(spec.clone(), v.clone());
1296        }
1297        Value::Object(out)
1298    }
1299
1300    pub async fn shutdown(&mut self) {
1301        let _ = self.request("dispose", json!({})).await;
1302        let _ = self.child.start_kill();
1303    }
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308    use super::*;
1309
1310    #[test]
1311    fn strip_version_cases() {
1312        assert_eq!(strip_version("context-mode"), "context-mode");
1313        assert_eq!(strip_version("context-mode@latest"), "context-mode");
1314        assert_eq!(
1315            strip_version("@cortexkit/opencode-magic-context@latest"),
1316            "@cortexkit/opencode-magic-context"
1317        );
1318        assert_eq!(
1319            strip_version("@iam-brain/opencode-codex-auth@latest"),
1320            "@iam-brain/opencode-codex-auth"
1321        );
1322    }
1323
1324    #[test]
1325    fn entry_from_package_shapes() {
1326        let dir = tempfile::tempdir().unwrap();
1327        // exports["."] string
1328        std::fs::write(
1329            dir.path().join("package.json"),
1330            r#"{"exports": {".": "./dist/index.js"}}"#,
1331        )
1332        .unwrap();
1333        std::fs::create_dir(dir.path().join("dist")).unwrap();
1334        std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
1335        let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
1336            .expect("exports dot");
1337        assert!(e.ends_with("dist/index.js"));
1338        // main fallback
1339        std::fs::write(
1340            dir.path().join("package.json"),
1341            r#"{"main": "./lib/main.js"}"#,
1342        )
1343        .unwrap();
1344        std::fs::create_dir(dir.path().join("lib")).unwrap();
1345        std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
1346        let e =
1347            entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
1348        assert!(e.ends_with("lib/main.js"));
1349    }
1350
1351    #[test]
1352    fn resolve_entry_accepts_file_urls_and_directories() {
1353        let dir = tempfile::tempdir().unwrap();
1354        // file:// URL (what launchers inject via OPENCODE_CONFIG_CONTENT)
1355        let file = dir.path().join("bridge.mjs");
1356        std::fs::write(&file, "//").unwrap();
1357        let url = format!("file://{}", file.display());
1358        assert_eq!(resolve_entry(&url, dir.path()).unwrap(), file);
1359        // percent-encoded URL (a temp path with a space must still resolve)
1360        let spaced = dir.path().join("bridge copy.mjs");
1361        std::fs::write(&spaced, "//").unwrap();
1362        let encoded = format!("file://{}", spaced.display()).replace(' ', "%20");
1363        assert_eq!(resolve_entry(&encoded, dir.path()).unwrap(), spaced);
1364        // directory with a v2-style package manifest: the `./server` export is
1365        // the entry, even when no conventional index file exists (upstream
1366        // resolvePathPluginTarget reads exports["./server"], then main).
1367        let pkg = dir.path().join("managed-bridge");
1368        std::fs::create_dir_all(pkg.join("dist")).unwrap();
1369        std::fs::write(
1370            pkg.join("package.json"),
1371            r#"{"name":"paseo-managed-bridge","type":"module","exports":{"./server":"./dist/main.mjs"}}"#,
1372        )
1373        .unwrap();
1374        std::fs::write(pkg.join("dist/main.mjs"), "//").unwrap();
1375        assert_eq!(
1376            resolve_entry(pkg.to_str().unwrap(), dir.path()).unwrap(),
1377            pkg.join("dist/main.mjs")
1378        );
1379        // no package.json exports → conventional index.ts (upstream order)
1380        let plain = dir.path().join("plain");
1381        std::fs::create_dir_all(&plain).unwrap();
1382        std::fs::write(plain.join("index.ts"), "//").unwrap();
1383        assert_eq!(
1384            resolve_entry(plain.to_str().unwrap(), dir.path()).unwrap(),
1385            plain.join("index.ts")
1386        );
1387        // directory without any entrypoint is a named error, never a dir import
1388        let empty = dir.path().join("empty");
1389        std::fs::create_dir_all(&empty).unwrap();
1390        let err = resolve_entry(empty.to_str().unwrap(), dir.path()).unwrap_err();
1391        assert!(err.to_string().contains("no entrypoint"), "{err}");
1392    }
1393
1394    #[test]
1395    fn resolve_entry_negative_control_still_rejects_unknown_packages() {
1396        let dir = tempfile::tempdir().unwrap();
1397        let err = resolve_entry("no-such-plugin-package", dir.path()).unwrap_err();
1398        assert!(err.to_string().contains("plugin target not found"), "{err}");
1399    }
1400
1401    #[test]
1402    fn discover_plugin_specs_matches_upstream_layout() {
1403        let dir = tempfile::tempdir().unwrap();
1404        std::fs::create_dir_all(dir.path().join("plugin")).unwrap();
1405        std::fs::create_dir_all(dir.path().join("plugins/managed-bridge")).unwrap();
1406        std::fs::write(dir.path().join("plugin/a.js"), "//").unwrap();
1407        std::fs::write(dir.path().join("plugin/b.mjs"), "//").unwrap(); // upstream: not discovered
1408        std::fs::write(dir.path().join("plugins/readme.txt"), "x").unwrap();
1409        let got = discover_plugin_specs(dir.path());
1410        assert!(
1411            got.iter().any(|s| s.ends_with("/plugin/a.js")),
1412            "a .js source file is discovered: {got:?}"
1413        );
1414        assert!(
1415            got.iter().any(|s| s.ends_with("/plugins/managed-bridge")),
1416            "a package DIRECTORY is discovered: {got:?}"
1417        );
1418        assert!(
1419            !got.iter().any(|s| s.ends_with("b.mjs")),
1420            "upstream does not discover .mjs by glob: {got:?}"
1421        );
1422        assert!(!got.iter().any(|s| s.ends_with("readme.txt")));
1423        // Another volume of entries must not panic or duplicate; the cap is
1424        // enforced by construction (bounded scan).
1425        assert_eq!(got.len(), 2, "{got:?}");
1426    }
1427
1428    /// v2 tools: `ctx.tool.transform(editor => editor.add(...))` must actually
1429    /// install the tool (Paseo's bridge depends on it), advertise its JSON
1430    /// Schema, and dispatch `execute(input, {sessionID})`.
1431    #[tokio::test]
1432    async fn v2_tool_transform_registers_and_executes() -> anyhow::Result<()> {
1433        if !runtime_available() {
1434            panic!(
1435                "plugin-runtime binary ({}) required for plugin-host tests",
1436                crate::plugin_runtime().program()
1437            );
1438        }
1439        let dir = tempfile::tempdir().unwrap();
1440        std::fs::write(
1441            dir.path().join("tools.mjs"),
1442            r#"export default {
1443  id: "toolshop",
1444  setup: async (ctx) => {
1445    await ctx.tool.transform((editor) => {
1446      editor.add({
1447        name: "echo",
1448        description: "echo the input",
1449        input: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
1450        async execute(input, call) {
1451          return {
1452            content: [{ type: "text", text: `hi ${input.text} ${call.sessionID}` }],
1453            metadata: { tag: "v2" },
1454          };
1455        },
1456      });
1457    });
1458  },
1459};"#,
1460        )
1461        .unwrap();
1462        let host = materialize_host(&dir.path().join("host"))?;
1463        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1464        sc.load(
1465            "toolshop",
1466            &dir.path().join("tools.mjs"),
1467            &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1468            &json!({}),
1469        )
1470        .await?;
1471        assert!(sc.handle().has_tools(), "load must report has_tools");
1472        let tools = sc.handle().tools().await?;
1473        let tool = tools
1474            .iter()
1475            .find(|t| t["name"] == "echo")
1476            .expect("v2 tool advertised");
1477        assert_eq!(tool["parameters"]["properties"]["text"]["type"], "string");
1478        let res = sc
1479            .handle()
1480            .execute_tool("echo", json!({"text": "x"}), json!({"sessionID": "s1"}))
1481            .await?;
1482        assert_eq!(res["ok"], true, "{res}");
1483        assert_eq!(res["output"], "hi x s1", "{res}");
1484        assert_eq!(res["metadata"]["tag"], "v2", "{res}");
1485        // Negative control: an unregistered name still fails honestly.
1486        let missing = sc
1487            .handle()
1488            .execute_tool("nope", json!({}), json!({}))
1489            .await?;
1490        assert_eq!(missing["ok"], false, "{missing}");
1491        sc.shutdown().await;
1492        Ok(())
1493    }
1494
1495    /// The Paseo sequencing: tools are added AFTER load, from an RPC handler
1496    /// (`rpc.bind` → `tool.transform`). A load-time tool count must not gate
1497    /// `tools()` — this test goes red under that gate.
1498    #[tokio::test]
1499    async fn v2_tool_added_after_load_is_advertised() -> anyhow::Result<()> {
1500        if !runtime_available() {
1501            panic!(
1502                "plugin-runtime binary ({}) required for plugin-host tests",
1503                crate::plugin_runtime().program()
1504            );
1505        }
1506        let dir = tempfile::tempdir().unwrap();
1507        std::fs::write(
1508            dir.path().join("late.mjs"),
1509            r#"export default {
1510  id: "late",
1511  setup: async (ctx) => {
1512    await ctx.rpc.register(
1513      { id: "late.rpc", methods: { add: { input: {}, output: {} } }, events: {} },
1514      {
1515        add: async () => {
1516          await ctx.tool.transform((editor) => {
1517            editor.add({
1518              name: "late_tool",
1519              description: "added by rpc",
1520              input: { type: "object", properties: {} },
1521              async execute() { return { content: [{ type: "text", text: "late-ok" }] }; },
1522            });
1523          });
1524          return {};
1525        },
1526      },
1527    );
1528  },
1529};"#,
1530        )
1531        .unwrap();
1532        let host = materialize_host(&dir.path().join("host"))?;
1533        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1534        let hooks = sc
1535            .load(
1536                "late",
1537                &dir.path().join("late.mjs"),
1538                &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1539                &json!({}),
1540            )
1541            .await?;
1542        assert!(hooks.is_empty(), "no hooks at load: {hooks:?}");
1543        assert!(
1544            sc.handle().tools().await?.is_empty(),
1545            "no tools before bind"
1546        );
1547        let out = sc.rpc_call("late.rpc", "add", json!({})).await?;
1548        assert!(out.get("output").is_some(), "{out}");
1549        let tools = sc.handle().tools().await?;
1550        assert!(
1551            tools.iter().any(|t| t["name"] == "late_tool"),
1552            "tool added after load must be advertised: {tools:?}"
1553        );
1554        sc.shutdown().await;
1555        Ok(())
1556    }
1557
1558    #[tokio::test]
1559    async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
1560        if !runtime_available() {
1561            panic!(
1562                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1563                crate::plugin_runtime().program()
1564            );
1565        }
1566        let dir = tempfile::tempdir().unwrap();
1567        // synthetic v1 plugin: PluginModule.server factory + mutating hook
1568        std::fs::write(
1569            dir.path().join("plug.mjs"),
1570            r#"
1571export const PluginModule = {
1572  id: "synthetic",
1573  server: async () => ({
1574    "tool.execute.after": async (input, output) => { output.seen = input.tool; },
1575    "chat.message": async (input, output) => { output.touched = true; },
1576    "event": async (payload) => {
1577      if (!payload.event || !payload.event.type) throw new Error("bad event shape");
1578      if (payload.event.type === "boom.type") throw new Error("event boom");
1579    },
1580  }),
1581};
1582export default PluginModule.server;
1583"#,
1584        )
1585        .unwrap();
1586        let host = materialize_host(&dir.path().join("host"))?;
1587        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
1588            .await
1589            .expect("spawn node");
1590        let ping = sc.request("ping", json!({})).await.expect("ping");
1591        assert_eq!(ping, "pong");
1592
1593        let input =
1594            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
1595        let hooks = sc
1596            .load(
1597                "synthetic",
1598                &dir.path().join("plug.mjs"),
1599                &input,
1600                &Value::Null,
1601            )
1602            .await
1603            .expect("load");
1604        assert_eq!(
1605            hooks,
1606            vec![
1607                "tool.execute.after".to_string(),
1608                "chat.message".to_string(),
1609                "event".to_string()
1610            ],
1611            "hook names registered in declaration order"
1612        );
1613
1614        // trigger mutates output in place (v1 semantics)
1615        let out = sc
1616            .trigger(
1617                "tool.execute.after",
1618                json!({"tool": "write", "args": {"filePath": "/x"}}),
1619                json!({}),
1620            )
1621            .await
1622            .expect("trigger");
1623        assert_eq!(
1624            out["seen"], "write",
1625            "hook observed input and mutated output"
1626        );
1627        // unregistered hook name → output unchanged
1628        let out2 = sc
1629            .trigger("permission.ask", json!({}), json!({"keep": 1}))
1630            .await
1631            .expect("trigger2");
1632        assert_eq!(out2["keep"], 1);
1633
1634        // v1 event delivery (plugin/index.ts:255-259): hooks["event"]
1635        // receives {event:{id,type,properties}}; shape-asserting fixture
1636        // only succeeds if the wrapper is exact (delivered counts non-
1637        // throwing hooks), and a throwing event hook fails open.
1638        let ev = sc
1639            .emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
1640            .await
1641            .expect("emit_event");
1642        assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
1643        let ev2 = sc
1644            .emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
1645            .await
1646            .expect("emit_event fail-open");
1647        assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");
1648
1649        let st = sc.statuses();
1650        assert_eq!(st["synthetic"]["ok"], true);
1651        assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");
1652
1653        sc.shutdown().await;
1654        Ok(())
1655    }
1656
1657    #[tokio::test]
1658    async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
1659        if !runtime_available() {
1660            panic!(
1661                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
1662                crate::plugin_runtime().program()
1663            );
1664        }
1665        let dir = tempfile::tempdir().unwrap();
1666        std::fs::write(
1667            dir.path().join("plug.mjs"),
1668            r#"
1669export const PluginModule = {
1670  id: "reaper",
1671  server: async () => ({
1672    "chat.message": async (_i, output) => { output.alive = true; },
1673  }),
1674};
1675export default PluginModule.server;
1676"#,
1677        )
1678        .unwrap();
1679        let host = materialize_host(&dir.path().join("host"))?;
1680        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1681        sc.load(
1682            "reaper",
1683            &dir.path().join("plug.mjs"),
1684            &json!({}),
1685            &Value::Null,
1686        )
1687        .await
1688        .expect("load");
1689        let pid = sc.child_pid();
1690        // force-kill the child (the live OOM class: sidecar dies, hooks
1691        // silently broken-piped until a respawn guard exists)
1692        std::process::Command::new("kill")
1693            .arg("-9")
1694            .arg(pid.to_string())
1695            .status()
1696            .expect("kill -9");
1697        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1698
1699        // next RPC must respawn + replay loads + deliver the mutation
1700        let out = sc
1701            .trigger("chat.message", json!({"sessionID": "s"}), json!({}))
1702            .await
1703            .expect("trigger after respawn");
1704        assert_eq!(out["alive"], true, "hook must fire after respawn");
1705        assert_ne!(sc.child_pid(), pid, "child process must be replaced");
1706        let st = sc.statuses();
1707        assert_eq!(
1708            st["reaper"]["ok"], true,
1709            "previously loaded plugins must be reloaded"
1710        );
1711        sc.shutdown().await;
1712        Ok(())
1713    }
1714
1715    /// v2 plugin battery (Phase 3): both dialects through the real sidecar.
1716    /// A promise-flavor plugin registers a session hook + an RPC; an
1717    /// effect-flavor plugin (with its own `effect` runtime vendored beside it)
1718    /// registers a tool hook. Asserts detection, dispatch, RPC round-trip, the
1719    /// real inventory, and that unregistered/missing RPCs keep exact errors.
1720    #[tokio::test]
1721    async fn v2_battery_promise_and_effect_dialects() -> anyhow::Result<()> {
1722        if !runtime_available() {
1723            panic!(
1724                "plugin-runtime binary ({}) required for plugin-host tests",
1725                crate::plugin_runtime().program()
1726            );
1727        }
1728        let dir = tempfile::tempdir().unwrap();
1729        std::fs::write(
1730            dir.path().join("p_v2_promise.mjs"),
1731            r#"export default {
1732  id: "v2promise",
1733  setup: async (ctx) => {
1734    await ctx.session.hook("context", (ev) => { ev.promiseTouched = true; });
1735    await ctx.tool.hook("execute.after", (ev) => { ev.result = "mutated-by-promise"; });
1736    await ctx.rpc.register({ id: "sample" }, {
1737      hello: async (input) => ({ echoed: input, from: "promise" }),
1738    });
1739    await ctx.storage.set("k", 41);
1740    if ((await ctx.storage.get("k")) !== 41) throw new Error("storage broke");
1741  },
1742};"#,
1743        )
1744        .unwrap();
1745        let eff = dir
1746            .path()
1747            .join("p_v2_effect")
1748            .join("node_modules")
1749            .join("effect");
1750        std::fs::create_dir_all(eff.join("lib")).unwrap();
1751        std::fs::write(
1752            eff.join("package.json"),
1753            r#"{"name":"effect","version":"3.0.0","type":"module","exports":{".":"./lib/index.js"}}"#,
1754        )
1755        .unwrap();
1756        std::fs::write(
1757            eff.join("lib/index.js"),
1758            "export const Effect = { scoped: (p) => p, runPromise: async (p) => { await p; } };\nexport const Scope = {};\n",
1759        )
1760        .unwrap();
1761        std::fs::write(
1762            dir.path().join("p_v2_effect").join("plug.mjs"),
1763            r#"export default {
1764  id: "v2effect",
1765  effect: (ctx) => (async () => {
1766    await ctx.tool.hook("execute.before", (ev) => { ev.input.before = "effect"; });
1767  })(),
1768};"#,
1769        )
1770        .unwrap();
1771
1772        let host = materialize_host(&dir.path().join("host"))?;
1773        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1774        let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
1775
1776        let h1 = sc
1777            .load(
1778                "v2promise",
1779                &dir.path().join("p_v2_promise.mjs"),
1780                &input,
1781                &Value::Null,
1782            )
1783            .await?;
1784        assert!(
1785            h1.contains(&"session.context".to_string()),
1786            "promise hooks: {h1:?}"
1787        );
1788        assert!(h1.contains(&"tool.execute.after".to_string()));
1789        let h2 = sc
1790            .load(
1791                "v2effect",
1792                &dir.path().join("p_v2_effect").join("plug.mjs"),
1793                &input,
1794                &Value::Null,
1795            )
1796            .await?;
1797        assert!(
1798            h2.contains(&"tool.execute.before".to_string()),
1799            "effect hooks: {h2:?}"
1800        );
1801
1802        let out = sc.trigger_v2("session", "context", json!({})).await?;
1803        assert_eq!(out["matched"], 1);
1804        assert_eq!(out["output"]["promiseTouched"], true);
1805        let after = sc
1806            .trigger_v2(
1807                "tool",
1808                "execute.after",
1809                json!({"tool": "read", "result": "orig"}),
1810            )
1811            .await?;
1812        assert_eq!(after["output"]["result"], "mutated-by-promise");
1813        let before = sc
1814            .trigger_v2(
1815                "tool",
1816                "execute.before",
1817                json!({"tool": "read", "input": {}}),
1818            )
1819            .await?;
1820        assert_eq!(before["output"]["input"]["before"], "effect");
1821
1822        let rpc = sc.rpc_call("sample", "hello", json!({"n": 7})).await?;
1823        assert_eq!(rpc["output"]["echoed"]["n"], 7);
1824        let miss = sc.rpc_call("sample", "nope", json!({})).await?;
1825        assert_eq!(miss["error"]["type"], "rpc.method_not_found");
1826        let unreg = sc.rpc_call("ghost", "hello", json!({})).await?;
1827        assert_eq!(unreg["error"]["type"], "rpc.unavailable");
1828
1829        let inv = sc.v2_inventory().await?;
1830        assert_eq!(inv["plugins"].as_array().unwrap().len(), 2, "{inv}");
1831        assert!(
1832            inv["rpcs"]
1833                .as_array()
1834                .unwrap()
1835                .iter()
1836                .any(|r| r == "sample")
1837        );
1838
1839        sc.shutdown().await;
1840        Ok(())
1841    }
1842
1843    /// Every hook upstream declares must be REGISTRABLE. Registering
1844    /// `experimental.ws.handshake` used to throw `unknown session hook`, which
1845    /// failed the plugin's whole setup and discarded the hooks ocserve does
1846    /// dispatch (found 2026-10-23 by diffing bench/v2/hooks.json against the
1847    /// shim table).
1848    #[tokio::test]
1849    async fn v2_accepts_every_declared_hook_at_registration() -> anyhow::Result<()> {
1850        if !runtime_available() {
1851            panic!(
1852                "plugin-runtime binary ({}) required for plugin-host tests",
1853                crate::plugin_runtime().program()
1854            );
1855        }
1856        let dir = tempfile::tempdir().unwrap();
1857        // One plugin registers every hook the extracted surface declares.
1858        let surface: serde_json::Value =
1859            serde_json::from_str(include_str!("../tests/fixtures/v2-hooks.json"))?;
1860        let mut body =
1861            String::from("export default {\n  id: \"v2allhooks\",\n  setup: async (ctx) => {\n");
1862        for (domain, hooks) in surface.as_object().unwrap() {
1863            for hook in hooks.as_array().unwrap() {
1864                let hook = hook.as_str().unwrap();
1865                body.push_str(&format!(
1866                    "    await ctx.{domain}.hook(\"{hook}\", () => {{}});\n"
1867                ));
1868            }
1869        }
1870        body.push_str("    await ctx.event.subscribe(() => {});\n  },\n};\n");
1871        std::fs::write(dir.path().join("all_hooks.mjs"), body).unwrap();
1872        let host = materialize_host(&dir.path().join("host"))?;
1873        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1874        let h = sc
1875            .load(
1876                "v2allhooks",
1877                &dir.path().join("all_hooks.mjs"),
1878                &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
1879                &Value::Null,
1880            )
1881            .await
1882            .expect("every declared hook must register without failing setup");
1883        for d in ["session", "tool", "permission", "shell"] {
1884            assert!(
1885                h.iter().any(|x| x == d || x.starts_with(&format!("{d}."))),
1886                "no {d} hook registered: {h:?}"
1887            );
1888        }
1889        sc.shutdown().await;
1890        Ok(())
1891    }
1892
1893    /// A v2 plugin that registers a transform on an UNBRIDGED domain must still
1894    /// load, and the divergence must be reported.
1895    ///
1896    /// The corpus run on 2026-10-21 found four real plugins failing to load with
1897    /// `D-V2-DOMAIN: ctx.<domain>.transform is not bridged`. They were not
1898    /// broken plugins: they register transforms during `setup`, which is
1899    /// upstream's only way to contribute to those domains, and our shim threw on
1900    /// the registration call. That failed the WHOLE plugin, discarding the hooks
1901    /// we do bridge — `session.context`, `tool.execute.before`, events. A
1902    /// divergence must degrade one capability, never the plugin.
1903    ///
1904    /// The transform is accepted and recorded, never invoked (calling it would
1905    /// mean applying an edit ocserve cannot apply), and the domain is reported in
1906    /// the inventory so the operator can see it.
1907    #[tokio::test]
1908    async fn v2_unbridged_transform_registers_instead_of_failing_setup() -> anyhow::Result<()> {
1909        if !runtime_available() {
1910            panic!(
1911                "plugin-runtime binary ({}) required for plugin-host tests",
1912                crate::plugin_runtime().program()
1913            );
1914        }
1915        let dir = tempfile::tempdir().unwrap();
1916        std::fs::write(
1917            dir.path().join("p_v2_edit.mjs"),
1918            r#"export default {
1919  id: "v2edit",
1920  setup: async (ctx) => {
1921    // A transform on a domain ocserve does not bridge (upstream's registration
1922    // form, so this is what real plugins do).
1923    await ctx.tool.transform((editor) => { editor.remove("bash"); });
1924    await ctx.integration.transform(() => {});
1925    // The common transform -> reload -> list sequence: reload must resolve.
1926    await ctx.provider.reload();
1927    // The hooks we DO bridge must survive.
1928    await ctx.session.hook("context", (ev) => { ev.survived = true; });
1929  },
1930};"#,
1931        )
1932        .unwrap();
1933
1934        let host = materialize_host(&dir.path().join("host"))?;
1935        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
1936        let input = json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"});
1937
1938        let hooks = sc
1939            .load(
1940                "v2edit",
1941                &dir.path().join("p_v2_edit.mjs"),
1942                &input,
1943                &Value::Null,
1944            )
1945            .await
1946            .expect("a transform on an unbridged domain must not fail setup");
1947
1948        // The bridged hook registered by the same plugin still works.
1949        assert!(
1950            hooks.contains(&"session.context".to_string()),
1951            "the bridged hook must survive: {hooks:?}"
1952        );
1953        let out = sc.trigger_v2("session", "context", json!({})).await?;
1954        assert_eq!(out["matched"], 1);
1955        assert_eq!(out["output"]["survived"], true);
1956
1957        // And the still-unbridged domains are reported, not silently swallowed.
1958        // `tool` is NOT here any more: its transform runs against a live editor
1959        // (see v2_tool_transform_registers_and_executes).
1960        let inv = sc.v2_inventory().await?;
1961        let unbridged: Vec<String> = inv["unbridged_transforms"]
1962            .as_array()
1963            .expect("inventory must list unbridged transforms")
1964            .iter()
1965            .map(|v| v.as_str().unwrap_or_default().to_string())
1966            .collect();
1967        assert!(!unbridged.contains(&"tool".to_string()), "{inv}");
1968        assert!(unbridged.contains(&"integration".to_string()), "{inv}");
1969
1970        // Genuine USE of an unbridged domain still throws its named divergence
1971        // (the capability really is absent; only registration is tolerated).
1972        std::fs::write(
1973            dir.path().join("p_v2_use.mjs"),
1974            r#"export default {
1975  id: "v2use",
1976  setup: async (ctx) => { await ctx.vcs.apply({}); },
1977};"#,
1978        )
1979        .unwrap();
1980        let err = sc
1981            .load(
1982                "v2use",
1983                &dir.path().join("p_v2_use.mjs"),
1984                &input,
1985                &Value::Null,
1986            )
1987            .await
1988            .expect_err("using an unbridged domain must still fail loudly");
1989        let text = format!("{err:#}");
1990        assert!(text.contains("D-V2-DOMAIN"), "{text}");
1991        assert!(text.contains("vcs"), "{text}");
1992
1993        sc.shutdown().await;
1994        Ok(())
1995    }
1996
1997    /// The v2 REST half of a domain is bound to the route that actually exists —
1998    /// and an UNBOUND verb keeps the named divergence instead of a bare TypeError.
1999    ///
2000    /// The 2026-10-18 finding: `session: { ...registrar("session") }` gave
2001    /// `ctx.session` only `hook`, so `ctx.session.get(id)` was
2002    /// `TypeError: ... is not a function` — a crash, not the honest throw the rest
2003    /// of the shim uses. `ctx.plugin.list()` likewise returned `[]` while
2004    /// `/api/plugin` serves the real inventory (D-PLUGIN-INVENTORY was closed).
2005    #[tokio::test]
2006    async fn v2_domain_rest_methods_bind_real_routes() -> anyhow::Result<()> {
2007        if !runtime_available() {
2008            panic!(
2009                "plugin-runtime binary ({}) required for plugin-host tests",
2010                crate::plugin_runtime().program()
2011            );
2012        }
2013        // A real HTTP responder so ctx.session.get() exercises an actual route
2014        // (stdlib thread; the shim fetches it like any other client would).
2015        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2016        let port = listener.local_addr().unwrap().port();
2017        std::thread::spawn(move || {
2018            for stream in listener.incoming() {
2019                let Ok(mut s) = stream else { continue };
2020                use std::io::{Read, Write};
2021                let mut buf = [0u8; 2048];
2022                let _ = s.read(&mut buf);
2023                let body = br#"{"id":"ses_bound","title":"bound-route"}"#;
2024                let _ = s.write_all(
2025                format!(
2026                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
2027                    body.len()
2028                )
2029                .as_bytes(),
2030            );
2031                let _ = s.write_all(body);
2032            }
2033        });
2034
2035        let dir = tempfile::tempdir().unwrap();
2036        // The fixture reports each probe's outcome back over RPC so the test can
2037        // read real results (not shim internals).
2038        std::fs::write(
2039            dir.path().join("rest.mjs"),
2040            r#"export default {
2041  id: "restprobe",
2042  setup: async (ctx) => {
2043    const results = {};
2044    // plugin.list must return the REAL inventory, not [].
2045    results.pluginList = await ctx.plugin.list();
2046    // session.get must reach the bound route.
2047    try {
2048      const s = await ctx.session.get("ses_bound");
2049      results.sessionGet = { ok: true, id: s && s.id };
2050    } catch (e) { results.sessionGet = { ok: false, err: String(e && e.message || e) }; }
2051    // An UNBOUND verb must throw the NAMED divergence, not a TypeError.
2052    try { await ctx.session.notARealVerb("x"); results.unbound = { threw: false }; }
2053    catch (e) { results.unbound = { threw: true, msg: String(e && e.message || e) }; }
2054    await ctx.rpc.register({ id: "probe" }, { results: async () => results });
2055  },
2056};"#,
2057        )
2058        .unwrap();
2059
2060        let host = materialize_host(&dir.path().join("host"))?;
2061        let mut sc = Sidecar::spawn(&host, &format!("http://127.0.0.1:{port}"), "/work").await?;
2062        let input = json!({"directory": "/work", "serverUrl": format!("http://127.0.0.1:{port}")});
2063        sc.load(
2064            "restprobe",
2065            &dir.path().join("rest.mjs"),
2066            &input,
2067            &Value::Null,
2068        )
2069        .await?;
2070
2071        let r = sc.rpc_call("probe", "results", json!({})).await?;
2072        let out = &r["output"];
2073
2074        // 1. plugin.list is real (contains our own id), not empty.
2075        let listed = out["pluginList"].as_array().cloned().unwrap_or_default();
2076        assert!(
2077            listed.iter().any(|p| p["id"] == "restprobe"),
2078            "ctx.plugin.list() must report the loaded plugin: {out}"
2079        );
2080
2081        // 2. session.get hit the bound route (the stub answered ses_bound).
2082        assert_eq!(
2083            out["sessionGet"]["ok"], true,
2084            "ctx.session.get must reach /api/session/{{id}}: {out}"
2085        );
2086        assert_eq!(out["sessionGet"]["id"], "ses_bound");
2087
2088        // 3. an unbound verb throws the NAMED divergence (D-V2-DOMAIN), not a
2089        //    TypeError and not silently succeeding.
2090        assert_eq!(
2091            out["unbound"]["threw"], true,
2092            "unbound verb must throw: {out}"
2093        );
2094        let msg = out["unbound"]["msg"].as_str().unwrap_or_default();
2095        assert!(
2096            msg.contains("D-V2-DOMAIN"),
2097            "unbound verb must name the divergence (D-V2-DOMAIN), got: {msg}"
2098        );
2099
2100        sc.shutdown().await;
2101        Ok(())
2102    }
2103
2104    /// A v2 plugin's `command.transform` / `skill.transform` edits are PULLED by
2105    /// Rust and come back as the list both consumers serve.
2106    ///
2107    /// The all-consumers rule (TESTING §1): `skill_entries()` filters
2108    /// `Payloads.command` on `source=="skill"`, so a skill transform must change
2109    /// the SYSTEM PROMPT the model reads, not just the `/command` route. A test
2110    /// that only asserted the RPC round-trip would pass while the prompt kept the
2111    /// old text — shape without mutation.
2112    ///
2113    /// Also covers: add REPLACES a same-named entry (upstream `editor.set`,
2114    /// core/command.ts:61, so a reload is idempotent), and a THROWING transform is
2115    /// reported without taking the list down.
2116    #[tokio::test]
2117    async fn v2_command_transform_pulls_into_the_served_list() -> anyhow::Result<()> {
2118        if !runtime_available() {
2119            panic!(
2120                "plugin-runtime binary ({}) required for plugin-host tests",
2121                crate::plugin_runtime().program()
2122            );
2123        }
2124        let dir = tempfile::tempdir().unwrap();
2125        std::fs::write(
2126            dir.path().join("tx.mjs"),
2127            r#"export default {
2128  id: "tx",
2129  setup: async (ctx) => {
2130    // upstream shape: ctx.command.transform((editor) => editor.add({...}))
2131    await ctx.command.transform((editor) => {
2132      editor.add({ name: "plugin-cmd", description: "added by plugin" });
2133    });
2134    await ctx.skill.transform((editor) => {
2135      editor.update("demo-skill", (s) => { s.description = "rewritten by plugin"; });
2136      editor.add({ name: "plugin-skill", description: "skill from plugin", source: "skill" });
2137    });
2138    await ctx.command.reload();
2139    const listed = await ctx.command.list();
2140    await ctx.rpc.register({ id: "probe" }, {
2141      afterSetup: async () => ({ listed }),
2142    });
2143  },
2144};"#,
2145        )
2146        .unwrap();
2147
2148        let host = materialize_host(&dir.path().join("host"))?;
2149        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
2150        let input = json!({"directory": "/work"});
2151        sc.load("tx", &dir.path().join("tx.mjs"), &input, &Value::Null)
2152            .await?;
2153
2154        // The pristine list: one skill (what ocserve's own config produced) and
2155        // one config command. Skills and commands share ONE vector.
2156        let pristine = vec![
2157            json!({"name": "demo-skill", "description": "original", "source": "skill"}),
2158            json!({"name": "review", "description": "config command", "source": "config"}),
2159        ];
2160        let (edited, failures) = sc.transform_commands(pristine.clone()).await?;
2161
2162        assert!(
2163            failures.is_empty(),
2164            "no transform should have failed: {failures:?}"
2165        );
2166        // 1. the command transform's add landed
2167        let added = edited
2168            .iter()
2169            .find(|c| c["name"] == "plugin-cmd")
2170            .expect("plugin command must be present");
2171        assert_eq!(added["description"], "added by plugin");
2172        // 2. the skill transform's update landed — THIS is the prompt-visible half
2173        let skill = edited
2174            .iter()
2175            .find(|c| c["name"] == "demo-skill")
2176            .expect("demo-skill must still be present");
2177        assert_eq!(
2178            skill["description"], "rewritten by plugin",
2179            "skill.transform must reach the vector skill_entries() reads"
2180        );
2181        // 3. the skill add landed with the skill source (so skill_entries picks it up)
2182        assert!(
2183            edited
2184                .iter()
2185                .any(|c| c["name"] == "plugin-skill" && c["source"] == "skill"),
2186            "plugin skill must carry source=skill or skill_entries() drops it: {edited:?}"
2187        );
2188        // 4. untouched entries survive (the all-consumers rule cuts both ways)
2189        assert!(edited.iter().any(|c| c["name"] == "review"));
2190
2191        // 5. IDEMPOTENT: a second pull from pristine yields the same list (add
2192        //    replaces, never accumulates).
2193        let (again, _) = sc.transform_commands(pristine.clone()).await?;
2194        assert_eq!(
2195            serde_json::to_value(&again).unwrap(),
2196            serde_json::to_value(&edited).unwrap(),
2197            "a reload must not accumulate duplicates"
2198        );
2199
2200        // 6. a pull over a one-entry list keeps that entry (the plugin's own adds are
2201        //    additive; the caller must never receive a shorter list than it sent)
2202        let (kept, _) = sc
2203            .transform_commands(vec![json!({"name": "keepme"})])
2204            .await?;
2205        assert!(kept.iter().any(|c| c["name"] == "keepme"));
2206
2207        sc.shutdown().await;
2208        Ok(())
2209    }
2210
2211    /// A throwing v2 transform is reported, never fatal — upstream's state machine
2212    /// disables a failing transform (core/state.ts:178-184) rather than
2213    /// propagating, because a broken third-party plugin must not take the server's
2214    /// command surface down with it.
2215    #[tokio::test]
2216    async fn v2_command_transform_failure_keeps_the_list() -> anyhow::Result<()> {
2217        if !runtime_available() {
2218            panic!(
2219                "plugin-runtime binary ({}) required for plugin-host tests",
2220                crate::plugin_runtime().program()
2221            );
2222        }
2223        let dir = tempfile::tempdir().unwrap();
2224        std::fs::write(
2225            dir.path().join("boom.mjs"),
2226            r#"export default {
2227  id: "boom",
2228  setup: async (ctx) => {
2229    await ctx.command.transform(() => { throw new Error("transform exploded"); });
2230    await ctx.command.transform((editor) => { editor.add({ name: "survivor" }); });
2231  },
2232};"#,
2233        )
2234        .unwrap();
2235
2236        let host = materialize_host(&dir.path().join("host"))?;
2237        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:1", "/work").await?;
2238        let input = json!({"directory": "/work"});
2239        sc.load("boom", &dir.path().join("boom.mjs"), &input, &Value::Null)
2240            .await?;
2241
2242        let (kept, failures) = sc
2243            .transform_commands(vec![json!({"name": "existing"})])
2244            .await?;
2245        // the good transform still ran (a broken one does not abort the rest)
2246        assert!(
2247            kept.iter().any(|c| c["name"] == "survivor"),
2248            "a throwing transform must not stop the others: {kept:?}"
2249        );
2250        assert!(kept.iter().any(|c| c["name"] == "existing"));
2251        // and the failure is reported so the server can log + count it
2252        assert_eq!(failures.len(), 1, "the throwing transform must be reported");
2253        assert!(
2254            failures[0]["message"]
2255                .as_str()
2256                .unwrap_or_default()
2257                .contains("transform exploded"),
2258            "{failures:?}"
2259        );
2260
2261        sc.shutdown().await;
2262        Ok(())
2263    }
2264
2265    /// The `config` hook is dispatched (v1 parity, plugin/index.ts:244-251).
2266    /// Closes the registered-but-never-called class: a plugin whose `config`
2267    /// is a real hook must see it run (host `config` used to hard-code "ok").
2268    #[tokio::test]
2269    async fn config_hook_is_dispatched() -> anyhow::Result<()> {
2270        if !runtime_available() {
2271            panic!(
2272                "plugin-runtime binary ({}) required for plugin-host tests",
2273                crate::plugin_runtime().program()
2274            );
2275        }
2276        let dir = tempfile::tempdir().unwrap();
2277        std::fs::write(
2278            dir.path().join("cfg.mjs"),
2279            r#"export const PluginModule = {
2280  id: "cfg",
2281  server: async () => ({
2282    config: async (cfg) => {
2283      if (typeof cfg !== "object" || cfg === null) throw new Error("config not object");
2284    },
2285    "chat.message": async () => {},
2286  }),
2287};
2288export default PluginModule.server;"#,
2289        )
2290        .unwrap();
2291        let host = materialize_host(&dir.path().join("host"))?;
2292        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2293        sc.load("cfg", &dir.path().join("cfg.mjs"), &json!({}), &Value::Null)
2294            .await?;
2295        let r = sc.config(json!({"model": "x"})).await?;
2296        assert_eq!(r["matched"], 1, "config hook must be dispatched: {r}");
2297        sc.shutdown().await;
2298        Ok(())
2299    }
2300
2301    /// Test environment gate: the ACTUAL runtime (bun preferred) must exist.
2302    fn runtime_available() -> bool {
2303        crate::which(crate::plugin_runtime().program()).is_some()
2304    }
2305
2306    /// Real-plugin battery (V2-EXECUTION-PLAN Phase 2): every v1 authoring
2307    /// form the frozen client supports (plugin/index.ts readV1Plugin +
2308    /// getLegacyPlugins) plus the `[spec, options]` tuple. Loads all forms
2309    /// through ONE sidecar (as production does) and asserts each registered
2310    /// the expected hook AND that options actually reach the factory (the
2311    /// silently-dropped-tuple bug this battery exists to pin).
2312    #[tokio::test]
2313    async fn battery_all_authoring_forms_and_options() -> anyhow::Result<()> {
2314        if !runtime_available() {
2315            panic!(
2316                "plugin-runtime binary ({}) required for plugin-host tests",
2317                crate::plugin_runtime().program()
2318            );
2319        }
2320        let dir = tempfile::tempdir().unwrap();
2321        // 1. PluginModule.server (v1 canonical)
2322        std::fs::write(
2323            dir.path().join("p_module.mjs"),
2324            r#"export const PluginModule = {
2325  id: "m",
2326  server: async () => ({ "chat.message": async (_i, o) => { o.module = true; } }),
2327};"#,
2328        )
2329        .unwrap();
2330        // 2. default object with .server
2331        std::fs::write(
2332            dir.path().join("p_default_obj.mjs"),
2333            r#"export default { server: async () => ({ "chat.params": async (_i, o) => { o.defaultobj = true; } }) };"#,
2334        )
2335        .unwrap();
2336        // 3. default function (legacy)
2337        std::fs::write(
2338            dir.path().join("p_default_fn.mjs"),
2339            r#"export default async () => ({ "tool.execute.after": async (_i, o) => { o.defaultfn = true; } });"#,
2340        )
2341        .unwrap();
2342        // 4. named plain-function export (each IS a server factory)
2343        std::fs::write(
2344            dir.path().join("p_named.mjs"),
2345            r#"export async function MyPlugin() { return { "event": async () => {} }; }"#,
2346        )
2347        .unwrap();
2348        // 5. options tuple: the factory must SEE the second tuple element.
2349        std::fs::write(
2350            dir.path().join("p_options.mjs"),
2351            r#"export const PluginModule = {
2352  id: "opts",
2353  server: async (_input, options) => ({
2354    "chat.message": async (_i, o) => { o.sawOptions = options; },
2355  }),
2356};"#,
2357        )
2358        .unwrap();
2359
2360        let host = materialize_host(&dir.path().join("host"))?;
2361        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2362        let input =
2363            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
2364
2365        let h1 = sc
2366            .load("m", &dir.path().join("p_module.mjs"), &input, &Value::Null)
2367            .await?;
2368        assert_eq!(h1, vec!["chat.message"], "PluginModule.server form");
2369        let h2 = sc
2370            .load(
2371                "dobj",
2372                &dir.path().join("p_default_obj.mjs"),
2373                &input,
2374                &Value::Null,
2375            )
2376            .await?;
2377        assert_eq!(h2, vec!["chat.params"], "default object with .server form");
2378        let h3 = sc
2379            .load(
2380                "dfn",
2381                &dir.path().join("p_default_fn.mjs"),
2382                &input,
2383                &Value::Null,
2384            )
2385            .await?;
2386        assert_eq!(
2387            h3,
2388            vec!["tool.execute.after"],
2389            "default function (legacy) form"
2390        );
2391        let h4 = sc
2392            .load(
2393                "named",
2394                &dir.path().join("p_named.mjs"),
2395                &input,
2396                &Value::Null,
2397            )
2398            .await?;
2399        assert_eq!(h4, vec!["event"], "named function export form");
2400
2401        let opts = json!({"token": "abc", "n": 3});
2402        let h5 = sc
2403            .load("opts", &dir.path().join("p_options.mjs"), &input, &opts)
2404            .await?;
2405        assert_eq!(
2406            h5,
2407            vec!["chat.message"],
2408            "options-tuple form registers same hook"
2409        );
2410
2411        // Dispatch across ALL loaded plugins: each form's hook fires.
2412        let out = sc.trigger("chat.message", json!({}), json!({})).await?;
2413        assert_eq!(out["module"], true, "form 1 hook fired");
2414        // options reached the factory (the tuple was NOT dropped)
2415        assert_eq!(out["sawOptions"], opts, "factory saw the tuple options");
2416        let out2 = sc.trigger("chat.params", json!({}), json!({})).await?;
2417        assert_eq!(out2["defaultobj"], true, "form 2 hook fired");
2418        let out3 = sc
2419            .trigger("tool.execute.after", json!({}), json!({}))
2420            .await?;
2421        assert_eq!(out3["defaultfn"], true, "form 3 hook fired");
2422
2423        // statuses carry all five loads (real inventory, not empty).
2424        let st = sc.statuses();
2425        for spec in ["m", "dobj", "dfn", "named", "opts"] {
2426            assert_eq!(st[spec]["ok"], true, "status for {spec}");
2427        }
2428        sc.shutdown().await;
2429        Ok(())
2430    }
2431}
2432
2433#[cfg(test)]
2434mod runtime_selection_tests {
2435    /// `OCSERVE_PLUGIN_RUNTIME` forces the runtime (lab A/B control);
2436    /// unset/unknown → bun-if-present else node. Env is process-local and
2437    /// restored (this file is the only env mutator in its own process).
2438    #[test]
2439    fn runtime_override_and_default_preference() {
2440        let has_bun = crate::which("bun").is_some();
2441        let has_node = crate::which("node").is_some();
2442        if !has_node {
2443            panic!("node required for the fallback leg (test environment gate)");
2444        }
2445
2446        // SAFETY: single-threaded env mutation, restored below.
2447        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
2448        assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
2449
2450        if has_bun {
2451            unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
2452            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
2453            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2454            assert_eq!(
2455                crate::plugin_runtime(),
2456                crate::PluginRuntime::Bun,
2457                "bun present + no override → bun preferred (upstream fidelity)"
2458            );
2459        } else {
2460            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2461            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
2462        }
2463
2464        // unknown value falls through to preference, never panics
2465        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
2466        let _ = crate::plugin_runtime();
2467        unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
2468    }
2469}
2470
2471#[cfg(test)]
2472mod oom_wrapper_tests {
2473    /// A3 proof: the spawn wrapper makes the CHILD report adj=500 so a
2474    /// memcg OOM kill takes the child (respawnable) — not the main service.
2475    #[cfg(target_os = "linux")]
2476    #[test]
2477    fn wrapper_raises_child_oom_score_adj() {
2478        let out = std::process::Command::new("sh")
2479            .arg("-c")
2480            .arg(ocserve_store::cgroup::WRAPPER)
2481            .arg("sh")
2482            .arg("cat")
2483            .arg("/proc/self/oom_score_adj")
2484            .output()
2485            .expect("wrapper spawns");
2486        assert!(
2487            out.status.success(),
2488            "wrapper failed: {}",
2489            String::from_utf8_lossy(&out.stderr)
2490        );
2491        assert_eq!(
2492            String::from_utf8_lossy(&out.stdout).trim(),
2493            "500",
2494            "child must run at adj=500"
2495        );
2496    }
2497}
2498
2499#[cfg(test)]
2500mod plugin_tool_schema_tests {
2501    use super::*;
2502
2503    /// A plugin tool's Zod args must become a VALID JSON Schema before it
2504    /// reaches the provider. The first implementation passed the raw Zod
2505    /// objects straight through (`{~standard, def, type}`) and the provider
2506    /// rejected every request in the session with 400 (found live on
2507    /// `ctx_reduce`, 2026-10-23).
2508    #[tokio::test]
2509    async fn plugin_tool_schema_is_valid_json_schema() -> anyhow::Result<()> {
2510        let dir = tempfile::tempdir()?;
2511        let entry = dir.path().join("p_schema.mjs");
2512        std::fs::write(
2513            &entry,
2514            r#"import { z } from "zod";
2515export const hook = async () => ({
2516  tool: {
2517    ztool: {
2518      description: "zod args",
2519      args: {
2520        text: z.string(),
2521        count: z.number(),
2522      },
2523      execute: async () => "ok",
2524    },
2525  },
2526});"#,
2527        )?;
2528        // `z` is resolved from the plugin's own tree, exactly like a real one.
2529        std::fs::create_dir_all(dir.path().join("node_modules/zod"))?;
2530        std::fs::write(
2531            dir.path().join("node_modules/zod/package.json"),
2532            r#"{"name":"zod","version":"4.0.0","main":"./index.cjs","exports":{".":"./index.cjs","./v4":"./index.cjs"}}"#,
2533        )?;
2534        std::fs::write(
2535            dir.path().join("node_modules/zod/index.cjs"),
2536            "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'] });",
2537        )?;
2538        let host = materialize_host(&dir.path().join("host"))?;
2539        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
2540        sc.load(
2541            "schema-fixture",
2542            &entry,
2543            &json!({"directory": "/work", "serverUrl": "http://127.0.0.1:9"}),
2544            &Value::Null,
2545        )
2546        .await?;
2547        let tools = sc.handle().tools().await?;
2548        let tool = tools
2549            .iter()
2550            .find(|t| t["name"] == "ztool")
2551            .expect("ztool advertised");
2552        let params = &tool["parameters"];
2553        assert_eq!(params["type"], "object", "{params}");
2554        assert_eq!(params["properties"]["text"]["type"], "string", "{params}");
2555        assert!(
2556            params["properties"]["text"].get("~standard").is_none()
2557                && params["properties"]["text"].get("def").is_none(),
2558            "a raw Zod object must never reach the provider: {params}"
2559        );
2560        sc.shutdown().await;
2561        Ok(())
2562    }
2563}