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
12pub mod normalize;
13pub use normalize::{Outcome as NormalizeOutcome, normalize_or_raw_sync};
14
15use anyhow::{Context, Result, anyhow};
16use serde_json::{Value, json};
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
21use tokio::process::{Child, ChildStdin, Command};
22use tokio::sync::oneshot;
23
24/// Host files (written next to the data dir once; content-addressed by embed).
25pub const HOST_FILES: &[(&str, &str)] = &[
26    ("host.mjs", include_str!("host/host.mjs")),
27    (
28        "bun-sqlite-loader.mjs",
29        include_str!("host/bun-sqlite-loader.mjs"),
30    ),
31    (
32        "shim-bun-sqlite.mjs",
33        include_str!("host/shim-bun-sqlite.mjs"),
34    ),
35    (
36        "shim-bun-sqlite.cjs",
37        include_str!("host/shim-bun-sqlite.cjs"),
38    ),
39];
40
41/// Per-RPC timeout (hooks are local JS; anything longer is a runaway plugin).
42pub const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
43
44/// Write host files into `dir` (idempotent overwrite — embed is authoritative).
45pub fn materialize_host(dir: &Path) -> Result<PathBuf> {
46    std::fs::create_dir_all(dir).with_context(|| format!("create host dir {}", dir.display()))?;
47    for (name, body) in HOST_FILES {
48        let path = dir.join(name);
49        std::fs::write(&path, body).with_context(|| format!("write {}", path.display()))?;
50    }
51    Ok(dir.join("host.mjs"))
52}
53
54/// Resolve a plugin spec to an entry file (loader.ts semantics, npm-install
55/// stage assumed already done by opencode's cache — we re-use it read-only):
56/// - absolute/relative path → direct entry
57/// - npm spec (`name`, `@scope/name`, `name@version`) →
58///   `~/.cache/opencode/packages/{spec}[@latest]/node_modules/{pkg}/…` entry
59///   via package.json exports["."] | main | module
60pub fn resolve_entry(spec: &str, home: &Path) -> Result<PathBuf> {
61    if spec.starts_with('/') || spec.starts_with("./") || spec.starts_with("../") {
62        let p = PathBuf::from(spec);
63        if p.exists() {
64            return Ok(p);
65        }
66        anyhow::bail!("plugin file not found: {spec}");
67    }
68    let cache = home.join(".cache/opencode/packages");
69    let pkg_name = strip_version(spec);
70    let candidates = [
71        cache.join(format!("{spec}@latest")),
72        cache.join(spec),
73        cache.join(format!("{pkg_name}@latest")),
74    ];
75    for dir in &candidates {
76        if !dir.exists() {
77            continue;
78        }
79        // wrapper package.json → node_modules/<pkg>/package.json
80        let direct = dir.join("package.json");
81        if let Some(entry) = entry_from_package(&direct, dir, &pkg_name) {
82            return Ok(entry);
83        }
84        let nested = dir
85            .join("node_modules")
86            .join(&pkg_name)
87            .join("package.json");
88        if let Some(entry) = entry_from_package(&nested, nested.parent().unwrap_or(dir), &pkg_name)
89        {
90            return Ok(entry);
91        }
92    }
93    anyhow::bail!("plugin target not found in opencode cache: {spec}")
94}
95
96fn strip_version(spec: &str) -> String {
97    // "@scope/name@latest" → "@scope/name"; "name@1.2.3" → "name"
98    let bytes = spec.as_bytes();
99    // find the LAST '@' that is NOT at index 0 (scope marker)
100    let mut cut = None;
101    for (i, b) in bytes.iter().enumerate() {
102        if *b == b'@' && i > 0 {
103            cut = Some(i);
104        }
105    }
106    match cut {
107        Some(i) => spec[..i].to_string(),
108        None => spec.to_string(),
109    }
110}
111
112fn entry_from_package(pkg_json: &Path, base: &Path, _pkg_name: &str) -> Option<PathBuf> {
113    let text = std::fs::read_to_string(pkg_json).ok()?;
114    let v: Value = serde_json::from_str(&text).ok()?;
115    let mut rel: Option<&str> = None;
116    if let Some(exp) = v.get("exports")
117        && let Some(dot) = exp.get(".")
118    {
119        rel = match dot {
120            Value::String(s) => Some(s.as_str()),
121            Value::Object(_) => dot
122                .get("import")
123                .and_then(|x| x.as_str())
124                .or_else(|| dot.get("default").and_then(|x| x.as_str())),
125            _ => None,
126        };
127    }
128    rel = rel.or_else(|| v.get("main").and_then(|x| x.as_str()));
129    rel = rel.or_else(|| v.get("module").and_then(|x| x.as_str()));
130    let rel = rel?;
131    let entry = base.join(rel);
132    entry.exists().then_some(entry)
133}
134
135struct Pending {
136    tx: oneshot::Sender<Result<Value, String>>,
137}
138
139/// Sidecar handle: one Node process, NDJSON request/response, reader task.
140pub struct Sidecar {
141    stdin: ChildStdin,
142    pending: Arc<parking_lot::Mutex<HashMap<i64, Pending>>>,
143    next_id: std::sync::atomic::AtomicI64,
144    child: Child,
145    /// load results (spec → hooks) for status introspection
146    statuses: parking_lot::Mutex<HashMap<String, Value>>,
147    /// server/directory context for loads (kept for future reloads)
148    server: (String, String),
149    /// spawn identity for respawn-after-death
150    args: SpawnArgs,
151    /// successful loads (spec, entry, input) — replayed on respawn
152    /// (entries stored RAW; load_raw re-normalizes on replay — D1-PLAN)
153    loads: Vec<(String, PathBuf, Value)>,
154    /// normalization output root (`data/normalized`); None = skip (tests,
155    /// any sidecar without it — existing behavior untouched, D1-PLAN)
156    normalize_root: Option<PathBuf>,
157    /// spawn time for the L1 recycle min-uptime guard (SRE §5) — fresh on
158    /// every (re)spawn, so a recycled sidecar can't be recycled again until
159    /// the guard window passes.
160    started_at: std::time::Instant,
161    /// L1 recycle marker: set when WE killed the child on purpose; the next
162    /// ensure_alive must log that as INFO (planned), not ERROR (crash) —
163    /// an intentional action must never read as a failure in the logs.
164    recycled: bool,
165}
166
167/// `sh -c WRAPPER sh <prog> <args…>` → raise oom_score_adj, move into the
168/// L2 kids cgroup (if the partition dance published one), then exec.
169/// Kept identical in ocserve-mcp + ocserve-plugin (no shared dep) — A3/L2.
170pub const OOM_CHILD_WRAPPER: &str = r#"echo 500 >/proc/self/oom_score_adj 2>/dev/null; [ -n "$OCSERVE_KIDS_CGROUP" ] && echo $$ >"$OCSERVE_KIDS_CGROUP/cgroup.procs" 2>/dev/null; exec "$@""#;
171
172/// L2 partition: path published by ocserve's cgroup dance; children get
173/// it as a per-Command env (race-free — no process-global set_var).
174static KIDS_CGROUP: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
175pub fn set_kids_cgroup(p: impl Into<std::path::PathBuf>) {
176    let _ = KIDS_CGROUP.set(p.into());
177}
178
179/// Plugin-host runtime: Bun preferred (upstream runs plugins under Bun; real
180/// `bun:sqlite`, TS plugins load, lower RSS floor), Node fallback.
181/// `OCSERVE_PLUGIN_RUNTIME=node|bun` forces one (lab A/B control).
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum PluginRuntime {
184    Bun,
185    Node,
186}
187
188impl PluginRuntime {
189    pub fn program(self) -> &'static str {
190        match self {
191            PluginRuntime::Bun => "bun",
192            PluginRuntime::Node => "node",
193        }
194    }
195}
196
197/// Resolve an executable on PATH plus `~/.bun/bin` (the common user-local
198/// bun install location — systemd units do not see shell PATH extras).
199pub(crate) fn which(prog: &str) -> Option<PathBuf> {
200    if let Ok(path) = std::env::var("PATH") {
201        for dir in std::env::split_paths(&path) {
202            let cand = dir.join(prog);
203            if cand.is_file() {
204                return Some(cand);
205            }
206        }
207    }
208    if let Some(home) = std::env::var_os("HOME") {
209        let cand = Path::new(&home).join(".bun/bin").join(prog);
210        if cand.is_file() {
211            return Some(cand);
212        }
213    }
214    None
215}
216
217pub fn plugin_runtime() -> PluginRuntime {
218    match std::env::var("OCSERVE_PLUGIN_RUNTIME").as_deref() {
219        Ok("node") => return PluginRuntime::Node,
220        Ok("bun") => return PluginRuntime::Bun,
221        _ => {}
222    }
223    if which("bun").is_some() {
224        PluginRuntime::Bun
225    } else {
226        PluginRuntime::Node
227    }
228}
229
230#[derive(Clone)]
231struct SpawnArgs {
232    host_path: PathBuf,
233    server_url: String,
234    directory: String,
235}
236
237impl Sidecar {
238    pub async fn spawn(host_path: &Path, server_url: &str, directory: &str) -> Result<Self> {
239        // A3 (OOM-resilience): same wrapper as ocserve-mcp — the plugin host
240        // dies first on memcg pressure (ensure_alive respawns it) instead
241        // of the main service.
242        let runtime = crate::plugin_runtime();
243        // absolute path (systemd PATH may lack ~/.bun/bin); fall back to the
244        // bare name so a PATH-only environment still resolves
245        let program = which(runtime.program())
246            .map(|p| p.to_string_lossy().into_owned())
247            .unwrap_or_else(|| runtime.program().to_string());
248        let mut cmd = Command::new("sh");
249        cmd.arg("-c")
250            .arg(crate::OOM_CHILD_WRAPPER)
251            .arg("sh")
252            .arg(&program);
253        match runtime {
254            // Bun (upstream's own plugin runtime): real bun:sqlite + TS
255            // plugins load; `--smol` trades GC frequency for a lower RSS
256            // floor. No V8 --max-old-space knobs exist here.
257            PluginRuntime::Bun => {
258                cmd.arg("--smol");
259            }
260            // Node (fallback when bun is absent): V8 heap cap (env-tunable).
261            // Default raised64→128 after the LIVE battery (2026-10-03): with
262            // the real plugin set the sidecar OOM-killed at64 (observed boot
263            // death → hooks broken-piped until restart). Measured
264            // 64/128/192/256: RSS flat ~145-148MB either way (native
265            // dominates; heap cap only binds when heap actually grows).
266            PluginRuntime::Node => {
267                cmd.arg(format!(
268                    "--max-old-space-size={}",
269                    std::env::var("OCSERVE_PLUGIN_HEAP_MB")
270                        .ok()
271                        .and_then(|v| v.parse().ok())
272                        .unwrap_or(128)
273                ));
274                cmd.arg("--max-semi-space-size=2");
275            }
276        }
277        if let Some(k) = KIDS_CGROUP.get() {
278            cmd.env("OCSERVE_KIDS_CGROUP", k);
279        }
280        cmd.arg(host_path)
281            .stdin(std::process::Stdio::piped())
282            .stdout(std::process::Stdio::piped())
283            .stderr(std::process::Stdio::inherit())
284            .kill_on_drop(true);
285        let mut child = cmd
286            .spawn()
287            .with_context(|| format!("spawn {} plugin host", runtime.program()))?;
288        let stdin = child.stdin.take().context("host stdin")?;
289        let stdout = child.stdout.take().context("host stdout")?;
290        let pending = Arc::new(parking_lot::Mutex::new(HashMap::<i64, Pending>::new()));
291        let pending_task = Arc::clone(&pending);
292        tokio::spawn(async move {
293            let mut reader = BufReader::new(stdout);
294            let mut line = String::new();
295            loop {
296                line.clear();
297                match reader.read_line(&mut line).await {
298                    Ok(0) | Err(_) => break,
299                    Ok(_) => {}
300                }
301                let trimmed = line.trim();
302                if trimmed.is_empty() {
303                    continue;
304                }
305                match serde_json::from_str::<Value>(trimmed) {
306                    Ok(v) => {
307                        if let Some(id) = v.get("id").and_then(|i| i.as_i64()) {
308                            let result = match v.get("error") {
309                                Some(e) if !e.is_null() => {
310                                    Err(e["message"].as_str().unwrap_or("host error").to_string())
311                                }
312                                _ => Ok(v.get("result").cloned().unwrap_or(Value::Null)),
313                            };
314                            if let Some(p) = pending_task.lock().remove(&id) {
315                                let _ = p.tx.send(result);
316                            }
317                        }
318                        // no id → informational; host routes plugin chatter to stderr
319                    }
320                    Err(_) => {
321                        let head: String = trimmed.chars().take(120).collect();
322                        tracing::warn!("plugin host: unparsable line: {head}");
323                    }
324                }
325            }
326            // host death: fail everything in flight (fail fast, AGENTS §2.4)
327            for (_, p) in pending_task.lock().drain() {
328                let _ = p.tx.send(Err("plugin host exited".into()));
329            }
330        });
331        Ok(Self {
332            stdin,
333            pending,
334            next_id: std::sync::atomic::AtomicI64::new(1),
335            child,
336            statuses: parking_lot::Mutex::new(HashMap::new()),
337            server: (server_url.to_string(), directory.to_string()),
338            args: SpawnArgs {
339                host_path: host_path.to_path_buf(),
340                server_url: server_url.to_string(),
341                directory: directory.to_string(),
342            },
343            loads: Vec::new(),
344            normalize_root: None,
345            started_at: std::time::Instant::now(),
346            recycled: false,
347        })
348    }
349
350    /// RPCs currently in flight (the L1 recycle idle gate — a hook must
351    /// never be interrupted mid-call).
352    pub fn in_flight(&self) -> usize {
353        self.pending.lock().len()
354    }
355
356    /// Seconds since this sidecar instance was spawned (respawns reset it).
357    pub fn uptime(&self) -> std::time::Duration {
358        self.started_at.elapsed()
359    }
360
361    /// L1 graceful recycle (SRE §5): kill the sidecar child while idle.
362    /// State is disk-backed (context.db / pins) and `loads` is kept, so the
363    /// next `ensure_alive` respawns + replays hooks (warm-hash normalize is
364    /// a no-op). SIGKILL is deliberate: the host has no shutdown protocol
365    /// and nothing in it needs flushing. Returns false if already dead.
366    pub fn recycle_child(&mut self) -> bool {
367        if self.child.try_wait().ok().flatten().is_some() {
368            return false;
369        }
370        let _ = self.child.start_kill();
371        self.statuses.lock().clear();
372        self.recycled = true;
373        true
374    }
375
376    /// Enable normalization for this sidecar (set once at boot; carried to
377    /// respawns by `ensure_alive`). None/never-set = raw loads (today's
378    /// behavior — all existing tests stay on this path).
379    pub fn set_normalize_root(&mut self, root: PathBuf) {
380        self.normalize_root = Some(root);
381    }
382
383    /// Respawn after unexpected death (V8 OOM / crash) and replay every
384    /// previously loaded plugin. Without this a dead sidecar leaves ALL
385    /// hooks broken-piped until service restart (live battery finding
386    /// 2026-10-03: boot-time heap OOM, fail-open hid it in the prompt path).
387    pub async fn ensure_alive(&mut self) -> Result<()> {
388        match self.child.try_wait() {
389            Ok(None) => return Ok(()),
390            Ok(Some(status)) => {
391                if std::mem::take(&mut self.recycled) {
392                    tracing::info!(
393                        "plugin sidecar recycled (L1, was {status}) — respawning + replaying hooks"
394                    );
395                } else {
396                    tracing::error!("plugin sidecar exited ({status}) — respawning");
397                }
398            }
399            Err(e) => {
400                tracing::error!("plugin sidecar try_wait failed: {e} — respawning");
401            }
402        }
403        let args = self.args.clone();
404        let loads = std::mem::take(&mut self.loads);
405        let mut fresh = Sidecar::spawn(&args.host_path, &args.server_url, &args.directory).await?;
406        // D1-PLAN: replay must normalize too (warm no-op; rebuilds if outputs
407        // were wiped mid-run — A1 stores raw, rebuilds here AND at next boot).
408        fresh.normalize_root = self.normalize_root.clone();
409        for (spec, entry, input) in &loads {
410            if let Err(e) = fresh.load_raw(spec, entry, input).await {
411                tracing::warn!("plugin {spec} reload after respawn failed: {e:#}");
412            }
413        }
414        *self = fresh;
415        Ok(())
416    }
417
418    /// Child pid (test/diag: force-kill to prove respawn).
419    pub fn child_pid(&self) -> u32 {
420        self.child.id().unwrap_or(0)
421    }
422
423    pub async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
424        self.ensure_alive().await?;
425        self.request_raw(method, params).await
426    }
427
428    /// Unguarded RPC (respawn replay only — the fresh child is alive).
429    async fn request_raw(&mut self, method: &str, params: Value) -> Result<Value> {
430        let id = self
431            .next_id
432            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
433        let (tx, rx) = oneshot::channel();
434        self.pending.lock().insert(id, Pending { tx });
435        let msg = json!({"id": id, "method": method, "params": params});
436        let mut line = msg.to_string();
437        line.push('\n');
438        self.stdin.write_all(line.as_bytes()).await?;
439        self.stdin.flush().await?;
440        match tokio::time::timeout(RPC_TIMEOUT, rx).await {
441            Ok(Ok(res)) => res.map_err(|e| anyhow!("plugin host {method}: {e}")),
442            Ok(Err(_)) => Err(anyhow!("plugin host dropped response for {method}")),
443            Err(_) => {
444                self.pending.lock().remove(&id);
445                Err(anyhow!("plugin host {method} timed out (runaway hook?)"))
446            }
447        }
448    }
449
450    /// Load one plugin (v1 server-factory extraction happens host-side).
451    pub async fn load(&mut self, spec: &str, entry: &Path, input: &Value) -> Result<Vec<String>> {
452        self.ensure_alive().await?;
453        self.load_raw(spec, entry, input).await
454    }
455
456    /// Unguarded load (respawn replay only — fresh child is alive).
457    async fn load_raw(&mut self, spec: &str, entry: &Path, input: &Value) -> Result<Vec<String>> {
458        // D1: normalize for the RPC (CPU on spawn_blocking — A2 class); the
459        // RAW entry is what gets recorded for respawn replay (A1).
460        let root = self.normalize_root.clone();
461        let raw = entry.to_path_buf();
462        let (load_path, outcome) = tokio::task::spawn_blocking(move || {
463            crate::normalize::normalize_or_raw_sync(root.as_deref(), &raw)
464        })
465        .await
466        .map_err(|e| anyhow!("normalize task: {e}"))?;
467        ocserve_metrics::labeled_counter(
468            "ocserve_plugin_normalize_total",
469            &format!("result=\"{}\"", outcome.label()),
470            1,
471        );
472        match &outcome {
473            crate::normalize::Outcome::Built {
474                path,
475                ms,
476                beside,
477                rss_before_kb,
478                rss_after_kb,
479            } => tracing::info!(
480                "plugin normalize {spec}: built {} ({}) in {ms}ms rss {rss_before_kb}→{rss_after_kb}kB",
481                path.display(),
482                if *beside { "beside-entry" } else { "data-dir" }
483            ),
484            crate::normalize::Outcome::Fallback { err, .. } => {
485                tracing::warn!("plugin normalize {spec} failed, loading raw entry: {err}")
486            }
487            _ => {}
488        }
489        // server/directory context defaults from spawn (input may omit them)
490        let mut input = input.clone();
491        if input
492            .get("serverUrl")
493            .and_then(|v| v.as_str())
494            .unwrap_or("")
495            .is_empty()
496        {
497            input["serverUrl"] = json!(self.server.0);
498        }
499        if input
500            .get("directory")
501            .and_then(|v| v.as_str())
502            .unwrap_or("")
503            .is_empty()
504        {
505            input["directory"] = json!(self.server.1);
506        }
507        let params = json!({
508            "spec": spec,
509            "entry": load_path.to_string_lossy(),
510            "input": input,
511            "options": Value::Null,
512        });
513        let res = self.request_raw("load", params).await?;
514        let hooks: Vec<String> = res["hooks"]
515            .as_array()
516            .map(|a| {
517                a.iter()
518                    .filter_map(|h| h.as_str().map(String::from))
519                    .collect()
520            })
521            .unwrap_or_default();
522        self.statuses.lock().insert(
523            spec.to_string(),
524            json!({"ok": true, "hooks": hooks, "id": res["id"]}),
525        );
526        self.loads
527            .push((spec.to_string(), entry.to_path_buf(), input));
528        Ok(hooks)
529    }
530
531    /// v1 trigger semantics: sequential hooks mutate `output` in place.
532    pub async fn trigger(&mut self, name: &str, input: Value, mut output: Value) -> Result<Value> {
533        let params = json!({"name": name, "input": input, "output": output});
534        let res = self.request("trigger", params).await?;
535        if res.is_object() {
536            output = res;
537        }
538        Ok(output)
539    }
540
541    /// v1 event delivery (plugin/index.ts:255-259): per-plugin
542    /// `hooks["event"]({event})`. Returns host delivery count.
543    pub async fn emit_event(&mut self, event: Value) -> Result<Value> {
544        self.request("event", json!({"event": event})).await
545    }
546
547    pub async fn config(&mut self, cfg: Value) -> Result<Value> {
548        self.request("config", json!({"config": cfg})).await
549    }
550
551    pub fn statuses(&self) -> Value {
552        let mut out = serde_json::Map::new();
553        for (spec, v) in self.statuses.lock().iter() {
554            out.insert(spec.clone(), v.clone());
555        }
556        Value::Object(out)
557    }
558
559    pub async fn shutdown(&mut self) {
560        let _ = self.request("dispose", json!({})).await;
561        let _ = self.child.start_kill();
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568
569    #[test]
570    fn strip_version_cases() {
571        assert_eq!(strip_version("context-mode"), "context-mode");
572        assert_eq!(strip_version("context-mode@latest"), "context-mode");
573        assert_eq!(
574            strip_version("@cortexkit/opencode-magic-context@latest"),
575            "@cortexkit/opencode-magic-context"
576        );
577        assert_eq!(
578            strip_version("@iam-brain/opencode-codex-auth@latest"),
579            "@iam-brain/opencode-codex-auth"
580        );
581    }
582
583    #[test]
584    fn entry_from_package_shapes() {
585        let dir = tempfile::tempdir().unwrap();
586        // exports["."] string
587        std::fs::write(
588            dir.path().join("package.json"),
589            r#"{"exports": {".": "./dist/index.js"}}"#,
590        )
591        .unwrap();
592        std::fs::create_dir(dir.path().join("dist")).unwrap();
593        std::fs::write(dir.path().join("dist/index.js"), "//").unwrap();
594        let e = entry_from_package(&dir.path().join("package.json"), dir.path(), "x")
595            .expect("exports dot");
596        assert!(e.ends_with("dist/index.js"));
597        // main fallback
598        std::fs::write(
599            dir.path().join("package.json"),
600            r#"{"main": "./lib/main.js"}"#,
601        )
602        .unwrap();
603        std::fs::create_dir(dir.path().join("lib")).unwrap();
604        std::fs::write(dir.path().join("lib/main.js"), "//").unwrap();
605        let e =
606            entry_from_package(&dir.path().join("package.json"), dir.path(), "x").expect("main");
607        assert!(e.ends_with("lib/main.js"));
608    }
609
610    #[tokio::test]
611    async fn sidecar_load_trigger_roundtrip() -> anyhow::Result<()> {
612        if !runtime_available() {
613            panic!(
614                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
615                crate::plugin_runtime().program()
616            );
617        }
618        let dir = tempfile::tempdir().unwrap();
619        // synthetic v1 plugin: PluginModule.server factory + mutating hook
620        std::fs::write(
621            dir.path().join("plug.mjs"),
622            r#"
623export const PluginModule = {
624  id: "synthetic",
625  server: async () => ({
626    "tool.execute.after": async (input, output) => { output.seen = input.tool; },
627    "chat.message": async (input, output) => { output.touched = true; },
628    "event": async (payload) => {
629      if (!payload.event || !payload.event.type) throw new Error("bad event shape");
630      if (payload.event.type === "boom.type") throw new Error("event boom");
631    },
632  }),
633};
634export default PluginModule.server;
635"#,
636        )
637        .unwrap();
638        let host = materialize_host(&dir.path().join("host"))?;
639        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work")
640            .await
641            .expect("spawn node");
642        let ping = sc.request("ping", json!({})).await.expect("ping");
643        assert_eq!(ping, "pong");
644
645        let input =
646            json!({"directory": "/work", "projectID": "global", "serverUrl": "http://127.0.0.1:9"});
647        let hooks = sc
648            .load("synthetic", &dir.path().join("plug.mjs"), &input)
649            .await
650            .expect("load");
651        assert_eq!(
652            hooks,
653            vec![
654                "tool.execute.after".to_string(),
655                "chat.message".to_string(),
656                "event".to_string()
657            ],
658            "hook names registered in declaration order"
659        );
660
661        // trigger mutates output in place (v1 semantics)
662        let out = sc
663            .trigger(
664                "tool.execute.after",
665                json!({"tool": "write", "args": {"filePath": "/x"}}),
666                json!({}),
667            )
668            .await
669            .expect("trigger");
670        assert_eq!(
671            out["seen"], "write",
672            "hook observed input and mutated output"
673        );
674        // unregistered hook name → output unchanged
675        let out2 = sc
676            .trigger("permission.ask", json!({}), json!({"keep": 1}))
677            .await
678            .expect("trigger2");
679        assert_eq!(out2["keep"], 1);
680
681        // v1 event delivery (plugin/index.ts:255-259): hooks["event"]
682        // receives {event:{id,type,properties}}; shape-asserting fixture
683        // only succeeds if the wrapper is exact (delivered counts non-
684        // throwing hooks), and a throwing event hook fails open.
685        let ev = sc
686            .emit_event(json!({"id": "e1", "type": "session.created", "properties": {}}))
687            .await
688            .expect("emit_event");
689        assert_eq!(ev["delivered"], 1, "event hook must receive exact shape");
690        let ev2 = sc
691            .emit_event(json!({"id": "e2", "type": "boom.type", "properties": {}}))
692            .await
693            .expect("emit_event fail-open");
694        assert_eq!(ev2["delivered"], 0, "throwing event hook must not count");
695
696        let st = sc.statuses();
697        assert_eq!(st["synthetic"]["ok"], true);
698        assert_eq!(st["synthetic"]["hooks"][0], "tool.execute.after");
699
700        sc.shutdown().await;
701        Ok(())
702    }
703
704    #[tokio::test]
705    async fn sidecar_respawns_after_death_and_reloads_plugins() -> anyhow::Result<()> {
706        if !runtime_available() {
707            panic!(
708                "plugin-runtime binary ({}) required for plugin-host tests (M4b environment gate)",
709                crate::plugin_runtime().program()
710            );
711        }
712        let dir = tempfile::tempdir().unwrap();
713        std::fs::write(
714            dir.path().join("plug.mjs"),
715            r#"
716export const PluginModule = {
717  id: "reaper",
718  server: async () => ({
719    "chat.message": async (_i, output) => { output.alive = true; },
720  }),
721};
722export default PluginModule.server;
723"#,
724        )
725        .unwrap();
726        let host = materialize_host(&dir.path().join("host"))?;
727        let mut sc = Sidecar::spawn(&host, "http://127.0.0.1:9", "/work").await?;
728        sc.load("reaper", &dir.path().join("plug.mjs"), &json!({}))
729            .await
730            .expect("load");
731        let pid = sc.child_pid();
732        // force-kill the child (the live OOM class: sidecar dies, hooks
733        // silently broken-piped until a respawn guard exists)
734        std::process::Command::new("kill")
735            .arg("-9")
736            .arg(pid.to_string())
737            .status()
738            .expect("kill -9");
739        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
740
741        // next RPC must respawn + replay loads + deliver the mutation
742        let out = sc
743            .trigger("chat.message", json!({"sessionID": "s"}), json!({}))
744            .await
745            .expect("trigger after respawn");
746        assert_eq!(out["alive"], true, "hook must fire after respawn");
747        assert_ne!(sc.child_pid(), pid, "child process must be replaced");
748        let st = sc.statuses();
749        assert_eq!(
750            st["reaper"]["ok"], true,
751            "previously loaded plugins must be reloaded"
752        );
753        sc.shutdown().await;
754        Ok(())
755    }
756
757    /// Test environment gate: the ACTUAL runtime (bun preferred) must exist.
758    fn runtime_available() -> bool {
759        crate::which(crate::plugin_runtime().program()).is_some()
760    }
761}
762
763#[cfg(test)]
764mod runtime_selection_tests {
765    /// `OCSERVE_PLUGIN_RUNTIME` forces the runtime (lab A/B control);
766    /// unset/unknown → bun-if-present else node. Env is process-local and
767    /// restored (this file is the only env mutator in its own process).
768    #[test]
769    fn runtime_override_and_default_preference() {
770        let has_bun = crate::which("bun").is_some();
771        let has_node = crate::which("node").is_some();
772        if !has_node {
773            panic!("node required for the fallback leg (test environment gate)");
774        }
775
776        // SAFETY: single-threaded env mutation, restored below.
777        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "node") };
778        assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
779
780        if has_bun {
781            unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "bun") };
782            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Bun);
783            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
784            assert_eq!(
785                crate::plugin_runtime(),
786                crate::PluginRuntime::Bun,
787                "bun present + no override → bun preferred (upstream fidelity)"
788            );
789        } else {
790            unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
791            assert_eq!(crate::plugin_runtime(), crate::PluginRuntime::Node);
792        }
793
794        // unknown value falls through to preference, never panics
795        unsafe { std::env::set_var("OCSERVE_PLUGIN_RUNTIME", "deno") };
796        let _ = crate::plugin_runtime();
797        unsafe { std::env::remove_var("OCSERVE_PLUGIN_RUNTIME") };
798    }
799}
800
801#[cfg(test)]
802mod oom_wrapper_tests {
803    /// A3 proof: the spawn wrapper makes the CHILD report adj=500 so a
804    /// memcg OOM kill takes the child (respawnable) — not the main service.
805    #[test]
806    fn wrapper_raises_child_oom_score_adj() {
807        let out = std::process::Command::new("sh")
808            .arg("-c")
809            .arg(crate::OOM_CHILD_WRAPPER)
810            .arg("sh")
811            .arg("cat")
812            .arg("/proc/self/oom_score_adj")
813            .output()
814            .expect("wrapper spawns");
815        assert!(
816            out.status.success(),
817            "wrapper failed: {}",
818            String::from_utf8_lossy(&out.stderr)
819        );
820        assert_eq!(
821            String::from_utf8_lossy(&out.stdout).trim(),
822            "500",
823            "child must run at adj=500"
824        );
825    }
826}