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