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        log_level: Some(LogLevel::Warn),
420        ..Default::default()
421    };
422    let mut bundler = Bundler::with_plugins(
423        opts,
424        vec![rolldown::plugin::__inner::Pluginable::new_shared(
425            AliasBunSqlite { shim_src: SHIM_SRC },
426        )],
427    )
428    .map_err(|e| anyhow::anyhow!("bundler init: {e:?}"))?;
429
430    // CPU-bound work runs on our own current-thread runtime; the caller
431    // (load_raw) has already moved us onto spawn_blocking (A2 class).
432    let rt = tokio::runtime::Builder::new_current_thread()
433        .enable_all()
434        .build()
435        .context("normalize runtime")?;
436    let out = rt
437        .block_on(bundler.generate())
438        .map_err(|e| anyhow::anyhow!("{e:?}"))?;
439    for w in &out.warnings {
440        tracing::warn!("normalize bundler warning: {w:?}");
441    }
442    let mut chunks = Vec::new();
443    for a in &out.assets {
444        if let rolldown_common::Output::Chunk(c) = a {
445            chunks.push(c);
446        }
447    }
448    if chunks.len() != 1 {
449        bail!(
450            "expected exactly 1 chunk, got {} ({:?})",
451            chunks.len(),
452            chunks
453                .iter()
454                .map(|c| c.filename.as_str())
455                .collect::<Vec<_>>()
456        );
457    }
458    Ok(chunks[0].code.clone())
459}
460
461// ---------------------------------------------------------------------------
462// Cache + atomic writes
463// ---------------------------------------------------------------------------
464
465fn content_hash(entry: &Path) -> Result<String> {
466    let mut h = Sha256::new();
467    let bytes = std::fs::read(entry).with_context(|| format!("read {}", entry.display()))?;
468    h.update(bytes);
469    h.update([0xff]);
470    h.update(SHIM_SRC.as_bytes());
471    h.update(NORMALIZER_VERSION.as_bytes());
472    // sha2 0.11 output no longer implements LowerHex; hex-encode explicitly.
473    Ok(hex::encode(h.finalize()))
474}
475
476/// Data-dir subdirectory for an entry: path-hash (16 hex chars).
477fn path_key(entry: &Path) -> String {
478    let mut h = Sha256::new();
479    h.update(entry.to_string_lossy().as_bytes());
480    hex::encode(h.finalize())[..16].to_string()
481}
482
483fn warm(out: &Path, want: &str) -> bool {
484    let hash_path = hash_path_of(out);
485    let Ok(h) = std::fs::read_to_string(&hash_path) else {
486        return false;
487    };
488    h.trim() == want && std::fs::metadata(out).map(|m| m.len() > 0).unwrap_or(false)
489}
490
491fn hash_path_of(out: &Path) -> PathBuf {
492    let mut s = out.as_os_str().to_os_string();
493    s.push(".hash");
494    PathBuf::from(s)
495}
496
497/// Write data via pid-unique hidden tmp + rename (STORAGE crash discipline).
498/// Guard rule 8 bans direct `fs::write` to final normalized paths.
499fn atomic_write(dest: &Path, data: &str) -> Result<()> {
500    let dir = dest.parent().context("dest has no parent")?;
501    std::fs::create_dir_all(dir).with_context(|| format!("mkdir {}", dir.display()))?;
502    let name = dest
503        .file_name()
504        .context("dest has no name")?
505        .to_string_lossy()
506        .into_owned();
507    let tmp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
508    std::fs::write(&tmp, data).with_context(|| format!("write {}", tmp.display()))?;
509    std::fs::rename(&tmp, dest).with_context(|| format!("rename {}", dest.display()))?;
510    Ok(())
511}
512
513/// Remove crash-orphaned `.{name}.*.tmp` older than STALE_TMP_SECS.
514fn sweep_stale_tmp(dest: &Path) {
515    let (Some(dir), Some(name)) = (dest.parent(), dest.file_name()) else {
516        return;
517    };
518    let prefix = format!(".{}.", name.to_string_lossy());
519    let Ok(rd) = std::fs::read_dir(dir) else {
520        return;
521    };
522    for e in rd.flatten() {
523        let fname = e.file_name().to_string_lossy().into_owned();
524        if fname.starts_with(&prefix) && fname.ends_with(".tmp") {
525            let stale = e
526                .metadata()
527                .ok()
528                .and_then(|m| m.modified().ok())
529                .and_then(|t| t.elapsed().ok())
530                .map(|age| age.as_secs() > STALE_TMP_SECS)
531                .unwrap_or(false);
532            if stale {
533                let _ = std::fs::remove_file(e.path());
534            }
535        }
536    }
537}
538
539fn rss_kb() -> i64 {
540    std::fs::read_to_string("/proc/self/status")
541        .ok()
542        .and_then(|s| {
543            s.lines()
544                .find(|l| l.starts_with("VmRSS:"))
545                .and_then(|l| l.split_whitespace().nth(1))
546                .and_then(|v| v.parse().ok())
547        })
548        .unwrap_or(-1)
549}
550
551// ---------------------------------------------------------------------------
552// Entry point
553// ---------------------------------------------------------------------------
554
555/// Normalize `entry` for loading. Returns (path-to-load, outcome). On any
556/// failure the raw entry is returned with `Fallback` — the load proceeds
557/// exactly as it does today (never worse than raw; D1-PLAN).
558pub fn normalize_or_raw_sync(root: Option<&Path>, entry: &Path) -> (PathBuf, Outcome) {
559    let raw = entry.to_path_buf();
560    // A11: never re-normalize an output.
561    if entry
562        .file_name()
563        .map(|n| n.to_string_lossy().ends_with(".normalized.mjs"))
564        .unwrap_or(false)
565    {
566        return (raw.clone(), Outcome::Passthrough(raw));
567    }
568    let Some(root) = root else {
569        // No root configured (tests, sidecars without it) → today's behavior.
570        return (raw.clone(), Outcome::Skipped(raw));
571    };
572    // A3: kill switch checked BEFORE rolldown exists anywhere.
573    if matches!(
574        std::env::var("OCSERVE_PLUGIN_NORMALIZE").as_deref(),
575        Ok("0")
576    ) {
577        return (raw.clone(), Outcome::Skipped(raw));
578    }
579
580    let work = match entry.canonicalize() {
581        Ok(w) => w,
582        Err(e) => {
583            return (
584                raw.clone(),
585                Outcome::Fallback {
586                    path: raw,
587                    err: format!("canonicalize {}: {e}", entry.display()),
588                },
589            );
590        }
591    };
592    let hash = match content_hash(&work) {
593        Ok(h) => h,
594        Err(e) => {
595            return (
596                raw.clone(),
597                Outcome::Fallback {
598                    path: raw,
599                    err: format!("{e:#}"),
600                },
601            );
602        }
603    };
604
605    let stem = work
606        .file_stem()
607        .map(|s| s.to_string_lossy().into_owned())
608        .unwrap_or_else(|| "index".into());
609    let out_name = format!("{stem}.normalized.mjs");
610    let beside = work.with_file_name(&out_name);
611    let data_dir = root.join(path_key(&work));
612    let data_out = data_dir.join(&out_name);
613    let hash_file = root.join(path_key(&work)).join(format!("{out_name}.hash"));
614
615    // Warm gate checks BOTH candidate locations (destination depends on the
616    // output, which only exists after a build — D1-PLAN).
617    for c in [&beside, &data_out] {
618        if warm(c, &hash) {
619            return (c.clone(), Outcome::Warm(c.clone()));
620        }
621    }
622
623    // Build (CPU — caller has us on spawn_blocking).
624    let rss_before = rss_kb();
625    let t0 = std::time::Instant::now();
626    let code = match bundle(&work) {
627        Ok(c) => c,
628        Err(e) => {
629            return (
630                raw.clone(),
631                Outcome::Fallback {
632                    path: raw,
633                    err: format!("bundle: {e:#}"),
634                },
635            );
636        }
637    };
638
639    // Destination rule (D1-PLAN conditional emit).
640    let needs = needs_ancestry(&code);
641    let (dest, other) = if needs {
642        (beside.clone(), Some(data_out.clone()))
643    } else {
644        (data_out.clone(), Some(beside.clone()))
645    };
646
647    if let Err(e) = atomic_write(&dest, &code) {
648        return (
649            raw.clone(),
650            Outcome::Fallback {
651                path: raw,
652                err: format!("write: {e:#}"),
653            },
654        );
655    }
656    // Hash AFTER the rename: any crash prefix leaves hash≠content → rebuild.
657    if let Err(e) = atomic_write(&hash_path_of(&dest), &hash) {
658        tracing::warn!("normalize hash write failed (will rebuild next boot): {e:#}");
659    }
660    // Stale opposite-location pair (destination flipped / spike leftovers):
661    // best-effort remove — these names are ocserve-derived, never user files.
662    if let Some(o) = other
663        && o != dest
664    {
665        let _ = std::fs::remove_file(&o);
666        let _ = std::fs::remove_file(hash_path_of(&o));
667    }
668    sweep_stale_tmp(&dest);
669    let _ = hash_file; // (path already handled via hash_path_of(dest))
670
671    (
672        dest.clone(),
673        Outcome::Built {
674            path: dest,
675            ms: t0.elapsed().as_millis(),
676            beside: needs,
677            rss_before_kb: rss_before,
678            rss_after_kb: rss_kb(),
679        },
680    )
681}
682
683// ---------------------------------------------------------------------------
684// Tests — every behavior test holds ENV_LOCK (kill-switch env is
685// process-global; guard-rule-7 class of race, same hazard).
686// ---------------------------------------------------------------------------
687#[cfg(test)]
688mod tests {
689    use super::*;
690
691    // parking_lot 0.13 removed the const_* constructors; `new` is const now.
692    static ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
693
694    /// M4b idiom: real-plugin tests exist only where the artifact exists.
695    fn real_entry(pkg: &str, rel: &str) -> Option<PathBuf> {
696        let home = std::env::var("HOME").ok()?;
697        let p = PathBuf::from(home).join(pkg).join(rel);
698        p.exists().then_some(p)
699    }
700
701    fn scratch() -> (PathBuf, PathBuf) {
702        let base = std::env::temp_dir().join(format!(
703            "ocserve-norm-test-{}-{:?}",
704            std::process::id(),
705            std::thread::current().id()
706        ));
707        let _ = std::fs::remove_dir_all(&base);
708        std::fs::create_dir_all(&base).unwrap();
709        let data = base.join("data");
710        std::fs::create_dir_all(&data).unwrap();
711        (base, data)
712    }
713
714    fn write_entry(base: &Path, name: &str, body: &str) -> PathBuf {
715        let p = base.join(name);
716        std::fs::write(&p, body).unwrap();
717        p
718    }
719
720    // ---- scanner controls (the conditional-emit oracle) ----
721
722    #[test]
723    fn scanner_real_magic_context_needs_ancestry() {
724        let Some(e) = real_entry(
725            ".cache/opencode/packages/@cortexkit/opencode-magic-context@latest/node_modules/@cortexkit/opencode-magic-context",
726            "dist/index.js",
727        ) else {
728            eprintln!("skip: magic-context not in opencode cache");
729            return;
730        };
731        let code = bundle(&e).expect("bundle magic-context");
732        assert!(
733            needs_ancestry(&code),
734            "computed @huggingface/transformers import MUST classify needs-ancestry \
735             (this is the ground truth that catches metadata-based scanners)"
736        );
737    }
738
739    #[test]
740    fn scanner_real_reliary8_is_clean() {
741        let home = std::env::var("HOME").unwrap();
742        let e = PathBuf::from(home).join("src/reliary8/opencode-plugin/dist/index.js");
743        if !e.exists() {
744            eprintln!("skip: reliary8 plugin absent");
745            return;
746        }
747        let code = bundle(&e).expect("bundle reliary8");
748        assert!(
749            !needs_ancestry(&code),
750            "reliary8 (builtins only) must be clean → data-dir emit, no repo writes"
751        );
752    }
753
754    #[test]
755    fn scanner_real_codex_auth_needs_ancestry() {
756        // Ground truth FLIPPED 2026-10-06 by evidence: codex-auth's
757        // getLockFunction() does `await import(specifier)` with specifier =
758        // "proper-lockfile" (its package.json dep) — a runtime-resolved
759        // BARE package → beside-entry emit is REQUIRED (cache ancestry).
760        // The first "clean" assumption was wrong; the scanner was right.
761        let Some(e) = real_entry(
762            ".cache/opencode/packages/@iam-brain/opencode-codex-auth@latest/node_modules/@iam-brain/opencode-codex-auth",
763            "dist/index.js",
764        ) else {
765            eprintln!("skip: codex-auth not in opencode cache");
766            return;
767        };
768        let code = bundle(&e).expect("bundle codex-auth");
769        assert!(
770            needs_ancestry(&code),
771            "codex-auth dynamically imports proper-lockfile at runtime"
772        );
773    }
774
775    #[test]
776    fn scanner_shim_identifier_stays_clean() {
777        // The K5b shim (inlined into every bun:sqlite bundle) does
778        // `await import(BUN_SPEC)` where `const BUN_SPEC = "bun:sqlite"`
779        // — virtual-module code is NOT folded at the call site (production
780        // evidence: magic-context output keeps the identifier). Staying
781        // clean REQUIRES const_map: gut it → None → false-dirty → any
782        // future path-plugin using bun:sqlite would pollute its repo.
783        let (base, _d) = scratch();
784        let e = write_entry(
785            &base,
786            "shimuser.js",
787            r#"import { Database } from "bun:sqlite";
788export default { Database };"#,
789        );
790        let code = bundle(&e).expect("bundle shim user");
791        assert!(
792            !needs_ancestry(&code),
793            "shim import(BUN_SPEC) must resolve via const_map to bun:sqlite (scheme-clean)"
794        );
795        let _ = std::fs::remove_dir_all(&base);
796    }
797
798    #[test]
799    fn scanner_synthetic_computed_import_needs_ancestry() {
800        let (base, _d) = scratch();
801        let e = write_entry(
802            &base,
803            "dyn.js",
804            r#"const pkg = "some-dep" + "-x";
805export default await import(pkg);"#,
806        );
807        let code = bundle(&e).expect("bundle synthetic dyn");
808        assert!(needs_ancestry(&code));
809        let _ = std::fs::remove_dir_all(&base);
810    }
811
812    #[test]
813    fn scanner_node_relative_const_are_clean() {
814        let (base, _d) = scratch();
815        std::fs::write(base.join("sib.js"), "export const x = 1;\n").unwrap();
816        // const via concat (real-bundle shape: rolldown keeps `import(P)`,
817        // folding the concat into `const P = "node:crypto"` — pure literals
818        // get inlined at the call and would bypass const_map entirely)
819        let e = write_entry(
820            &base,
821            "ok.js",
822            r#"import fs from "node:fs";
823import path2 from "path";
824import { x } from "./sib.js";
825const P = "node:" + "crypto";
826const dyn = await import(P);
827export default { fs, path2, x, dyn };"#,
828        );
829        let code = bundle(&e).expect("bundle clean fixture");
830        assert!(
831            !needs_ancestry(&code),
832            "node:/relative/builtin + const-resolved node: spec are clean"
833        );
834        let _ = std::fs::remove_dir_all(&base);
835    }
836
837    // ---- behavior (all under ENV_LOCK — env is process-global) ----
838
839    #[test]
840    fn warm_hash_skips_rebuild() {
841        let _g = ENV_LOCK.lock();
842        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
843        unsafe {
844            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
845        };
846        let (base, data) = scratch();
847        let e = write_entry(&base, "p.js", "export default 1;\n");
848        let (p1, o1) = normalize_or_raw_sync(Some(&data), &e);
849        assert!(matches!(o1, Outcome::Built { .. }), "first: {o1:?}");
850        let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
851        assert!(matches!(o2, Outcome::Warm(_)), "second: {o2:?}");
852        assert_eq!(p1, p2);
853        let _ = std::fs::remove_dir_all(&base);
854    }
855
856    #[test]
857    fn stale_entry_rebuilds() {
858        let _g = ENV_LOCK.lock();
859        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
860        unsafe {
861            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
862        };
863        let (base, data) = scratch();
864        let e = write_entry(&base, "p.js", "export default 1;\n");
865        let (_, o1) = normalize_or_raw_sync(Some(&data), &e);
866        assert!(matches!(o1, Outcome::Built { .. }));
867        std::fs::write(&e, "export default 2; // changed\n").unwrap();
868        let (_, o2) = normalize_or_raw_sync(Some(&data), &e);
869        assert!(matches!(o2, Outcome::Built { .. }), "changed: {o2:?}");
870        let _ = std::fs::remove_dir_all(&base);
871    }
872
873    #[test]
874    fn normalize_error_falls_back_to_raw() {
875        let _g = ENV_LOCK.lock();
876        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
877        unsafe {
878            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
879        };
880        let (base, data) = scratch();
881        let e = write_entry(&base, "bad.js", "import { from 'broken");
882        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
883        assert_eq!(p, e, "fallback path MUST be the raw entry");
884        assert!(matches!(o, Outcome::Fallback { .. }), "{o:?}");
885        let _ = std::fs::remove_dir_all(&base);
886    }
887
888    #[test]
889    fn kill_switch_disables_building() {
890        let _g = ENV_LOCK.lock();
891        let (base, data) = scratch();
892        let e = write_entry(&base, "p.js", "export default 1;\n");
893        // SAFETY: single env mutation under the shared lock, restored below.
894        unsafe { std::env::set_var("OCSERVE_PLUGIN_NORMALIZE", "0") };
895        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
896        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
897        unsafe {
898            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
899        };
900        assert_eq!(p, e);
901        assert!(matches!(o, Outcome::Skipped(_)), "{o:?}");
902        // proof of no-build: normalized dir stays empty
903        let built = std::fs::read_dir(&data).map(|d| d.count()).unwrap_or(0);
904        assert_eq!(built, 0, "kill switch must not construct outputs");
905        let _ = std::fs::remove_dir_all(&base);
906    }
907
908    #[test]
909    fn wipe_then_normalize_rebuilds() {
910        let _g = ENV_LOCK.lock();
911        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
912        unsafe {
913            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
914        };
915        let (base, data) = scratch();
916        let e = write_entry(&base, "p.js", "export default 1;\n");
917        let (p1, o1) = normalize_or_raw_sync(Some(&data), &e);
918        assert!(matches!(o1, Outcome::Built { .. }));
919        std::fs::remove_file(&p1).unwrap();
920        std::fs::remove_file(hash_path_of(&p1)).unwrap();
921        let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
922        assert!(matches!(o2, Outcome::Built { .. }), "after wipe: {o2:?}");
923        assert!(p2.exists());
924        let _ = std::fs::remove_dir_all(&base);
925    }
926
927    #[test]
928    fn suffix_guard_passthrough() {
929        let _g = ENV_LOCK.lock();
930        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
931        unsafe {
932            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
933        };
934        let (base, data) = scratch();
935        let already = base.join("thing.normalized.mjs");
936        std::fs::write(&already, "// sentinel, must not be re-bundled\n").unwrap();
937        let (p, o) = normalize_or_raw_sync(Some(&data), &already);
938        assert_eq!(p, already);
939        assert!(matches!(o, Outcome::Passthrough(_)), "{o:?}");
940        let after = std::fs::read_to_string(&already).unwrap();
941        assert!(after.contains("sentinel"), "output must be untouched");
942        let _ = std::fs::remove_dir_all(&base);
943    }
944
945    #[test]
946    fn dest_routing_clean_goes_to_data_dir() {
947        let _g = ENV_LOCK.lock();
948        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
949        unsafe {
950            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
951        };
952        let (base, data) = scratch();
953        let e = write_entry(&base, "plain.js", "export default 42;\n");
954        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
955        assert!(matches!(o, Outcome::Built { beside: false, .. }), "{o:?}");
956        assert!(
957            p.starts_with(&data),
958            "self-contained bundle must emit into ocserve's data dir, not beside entry: {}",
959            p.display()
960        );
961        // and the beside-entry candidate was never created
962        assert!(!base.join("plain.normalized.mjs").exists());
963        let _ = std::fs::remove_dir_all(&base);
964    }
965
966    #[test]
967    fn dest_routing_needs_ancestry_goes_beside_entry() {
968        let _g = ENV_LOCK.lock();
969        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
970        unsafe {
971            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
972        };
973        let (base, data) = scratch();
974        let e = write_entry(
975            &base,
976            "dyn.js",
977            r#"const pkg = "some-dep" + "-x";
978export default await import(pkg);"#,
979        );
980        let (p, o) = normalize_or_raw_sync(Some(&data), &e);
981        assert!(matches!(o, Outcome::Built { beside: true, .. }), "{o:?}");
982        assert_eq!(p, base.join("dyn.normalized.mjs"), "K4: beside entry");
983        let _ = std::fs::remove_dir_all(&base);
984    }
985
986    #[test]
987    fn flip_destination_removes_stale_pair() {
988        let _g = ENV_LOCK.lock();
989        // SAFETY: process-global env mutation, serialized under ENV_LOCK, restored here.
990        unsafe {
991            std::env::remove_var("OCSERVE_PLUGIN_NORMALIZE");
992        };
993        let (base, data) = scratch();
994        let e = write_entry(&base, "flip.js", "export default 7;\n");
995        let (p, _) = normalize_or_raw_sync(Some(&data), &e);
996        assert!(p.starts_with(&data), "clean → data dir first");
997        // Plant a stale beside-entry pair (as if a previous rule emitted there)
998        let stale = base.join("flip.normalized.mjs");
999        std::fs::write(&stale, "// stale\n").unwrap();
1000        // Content change → rebuild → dest still data-dir → stale pair removed
1001        std::fs::write(&e, "export default 8;\n").unwrap();
1002        let (p2, o2) = normalize_or_raw_sync(Some(&data), &e);
1003        assert!(matches!(o2, Outcome::Built { beside: false, .. }), "{o2:?}");
1004        assert!(p2.starts_with(&data));
1005        assert!(
1006            !stale.exists(),
1007            "stale beside-entry pair must be cleaned (spike-leftover class)"
1008        );
1009        let _ = std::fs::remove_dir_all(&base);
1010    }
1011}