Skip to main content

ocserve_plugin/
normalize.rs

1//! Plugin entry normalization (D1 — bench/normalizer-spike/STRESS-RESULTS.md
2//! §Phase 3 dispositions; executable spec: bench/normalizer-spike/D1-PLAN.md).
3//!
4//! One self-contained ESM output per plugin entry, loadable with zero
5//! runtime-specific patches on bun/node/deno (spike K1–K7), cached by
6//! content hash, emitted either beside the entry (bundle still has
7//! runtime-resolved bare specifiers → needs node_modules ancestry — the
8//! K4 case) or under ocserve's own `normalized/` tree (fully self-contained
9//! → zero writes into user repos; D1-PLAN scanner rule).
10//!
11//! Every failure degrades to the raw entry (loud in the log, metric
12//! `error`), never worse than today's behavior. `OCSERVE_PLUGIN_NORMALIZE=0`
13//! skips before rolldown is ever constructed (the panic=abort residual,
14//! A3). Callers: `Sidecar::load_raw` (boot AND respawn replay).
15
16use anyhow::{Context, Result, bail};
17use sha2::{Digest, Sha256};
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20
21/// Bump when bundling/alias/scanner behavior changes → all caches rebuild.
22const NORMALIZER_VERSION: &str = "normalize-v1";
23/// K5b dual-runtime sqlite shim, inlined into every bundle as a virtual
24/// module (bun:sqlite → native on bun, computed node:sqlite elsewhere —
25/// spike K5b; static node:sqlite would fail bun's graph link).
26const SHIM_SRC: &str = include_str!("host/shim-dual-sqlite.mjs");
27/// Crash-orphaned tmp files older than this are removed best-effort.
28const STALE_TMP_SECS: u64 = 3600;
29
30/// Result of one normalize attempt. The returned `PathBuf` (tuple) is what
31/// the caller must load; the raw entry stays the replay/canonical source.
32#[derive(Debug)]
33pub enum Outcome {
34    /// Content hash matched an existing complete output.
35    Warm(PathBuf),
36    /// Freshly bundled + written. `beside` = destination class (D1-PLAN).
37    Built {
38        path: PathBuf,
39        ms: u128,
40        beside: bool,
41        rss_before_kb: i64,
42        rss_after_kb: i64,
43    },
44    /// Kill switch or no normalize root configured → raw.
45    Skipped(PathBuf),
46    /// Normalize failed for a real reason → caller loads raw (A: never
47    /// worse than today). `path` is always the raw entry.
48    Fallback { path: PathBuf, err: String },
49    /// Entry already is a normalized output (double-normalize guard, A11).
50    Passthrough(PathBuf),
51}
52
53impl Outcome {
54    /// Metric label for `ocserve_plugin_normalize_total{result=…}`.
55    pub fn label(&self) -> &'static str {
56        match self {
57            Outcome::Warm(_) => "warm",
58            Outcome::Built { .. } => "built",
59            Outcome::Skipped(_) => "disabled",
60            Outcome::Fallback { .. } => "error",
61            Outcome::Passthrough(_) => "passthrough",
62        }
63    }
64}
65
66// ---------------------------------------------------------------------------
67// Scanner (D1-PLAN): classifies EMITTED code text. rolldown's
68// OutputChunk.imports/dynamic_imports provably MISS non-analyzable dynamic
69// imports (rolldown src/ast_scanner/impl_visit.rs:241 "No import record -
70// either @vite-ignore or non-static dynamic import"), so metadata alone
71// would misclassify magic-context's computed transformers import as clean →
72// broken plugin. Unknown parse forms err TOWARD needs-ancestry (false
73// positives cost tidiness only; false negatives are impossible by
74// construction).
75// ---------------------------------------------------------------------------
76
77/// `true` = the bundle still resolves something at runtime against its own
78/// location → must be emitted beside the entry (node_modules ancestry).
79pub fn needs_ancestry(code: &str) -> bool {
80    let consts = const_map(code);
81    for spec in specifiers(code, &consts) {
82        match spec {
83            // unresolvable argument (bare identifier / template with ${}) →
84            // conservative: unknown ⇒ needs ancestry
85            None => return true,
86            Some(s) if !clean_spec(&s) => return true,
87            Some(_) => {}
88        }
89    }
90    false
91}
92
93/// Runtime-resolved import specifiers: `Some(parsed)`, `None` = could not
94/// determine statically. Word-boundary correct (a keyword token must not be
95/// glued to identifier chars on either side — a naive offset check here
96/// would self-defeat and classify every bundle as needs-ancestry).
97fn specifiers(code: &str, consts: &HashMap<String, String>) -> Vec<Option<String>> {
98    let mut out = Vec::new();
99    let b = code.as_bytes();
100    let n = b.len();
101    let idc = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'$';
102    let boundary = |start: usize, len: usize| -> bool {
103        (start == 0 || !idc(b[start - 1])) && b.get(start + len).map(|&c| !idc(c)).unwrap_or(true)
104    };
105    let is_quote = |c: u8| c == b'"' || c == b'\'' || c == b'`';
106
107    for (kw, len) in [("import", 6usize), ("require", 7usize), ("from", 4usize)] {
108        let mut i = 0;
109        while let Some(rel) = code[i..].find(kw) {
110            let start = i + rel;
111            i = start + len;
112            if !boundary(start, len) {
113                continue;
114            }
115            let mut j = start + len;
116            while j < n && b[j].is_ascii_whitespace() {
117                j += 1;
118            }
119            if j >= n {
120                continue;
121            }
122            if b[j] == b'(' {
123                // dynamic import( / require( — expression position: an
124                // unresolvable argument is unknown → conservative (None).
125                // `from` is NOT call syntax (`Array.from(x)` is a method).
126                if kw != "from" {
127                    j += 1;
128                    while j < n && b[j].is_ascii_whitespace() {
129                        j += 1;
130                    }
131                    out.push(parse_arg(code, j, consts));
132                }
133            } else if is_quote(b[j]) {
134                // Static specifier position (`from "…"`, side-effect import):
135                // ESM specifiers cannot contain raw newlines or `${}`, so a
136                // parse failure means this `from`/`import` token is string
137                // CONTENT in source text, not an import statement → skip.
138                // (Pushing None here would false-dirty every clean bundle
139                // that mentions `from "` inside an error message.)
140                let after_dot = start > 0 && b[start - 1] == b'.';
141                if ((kw == "from" && !after_dot) || kw == "import")
142                    && let Some(sp) = parse_arg(code, j, consts)
143                {
144                    out.push(Some(sp));
145                }
146                // bare `require` without call parens is not an import
147            }
148        }
149    }
150    out
151}
152
153/// Parse an import argument starting at `j` (the quote / backtick / ident).
154fn parse_arg(code: &str, j: usize, consts: &HashMap<String, String>) -> Option<String> {
155    let b = code.as_bytes();
156    match b.get(j)? {
157        q @ (b'"' | b'\'') => read_quoted(code, j + 1, *q).map(|(s, _)| s),
158        b'`' => {
159            let (s, end) = read_quoted(code, j + 1, b'`')?;
160            if s.contains("${") {
161                None // template with substitution → unknown → conservative
162            } else {
163                let _ = end;
164                Some(s)
165            }
166        }
167        c if c.is_ascii_alphabetic() || *c == b'_' || *c == b'$' => {
168            // identifier argument → one-level const resolution
169            let mut k = j;
170            while k < b.len() && (b[k].is_ascii_alphanumeric() || b[k] == b'_' || b[k] == b'$') {
171                k += 1;
172            }
173            consts.get(&code[j..k]).cloned()
174        }
175        _ => None, // computed expression → unknown → conservative
176    }
177}
178
179/// Read a quoted literal from `start` (after the opening quote) up to the
180/// next unescaped matching quote. Returns (value, index_after_close).
181fn read_quoted(code: &str, start: usize, quote: u8) -> Option<(String, usize)> {
182    let b = code.as_bytes();
183    let mut k = start;
184    let mut val = String::new();
185    while k < b.len() {
186        match b[k] {
187            c if c == quote => return Some((val, k + 1)),
188            b'\\' => {
189                k += 1;
190                if k < b.len() {
191                    val.push(b[k] as char);
192                    k += 1;
193                }
194            }
195            c => {
196                val.push(c as char);
197                k += 1;
198            }
199        }
200    }
201    None // unterminated → unknown
202}
203
204/// One-level constant table: `const NAME = "lit"` / backtick-literal-without-`${`.
205/// Word-boundary correct (`constx` is not a declaration).
206fn const_map(code: &str) -> HashMap<String, String> {
207    let mut m = HashMap::new();
208    let b = code.as_bytes();
209    let n = b.len();
210    let idc = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'$';
211    for kw in ["const", "let", "var"] {
212        let len = kw.len();
213        let mut i = 0;
214        while let Some(rel) = code[i..].find(kw) {
215            let at = i + rel;
216            i = at + len;
217            let before_ok = at == 0 || !idc(b[at - 1]);
218            let after_ok = b.get(at + len).map(|&c| !idc(c)).unwrap_or(true);
219            if !before_ok || !after_ok {
220                continue;
221            }
222            let mut k = at + len;
223            while k < n && b[k].is_ascii_whitespace() {
224                k += 1;
225            }
226            let name_start = k;
227            while k < n && idc(b[k]) {
228                k += 1;
229            }
230            if k == name_start {
231                continue;
232            }
233            let name = code[name_start..k].to_string();
234            let mut ws = k;
235            while ws < n && b[ws].is_ascii_whitespace() {
236                ws += 1;
237            }
238            if ws >= n || b[ws] != b'=' {
239                continue;
240            }
241            ws += 1;
242            while ws < n && b[ws].is_ascii_whitespace() {
243                ws += 1;
244            }
245            if ws >= n {
246                continue;
247            }
248            let q = b[ws];
249            if (q == b'"' || q == b'\'')
250                && let Some((v, _)) = read_quoted(code, ws + 1, q)
251            {
252                m.entry(name).or_insert(v);
253            } else if q == b'`'
254                && let Some((v, _)) = read_quoted(code, ws + 1, b'`')
255                && !v.contains("${")
256            {
257                m.entry(name).or_insert(v);
258            }
259        }
260    }
261    m
262}
263
264/// A specifier that resolves WITHOUT the entry's node_modules ancestry.
265fn clean_spec(s: &str) -> bool {
266    if s.is_empty() {
267        return true;
268    }
269    if s.starts_with("./") || s.starts_with("../") || s.starts_with('/') {
270        return true;
271    }
272    if s.starts_with("file:") || s.starts_with("data:") {
273        return true;
274    }
275    if s.starts_with("node:") || s.starts_with("bun:") {
276        return true;
277    }
278    let first = s.split('/').next().unwrap_or("");
279    is_node_builtin(first)
280}
281
282/// Node.js builtin module names (first path segment). Missing an exotic one
283/// errs toward needs-ancestry (conservative — only affects destination).
284fn is_node_builtin(first: &str) -> bool {
285    matches!(
286        first,
287        "assert"
288            | "async_hooks"
289            | "buffer"
290            | "child_process"
291            | "cluster"
292            | "console"
293            | "constants"
294            | "crypto"
295            | "dgram"
296            | "diagnostics_channel"
297            | "dns"
298            | "events"
299            | "fs"
300            | "http"
301            | "http2"
302            | "https"
303            | "inspector"
304            | "module"
305            | "net"
306            | "os"
307            | "path"
308            | "perf_hooks"
309            | "process"
310            | "punycode"
311            | "querystring"
312            | "readline"
313            | "stream"
314            | "string_decoder"
315            | "sys"
316            | "timers"
317            | "tls"
318            | "tty"
319            | "url"
320            | "util"
321            | "v8"
322            | "vm"
323            | "wasi"
324            | "worker_threads"
325            | "zlib"
326    )
327}
328
329// ---------------------------------------------------------------------------
330// Bundling (spike K1 — one chunk, treeshake off, bun:sqlite alias w/ guard)
331// ---------------------------------------------------------------------------
332
333/// Bundle one entry to a single ESM chunk. Errors are diagnostics, never
334/// panics (spike S4: syntax/cycle/garbage/huge all → Err).
335fn bundle(entry: &Path) -> Result<String> {
336    use rolldown::plugin::{
337        HookLoadArgs, HookLoadOutput, HookResolveIdArgs, HookResolveIdOutput, HookUsage, Plugin,
338        PluginContext, SharedLoadPluginContext,
339    };
340    use rolldown::{
341        Bundler, BundlerOptions, InputItem, LogLevel, OutputFormat, Platform, TreeshakeOptions,
342    };
343    use std::borrow::Cow;
344    use std::future::Future;
345
346    const SHIM_ID: &str = "ocserve:bun-sqlite-shim";
347
348    #[derive(Debug)]
349    struct AliasBunSqlite {
350        shim_src: &'static str,
351    }
352
353    impl Plugin for AliasBunSqlite {
354        fn name(&self) -> Cow<'static, str> {
355            Cow::Borrowed("ocserve-bun-sqlite-alias")
356        }
357
358        fn resolve_id(
359            &self,
360            _ctx: &PluginContext,
361            args: &HookResolveIdArgs<'_>,
362        ) -> impl Future<Output = rolldown::plugin::HookResolveIdReturn> + Send {
363            let hit = args.specifier == "bun:sqlite";
364            // Guard: the shim's own `import("bun:"+"sqlite")` may be
365            // constant-folded back to a literal — it must stay a RUNTIME
366            // import (catchable off-bun), never aliased to itself.
367            let from_shim = args.importer == Some(SHIM_ID);
368            async move {
369                if hit && from_shim {
370                    Ok(Some(HookResolveIdOutput {
371                        id: "bun:sqlite".into(),
372                        external: Some(rolldown_common::ResolvedExternal::Bool(true)),
373                        ..Default::default()
374                    }))
375                } else if hit {
376                    Ok(Some(HookResolveIdOutput::from_id(SHIM_ID)))
377                } else {
378                    Ok(None)
379                }
380            }
381        }
382
383        fn load(
384            &self,
385            _ctx: SharedLoadPluginContext,
386            args: &HookLoadArgs<'_>,
387        ) -> impl Future<Output = rolldown::plugin::HookLoadReturn> + Send {
388            let hit = args.id == SHIM_ID;
389            let code = self.shim_src;
390            async move {
391                if hit {
392                    Ok(Some(HookLoadOutput {
393                        code: code.into(),
394                        map: None,
395                        side_effects: None,
396                        module_type: Some(rolldown_common::ModuleType::Js),
397                    }))
398                } else {
399                    Ok(None)
400                }
401            }
402        }
403
404        fn register_hook_usage(&self) -> HookUsage {
405            HookUsage::ResolveId | HookUsage::Load
406        }
407    }
408
409    let opts = BundlerOptions {
410        input: Some(vec![InputItem {
411            name: Some("plugin".to_string()),
412            import: entry.to_string_lossy().into_owned(),
413        }]),
414        cwd: entry.parent().map(Path::to_path_buf),
415        format: Some(OutputFormat::Esm),
416        platform: Some(Platform::Node),
417        // D1-PLAN: side effects ARE the plugin registration contract.
418        treeshake: TreeshakeOptions::Boolean(false),
419        // Rolldown's default is `DeadCodeEliminationOnly`, which still runs the
420        // oxc MINIFIER — and oxc's compressor carries
421        // `debug_assert!(false, "Ran loop more than 10 times.")`. A real plugin
422        // bundle trips it: the normalize task panicked and the plugin was
423        // silently disabled (`ok:false`), while the same plugin loads raw
424        // (`ok:true, hooks:["event"]`), reproduced with rolldown 1.3.1 AND
425        // 1.3.2 so it is not a dependency upgrade. In a `panic = "abort"`
426        // release that would kill the process. Minification of a bundled
427        // plugin buys nothing (it is not shipped over the wire), so turn it
428        // off entirely.
429        minify: Some(rolldown::RawMinifyOptions::Bool(false)),
430        log_level: Some(LogLevel::Warn),
431        ..Default::default()
432    };
433    let mut bundler = Bundler::with_plugins(
434        opts,
435        vec![rolldown::plugin::__inner::Pluginable::new_shared(
436            AliasBunSqlite { shim_src: SHIM_SRC },
437        )],
438    )
439    .map_err(|e| anyhow::anyhow!("bundler init: {e:?}"))?;
440
441    // CPU-bound work runs on our own current-thread runtime; the caller
442    // (load_raw) has already moved us onto spawn_blocking (A2 class).
443    let rt = tokio::runtime::Builder::new_current_thread()
444        .enable_all()
445        .build()
446        .context("normalize runtime")?;
447    let out = rt
448        .block_on(bundler.generate())
449        .map_err(|e| anyhow::anyhow!("{e:?}"))?;
450    for w in &out.warnings {
451        tracing::warn!("normalize bundler warning: {w:?}");
452    }
453    let mut chunks = Vec::new();
454    for a in &out.assets {
455        if let rolldown_common::Output::Chunk(c) = a {
456            chunks.push(c);
457        }
458    }
459    if chunks.len() != 1 {
460        bail!(
461            "expected exactly 1 chunk, got {} ({:?})",
462            chunks.len(),
463            chunks
464                .iter()
465                .map(|c| c.filename.as_str())
466                .collect::<Vec<_>>()
467        );
468    }
469    Ok(chunks[0].code.clone())
470}
471
472// ---------------------------------------------------------------------------
473// Cache + atomic writes
474// ---------------------------------------------------------------------------
475
476fn content_hash(entry: &Path) -> Result<String> {
477    let mut h = Sha256::new();
478    let bytes = std::fs::read(entry).with_context(|| format!("read {}", entry.display()))?;
479    h.update(bytes);
480    h.update([0xff]);
481    h.update(SHIM_SRC.as_bytes());
482    h.update(NORMALIZER_VERSION.as_bytes());
483    // sha2 0.11 output no longer implements LowerHex; hex-encode explicitly.
484    Ok(hex::encode(h.finalize()))
485}
486
487/// Data-dir subdirectory for an entry: path-hash (16 hex chars).
488fn path_key(entry: &Path) -> String {
489    let mut h = Sha256::new();
490    h.update(entry.to_string_lossy().as_bytes());
491    hex::encode(h.finalize())[..16].to_string()
492}
493
494fn warm(out: &Path, want: &str) -> bool {
495    let hash_path = hash_path_of(out);
496    let Ok(h) = std::fs::read_to_string(&hash_path) else {
497        return false;
498    };
499    h.trim() == want && std::fs::metadata(out).map(|m| m.len() > 0).unwrap_or(false)
500}
501
502fn hash_path_of(out: &Path) -> PathBuf {
503    let mut s = out.as_os_str().to_os_string();
504    s.push(".hash");
505    PathBuf::from(s)
506}
507
508/// Write data via pid-unique hidden tmp + rename (STORAGE crash discipline).
509/// Guard rule 8 bans direct `fs::write` to final normalized paths.
510fn atomic_write(dest: &Path, data: &str) -> Result<()> {
511    let dir = dest.parent().context("dest has no parent")?;
512    std::fs::create_dir_all(dir).with_context(|| format!("mkdir {}", dir.display()))?;
513    let name = dest
514        .file_name()
515        .context("dest has no name")?
516        .to_string_lossy()
517        .into_owned();
518    let tmp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
519    std::fs::write(&tmp, data).with_context(|| format!("write {}", tmp.display()))?;
520    std::fs::rename(&tmp, dest).with_context(|| format!("rename {}", dest.display()))?;
521    Ok(())
522}
523
524/// Remove crash-orphaned `.{name}.*.tmp` older than STALE_TMP_SECS.
525fn sweep_stale_tmp(dest: &Path) {
526    let (Some(dir), Some(name)) = (dest.parent(), dest.file_name()) else {
527        return;
528    };
529    let prefix = format!(".{}.", name.to_string_lossy());
530    let Ok(rd) = std::fs::read_dir(dir) else {
531        return;
532    };
533    for e in rd.flatten() {
534        let fname = e.file_name().to_string_lossy().into_owned();
535        if fname.starts_with(&prefix) && fname.ends_with(".tmp") {
536            let stale = e
537                .metadata()
538                .ok()
539                .and_then(|m| m.modified().ok())
540                .and_then(|t| t.elapsed().ok())
541                .map(|age| age.as_secs() > STALE_TMP_SECS)
542                .unwrap_or(false);
543            if stale {
544                let _ = std::fs::remove_file(e.path());
545            }
546        }
547    }
548}
549
550fn rss_kb() -> i64 {
551    std::fs::read_to_string("/proc/self/status")
552        .ok()
553        .and_then(|s| {
554            s.lines()
555                .find(|l| l.starts_with("VmRSS:"))
556                .and_then(|l| l.split_whitespace().nth(1))
557                .and_then(|v| v.parse().ok())
558        })
559        .unwrap_or(-1)
560}
561
562// ---------------------------------------------------------------------------
563// Entry point
564// ---------------------------------------------------------------------------
565
566/// Normalize `entry` for loading. Returns (path-to-load, outcome). On any
567/// failure the raw entry is returned with `Fallback` — the load proceeds
568/// exactly as it does today (never worse than raw; D1-PLAN).
569pub fn normalize_or_raw_sync(root: Option<&Path>, entry: &Path) -> (PathBuf, Outcome) {
570    let raw = entry.to_path_buf();
571    // A11: never re-normalize an output.
572    if entry
573        .file_name()
574        .map(|n| n.to_string_lossy().ends_with(".normalized.mjs"))
575        .unwrap_or(false)
576    {
577        return (raw.clone(), Outcome::Passthrough(raw));
578    }
579    let Some(root) = root else {
580        // No root configured (tests, sidecars without it) → today's behavior.
581        return (raw.clone(), Outcome::Skipped(raw));
582    };
583    // A3: kill switch checked BEFORE rolldown exists anywhere.
584    if matches!(
585        std::env::var("OCSERVE_PLUGIN_NORMALIZE").as_deref(),
586        Ok("0")
587    ) {
588        return (raw.clone(), Outcome::Skipped(raw));
589    }
590
591    let work = match entry.canonicalize() {
592        Ok(w) => w,
593        Err(e) => {
594            return (
595                raw.clone(),
596                Outcome::Fallback {
597                    path: raw,
598                    err: format!("canonicalize {}: {e}", entry.display()),
599                },
600            );
601        }
602    };
603    let hash = match content_hash(&work) {
604        Ok(h) => h,
605        Err(e) => {
606            return (
607                raw.clone(),
608                Outcome::Fallback {
609                    path: raw,
610                    err: format!("{e:#}"),
611                },
612            );
613        }
614    };
615
616    let stem = work
617        .file_stem()
618        .map(|s| s.to_string_lossy().into_owned())
619        .unwrap_or_else(|| "index".into());
620    let out_name = format!("{stem}.normalized.mjs");
621    let beside = work.with_file_name(&out_name);
622    let data_dir = root.join(path_key(&work));
623    let data_out = data_dir.join(&out_name);
624    let hash_file = root.join(path_key(&work)).join(format!("{out_name}.hash"));
625
626    // Warm gate checks BOTH candidate locations (destination depends on the
627    // output, which only exists after a build — D1-PLAN).
628    for c in [&beside, &data_out] {
629        if warm(c, &hash) {
630            return (c.clone(), Outcome::Warm(c.clone()));
631        }
632    }
633
634    // Build (CPU — caller has us on spawn_blocking).
635    let rss_before = rss_kb();
636    let t0 = std::time::Instant::now();
637    let code = match bundle(&work) {
638        Ok(c) => c,
639        Err(e) => {
640            return (
641                raw.clone(),
642                Outcome::Fallback {
643                    path: raw,
644                    err: format!("bundle: {e:#}"),
645                },
646            );
647        }
648    };
649
650    // Destination rule (D1-PLAN conditional emit).
651    let needs = needs_ancestry(&code);
652    let (dest, other) = if needs {
653        (beside.clone(), Some(data_out.clone()))
654    } else {
655        (data_out.clone(), Some(beside.clone()))
656    };
657
658    if let Err(e) = atomic_write(&dest, &code) {
659        return (
660            raw.clone(),
661            Outcome::Fallback {
662                path: raw,
663                err: format!("write: {e:#}"),
664            },
665        );
666    }
667    // Hash AFTER the rename: any crash prefix leaves hash≠content → rebuild.
668    if let Err(e) = atomic_write(&hash_path_of(&dest), &hash) {
669        tracing::warn!("normalize hash write failed (will rebuild next boot): {e:#}");
670    }
671    // Stale opposite-location pair (destination flipped / spike leftovers):
672    // best-effort remove — these names are ocserve-derived, never user files.
673    if let Some(o) = other
674        && o != dest
675    {
676        let _ = std::fs::remove_file(&o);
677        let _ = std::fs::remove_file(hash_path_of(&o));
678    }
679    sweep_stale_tmp(&dest);
680    let _ = hash_file; // (path already handled via hash_path_of(dest))
681
682    (
683        dest.clone(),
684        Outcome::Built {
685            path: dest,
686            ms: t0.elapsed().as_millis(),
687            beside: needs,
688            rss_before_kb: rss_before,
689            rss_after_kb: rss_kb(),
690        },
691    )
692}
693
694// ---------------------------------------------------------------------------
695// Tests — every behavior test holds ENV_LOCK (kill-switch env is
696// process-global; guard-rule-7 class of race, same hazard).
697// ---------------------------------------------------------------------------
698#[cfg(test)]
699mod tests {
700    use super::*;
701
702    // parking_lot 0.13 removed the const_* constructors; `new` is const now.
703    static ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
704
705    /// M4b idiom: real-plugin tests exist only where the artifact exists.
706    fn real_entry(pkg: &str, rel: &str) -> Option<PathBuf> {
707        let home = std::env::var("HOME").ok()?;
708        let p = PathBuf::from(home).join(pkg).join(rel);
709        p.exists().then_some(p)
710    }
711
712    fn scratch() -> (PathBuf, PathBuf) {
713        let base = std::env::temp_dir().join(format!(
714            "ocserve-norm-test-{}-{:?}",
715            std::process::id(),
716            std::thread::current().id()
717        ));
718        let _ = std::fs::remove_dir_all(&base);
719        std::fs::create_dir_all(&base).unwrap();
720        let data = base.join("data");
721        std::fs::create_dir_all(&data).unwrap();
722        (base, data)
723    }
724
725    fn write_entry(base: &Path, name: &str, body: &str) -> PathBuf {
726        let p = base.join(name);
727        std::fs::write(&p, body).unwrap();
728        p
729    }
730
731    // ---- scanner controls (the conditional-emit oracle) ----
732
733    #[test]
734    fn scanner_real_magic_context_needs_ancestry() {
735        let Some(e) = real_entry(
736            ".cache/opencode/packages/@cortexkit/opencode-magic-context@latest/node_modules/@cortexkit/opencode-magic-context",
737            "dist/index.js",
738        ) else {
739            eprintln!("skip: magic-context not in opencode cache");
740            return;
741        };
742        let code = bundle(&e).expect("bundle magic-context");
743        assert!(
744            needs_ancestry(&code),
745            "computed @huggingface/transformers import MUST classify needs-ancestry \
746             (this is the ground truth that catches metadata-based scanners)"
747        );
748    }
749
750    #[test]
751    fn scanner_real_reliary8_is_clean() {
752        let home = std::env::var("HOME").unwrap();
753        let e = PathBuf::from(home).join("src/reliary8/opencode-plugin/dist/index.js");
754        if !e.exists() {
755            eprintln!("skip: reliary8 plugin absent");
756            return;
757        }
758        let code = bundle(&e).expect("bundle reliary8");
759        assert!(
760            !needs_ancestry(&code),
761            "reliary8 (builtins only) must be clean → data-dir emit, no repo writes"
762        );
763    }
764
765    #[test]
766    fn scanner_real_codex_auth_needs_ancestry() {
767        // Ground truth FLIPPED 2026-10-06 by evidence: codex-auth's
768        // getLockFunction() does `await import(specifier)` with specifier =
769        // "proper-lockfile" (its package.json dep) — a runtime-resolved
770        // BARE package → beside-entry emit is REQUIRED (cache ancestry).
771        // The first "clean" assumption was wrong; the scanner was right.
772        let Some(e) = real_entry(
773            ".cache/opencode/packages/@iam-brain/opencode-codex-auth@latest/node_modules/@iam-brain/opencode-codex-auth",
774            "dist/index.js",
775        ) else {
776            eprintln!("skip: codex-auth not in opencode cache");
777            return;
778        };
779        let code = bundle(&e).expect("bundle codex-auth");
780        assert!(
781            needs_ancestry(&code),
782            "codex-auth dynamically imports proper-lockfile at runtime"
783        );
784    }
785
786    #[test]
787    fn scanner_shim_identifier_stays_clean() {
788        // The K5b shim (inlined into every bun:sqlite bundle) does
789        // `await import(BUN_SPEC)` where `const BUN_SPEC = "bun:sqlite"`
790        // — virtual-module code is NOT folded at the call site (production
791        // evidence: magic-context output keeps the identifier). Staying
792        // clean REQUIRES const_map: gut it → None → false-dirty → any
793        // future path-plugin using bun:sqlite would pollute its repo.
794        let (base, _d) = scratch();
795        let e = write_entry(
796            &base,
797            "shimuser.js",
798            r#"import { Database } from "bun:sqlite";
799export default { Database };"#,
800        );
801        let code = bundle(&e).expect("bundle shim user");
802        assert!(
803            !needs_ancestry(&code),
804            "shim import(BUN_SPEC) must resolve via const_map to bun:sqlite (scheme-clean)"
805        );
806        let _ = std::fs::remove_dir_all(&base);
807    }
808
809    #[test]
810    fn scanner_synthetic_computed_import_needs_ancestry() {
811        let (base, _d) = scratch();
812        let e = write_entry(
813            &base,
814            "dyn.js",
815            r#"const pkg = "some-dep" + "-x";
816export default await import(pkg);"#,
817        );
818        let code = bundle(&e).expect("bundle synthetic dyn");
819        assert!(needs_ancestry(&code));
820        let _ = std::fs::remove_dir_all(&base);
821    }
822
823    #[test]
824    fn scanner_node_relative_const_are_clean() {
825        let (base, _d) = scratch();
826        std::fs::write(base.join("sib.js"), "export const x = 1;\n").unwrap();
827        // const via concat (real-bundle shape: rolldown keeps `import(P)`,
828        // folding the concat into `const P = "node:crypto"` — pure literals
829        // get inlined at the call and would bypass const_map entirely)
830        let e = write_entry(
831            &base,
832            "ok.js",
833            r#"import fs from "node:fs";
834import path2 from "path";
835import { x } from "./sib.js";
836const P = "node:" + "crypto";
837const dyn = await import(P);
838export default { fs, path2, x, dyn };"#,
839        );
840        let code = bundle(&e).expect("bundle clean fixture");
841        assert!(
842            !needs_ancestry(&code),
843            "node:/relative/builtin + const-resolved node: spec are clean"
844        );
845        let _ = std::fs::remove_dir_all(&base);
846    }
847
848    // ---- behavior (all under ENV_LOCK — env is process-global) ----
849
850    #[test]
851    fn warm_hash_skips_rebuild() {
852        let _g = ENV_LOCK.lock();
853        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
854        unsafe {
855            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
856        };
857        let (base, data) = scratch();
858        let e = write_entry(&base, "p.js", "export default 1;\n");
859        let (p1, o1) = normalize_or_raw_sync(Some(&data), &e);
860        assert!(matches!(o1, Outcome::Built { .. }), "first: {o1:?}");
861        let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
862        assert!(matches!(o2, Outcome::Warm(_)), "second: {o2:?}");
863        assert_eq!(p1, p2);
864        let _ = std::fs::remove_dir_all(&base);
865    }
866
867    #[test]
868    fn stale_entry_rebuilds() {
869        let _g = ENV_LOCK.lock();
870        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
871        unsafe {
872            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
873        };
874        let (base, data) = scratch();
875        let e = write_entry(&base, "p.js", "export default 1;\n");
876        let (_, o1) = normalize_or_raw_sync(Some(&data), &e);
877        assert!(matches!(o1, Outcome::Built { .. }));
878        std::fs::write(&e, "export default 2; // changed\n").unwrap();
879        let (_, o2) = normalize_or_raw_sync(Some(&data), &e);
880        assert!(matches!(o2, Outcome::Built { .. }), "changed: {o2:?}");
881        let _ = std::fs::remove_dir_all(&base);
882    }
883
884    #[test]
885    fn normalize_error_falls_back_to_raw() {
886        let _g = ENV_LOCK.lock();
887        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
888        unsafe {
889            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
890        };
891        let (base, data) = scratch();
892        let e = write_entry(&base, "bad.js", "import { from 'broken");
893        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
894        assert_eq!(p, e, "fallback path MUST be the raw entry");
895        assert!(matches!(o, Outcome::Fallback { .. }), "{o:?}");
896        let _ = std::fs::remove_dir_all(&base);
897    }
898
899    #[test]
900    fn kill_switch_disables_building() {
901        let _g = ENV_LOCK.lock();
902        let (base, data) = scratch();
903        let e = write_entry(&base, "p.js", "export default 1;\n");
904        // SAFETY: single env mutation under the shared lock, restored below.
905        unsafe { std::env::set_var("OCSERVE_PLUGIN_NORMALIZE", "0") };
906        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
907        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
908        unsafe {
909            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
910        };
911        assert_eq!(p, e);
912        assert!(matches!(o, Outcome::Skipped(_)), "{o:?}");
913        // proof of no-build: normalized dir stays empty
914        let built = std::fs::read_dir(&data).map(|d| d.count()).unwrap_or(0);
915        assert_eq!(built, 0, "kill switch must not construct outputs");
916        let _ = std::fs::remove_dir_all(&base);
917    }
918
919    #[test]
920    fn wipe_then_normalize_rebuilds() {
921        let _g = ENV_LOCK.lock();
922        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
923        unsafe {
924            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
925        };
926        let (base, data) = scratch();
927        let e = write_entry(&base, "p.js", "export default 1;\n");
928        let (p1, o1) = normalize_or_raw_sync(Some(&data), &e);
929        assert!(matches!(o1, Outcome::Built { .. }));
930        std::fs::remove_file(&p1).unwrap();
931        std::fs::remove_file(hash_path_of(&p1)).unwrap();
932        let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
933        assert!(matches!(o2, Outcome::Built { .. }), "after wipe: {o2:?}");
934        assert!(p2.exists());
935        let _ = std::fs::remove_dir_all(&base);
936    }
937
938    #[test]
939    fn suffix_guard_passthrough() {
940        let _g = ENV_LOCK.lock();
941        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
942        unsafe {
943            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
944        };
945        let (base, data) = scratch();
946        let already = base.join("thing.normalized.mjs");
947        std::fs::write(&already, "// sentinel, must not be re-bundled\n").unwrap();
948        let (p, o) = normalize_or_raw_sync(Some(&data), &already);
949        assert_eq!(p, already);
950        assert!(matches!(o, Outcome::Passthrough(_)), "{o:?}");
951        let after = std::fs::read_to_string(&already).unwrap();
952        assert!(after.contains("sentinel"), "output must be untouched");
953        let _ = std::fs::remove_dir_all(&base);
954    }
955
956    #[test]
957    fn dest_routing_clean_goes_to_data_dir() {
958        let _g = ENV_LOCK.lock();
959        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
960        unsafe {
961            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
962        };
963        let (base, data) = scratch();
964        let e = write_entry(&base, "plain.js", "export default 42;\n");
965        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
966        assert!(matches!(o, Outcome::Built { beside: false, .. }), "{o:?}");
967        assert!(
968            p.starts_with(&data),
969            "self-contained bundle must emit into ocserve's data dir, not beside entry: {}",
970            p.display()
971        );
972        // and the beside-entry candidate was never created
973        assert!(!base.join("plain.normalized.mjs").exists());
974        let _ = std::fs::remove_dir_all(&base);
975    }
976
977    #[test]
978    fn dest_routing_needs_ancestry_goes_beside_entry() {
979        let _g = ENV_LOCK.lock();
980        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
981        unsafe {
982            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
983        };
984        let (base, data) = scratch();
985        let e = write_entry(
986            &base,
987            "dyn.js",
988            r#"const pkg = "some-dep" + "-x";
989export default await import(pkg);"#,
990        );
991        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
992        assert!(matches!(o, Outcome::Built { beside: true, .. }), "{o:?}");
993        let expected = base.join("dyn.normalized.mjs").canonicalize().unwrap();
994        let actual = p.canonicalize().unwrap();
995        assert_eq!(actual, expected, "K4: beside the resolved entry");
996        let _ = std::fs::remove_dir_all(&base);
997    }
998
999    #[test]
1000    fn flip_destination_removes_stale_pair() {
1001        let _g = ENV_LOCK.lock();
1002        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
1003        unsafe {
1004            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
1005        };
1006        let (base, data) = scratch();
1007        let e = write_entry(&base, "flip.js", "export default 7;\n");
1008        let (p, _) = normalize_or_raw_sync(Some(&data), &e);
1009        assert!(p.starts_with(&data), "clean → data dir first");
1010        // Plant a stale beside-entry pair (as if a previous rule emitted there)
1011        let stale = base.join("flip.normalized.mjs");
1012        std::fs::write(&stale, "// stale\n").unwrap();
1013        // Content change → rebuild → dest still data-dir → stale pair removed
1014        std::fs::write(&e, "export default 8;\n").unwrap();
1015        let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
1016        assert!(matches!(o2, Outcome::Built { beside: false, .. }), "{o2:?}");
1017        assert!(p2.starts_with(&data));
1018        assert!(
1019            !stale.exists(),
1020            "stale beside-entry pair must be cleaned (spike-leftover class)"
1021        );
1022        let _ = std::fs::remove_dir_all(&base);
1023    }
1024    /// The minifier must stay OFF. Rolldown's default (`DeadCodeEliminationOnly`)
1025    /// still runs oxc's compressor, which carries
1026    /// `debug_assert!(false, "Ran loop more than 10 times.")`; a real plugin
1027    /// bundle trips it, the normalize task panics, and the plugin is silently
1028    /// disabled — while the same plugin loads raw with its hooks intact.
1029    ///
1030    /// Reproduced 2026-11-23 with `opencode-models-discovery@2.0.0`:
1031    ///   minify default -> `ok:false`, "normalize task: task 30 panicked with
1032    ///   message \"Ran loop more than 10 times.\""
1033    ///   minify false   -> `ok:true, hooks:["event"]`
1034    /// The same panic occurs on rolldown 1.3.1, so it is not the #61 bump.
1035    ///
1036    /// Planted control: delete the `minify:` line and this fails.
1037    #[test]
1038    fn normalizer_never_minifies() {
1039        let f = include_str!("normalize.rs");
1040        let opts = f
1041            .split("let opts = BundlerOptions {")
1042            .nth(1)
1043            .expect("bundler options block");
1044        let block = &opts[..opts.find("};").expect("options end")];
1045        assert!(
1046            block.contains("minify: Some(rolldown::RawMinifyOptions::Bool(false))"),
1047            "the normalizer must disable minification (oxc compressor loop panic)"
1048        );
1049    }
1050}