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