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