#!/usr/bin/env python3
"""
v2.1 Deterministic 16-Gate & 4-Layer 3D WebGL / WebAudio DSP / System-32 CAD Verification Oracle
& Cryptographic Blinded Judge Staging Harness for borkbork ("Meble Na Wymiar") on DELTA-AMD.

Executes live against all gta-* builds in /home/b00lean/happier-workspaces/borkbork/public/out via
headless Chromium + ANGLE/SwiftShader with parallel evaluation on DELTA-AMD (32 threads / 46 GiB RAM):
  - Layer 1 (25 pts) / Gates G0a, G0b, G1a, G1b, G1c:
      * Boot, 0 uncaught pageerrors, active WebGL draw calls (>10)
      * Virtual-clock (dt=16.667ms) + wall-clock tween stability
      * PointerLock quaternion preservation (no per-frame view reset)
      * True THREE.OrthographicCamera in Elevation view (no fov=28deg perspective fake)
  - Layer 2 (25 pts) / Gates G2a, G2b, G2c, G2d:
      * Direct WebGL2 gl.readPixels center (96x96) & 70%-viewport readback (nonBlackRatio, meanLuma, lumaSpread)
      * Non-zero alpha volumetric god-ray shader verification (catches UV/aLocal boundary zeroing)
      * Live A/B Time-of-Day luminance delta probe
      * Planar Reflector / multi-pass FBO binds attached to door leaf hierarchy
  - Layer 3 (20 pts) / Gates G3a, G3b, G3c:
      * 100% procedural WebAudio synthesis (0 external .mp3/.wav/.ogg assets)
      * Live PannerNode / StereoPannerNode spatial graph + HRTF count
      * Live BiquadFilterNode low-pass filter getFrequencyResponse([100, 250, 900, 1800, 4000])
      * Deterministic OfflineAudioContext stereo ILD (dB) + 90->38Hz Blum soft-close sub-bass verification
  - Layer 4 (30 pts) / Gates G4a, G4b, G5a, G5b:
      * Articulated 3D cat (>=12 parts/bones) without double world-matrix SkinnedMesh explosion
      * Reachable shelf perch/descent lifecycle & headroom clearance
      * Parametric Polish System-32 (32mm pitch / 37mm setback) & instanced/solver verification
      * Live BOM quote extraction & 3D-mesh-to-cutlist reconciliation (8% vs 23% VAT)
"""

from __future__ import annotations
import argparse
import asyncio
import hashlib
import hmac
import http.server
import json
import math
import os
import platform
import re
import socketserver
import threading
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

from playwright.async_api import async_playwright

PUBLIC_DIR = Path("/home/b00lean/happier-workspaces/borkbork/public")
OUT_DIR = PUBLIC_DIR / "out"
RESEARCH_DIR = PUBLIC_DIR / "research"

CANDIDATES: List[Tuple[str, str]] = [
    ("gta-final",    "v4.1 Master 3D Room (Opus+Astra+Sol+Fable+Grok)"),
    ("gta-opus55",   "Anthropic Claude Opus 5.5"),
    ("gta-astramax", "OpenAI GPT-6 Astra Max"),
    ("gta-fable51",  "Anthropic Claude Fable 5.1"),
    ("gta-sol",      "OpenAI GPT-6.1 Sol"),
    ("gta-grok47",   "xAI Grok 4.7"),
    ("gta-qwen38",   "Alibaba Qwen 3.8 Max"),
    ("gta-muse",     "Meta Muse (muse-wonder-1.0 ultra)"),
    ("gta-minimax",  "MiniMax-M3"),
    ("gta-gemini4",  "Google Gemini 4 Argon High"),
    ("gta-glm53",    "Z.ai GLM-5.3"),
    ("gta-fugu",     "Sakana Fugu (fugu-ultra-v2.0 xhigh)"),
    ("gta-kimi",     "Moonshot Kimi K2.8 Preview"),
]

LEAVE_ONE_OUT_JUDGES: Dict[str, Dict[str, Any]] = {
    "gta-opus55":   {"opus": 97.0, "astra": 92.0, "sol": 91.0, "self": "opus"},
    "gta-astramax": {"opus": 88.0, "astra": 94.0, "sol": 88.0, "self": "astra"},
    "gta-fable51":  {"opus": 91.5, "astra": 87.0, "sol": 88.0, "self": "opus"},
    "gta-sol":      {"opus": 87.5, "astra": 90.0, "sol": 81.0, "self": "sol"},
    "gta-grok47":   {"opus": 81.0, "astra": 87.0, "sol": 87.0, "self": None},
    "gta-qwen38":   {"opus": 89.0, "astra": 79.0, "sol": 82.0, "self": None},
    "gta-muse":     {"opus": 92.0, "astra": 91.0, "sol": 91.0, "self": None},
    "gta-minimax":  {"opus": 72.0, "astra": 74.0, "sol": 73.0, "self": None},
    "gta-gemini4":  {"opus": 72.0, "astra": 66.0, "sol": 61.0, "self": None},
    "gta-glm53":    {"opus": 33.0, "astra": 40.0, "sol": 32.0, "self": None},
    "gta-fugu":     {"opus": 96.0, "astra": 94.0, "sol": 94.0, "self": None},
    "gta-kimi":     {"opus": 90.0, "astra": 89.0, "sol": 89.0, "self": None},
}

CANDIDATE_DRIVERS: Dict[str, List[str]] = {
    "gta-final": [
        "studio.audio.init(); studio.setTime(9.5); studio.setAllFronts(true); studio.cycleWindow(); studio.cycleWindow();",
        "studio.setMode('cad');",
        "studio.cat.command('shelf');",
    ],
    "gta-opus55": [
        "studio.audio.init(); studio.setTime(9.5); studio.setAllFronts(true); studio.cycleWindow(); studio.cycleWindow();",
        "studio.setMode('cad');",
        "studio.cat.command('shelf');",
    ],
    "gta-astramax": [
        "studio.audio.init(); studio.audio.setMute(false);",
        "document.querySelector('#masterBtn')?.click(); document.querySelector('#windowBtn')?.click();",
        "studio.setMode('cad'); studio.commandCat('shelf');",
    ],
    "gta-fable51": [
        "SIM.enter(); SIM.setTime(9.5); SIM.masterDoors(); SIM.setWindowOpen(true);",
        "SIM.setMode('cad'); SIM.cat.goToBay();",
    ],
    "gta-sol": [
        "await studio.enableAudio(); studio.setMode('cad');",
        "document.querySelector('#all-open')?.click(); document.querySelector('#window')?.click();",
        "studio.catAction('jump');",
    ],
    "gta-grok47": [
        "__studio.audio.ensure(); __studio.setHour(9.5);",
        "document.querySelector('#doors-open')?.click(); document.querySelector('#window')?.click();",
        "__studio.setMode('cad'); __studio.cat.force('jump');",
    ],
    "gta-qwen38": [
        "STUDIO.audio.init(); STUDIO.setHour(9.5); STUDIO.toggleAllFronts(true); STUDIO.toggleWindow();",
        "STUDIO.setMode('cad'); STUDIO.cat.jumpToShelf();",
    ],
    "gta-muse": [
        "document.getElementById('mirrorTgl')?.click(); document.getElementById('openAllBtn')?.click(); document.getElementById('windowTgl')?.click();",
        "document.getElementById('closeAllBtn')?.click(); document.getElementById('rainTgl')?.click(); document.getElementById('radioTgl')?.click();",
        "document.getElementById('dockCadBtn')?.click(); document.getElementById('elevTgl')?.click();",
    ],
    "gta-minimax": [
        "document.getElementById('splash')?.click(); if (typeof audio !== 'undefined' && audio.resumeOnce) audio.resumeOnce();",
        "document.getElementById('aRadio')?.click(); document.getElementById('aRain')?.click(); document.getElementById('aStreet')?.click();",
        "if (typeof setMode === 'function') setMode('cad'); if (typeof renderBom === 'function') renderBom();",
    ],
    "gta-gemini4": [
        "__WARDROBE_SIM__.soundEngine.ensureInit(); __WARDROBE_SIM__.updateTimeOfDay(9.5);",
        "__WARDROBE_SIM__.toggleMasterDoorsAndDrawers(); __WARDROBE_SIM__.toggleWindowState();",
        "__WARDROBE_SIM__.switchCameraMode('cad'); __WARDROBE_SIM__.apartmentCat.setState('jump');",
    ],
    "gta-glm53": [
        "__sim.audio.unlock(); __sim.setTime(9.5); __sim.openAllDoors(); __sim.toggleWindow();",
        "__sim.setMode('cad'); __sim.cat.force('jumpUp');",
    ],
    "gta-fugu": [
        "document.getElementById('radioButton')?.click(); document.getElementById('rainButton')?.click(); document.getElementById('windowButton')?.click();",
        "const d = document.getElementById('decor'); if (d) { d.value = 'mirror'; d.dispatchEvent(new Event('change', {bubbles:true})); }",
        "window.__studio?.setTime?.(9.5); window.__studio?.toggleAllDoors?.(true); window.__studio?.setMode?.('cad');",
    ],
    "gta-kimi": [
        "document.getElementById('radioTgl')?.click(); document.getElementById('rainTgl')?.click(); document.getElementById('openAll')?.click();",
        "if (window.__studio?.cfg && window.__studio?.buildWardrobe) { window.__studio.cfg.frontDecor = 'lustro'; window.__studio.buildWardrobe(); }",
        "window.__studio?.applyTime?.(9.5); window.__studio?.setMode?.('cad');",
    ],
}

INIT_INSTRUMENTATION_JS = r"""
(() => {
  let vNow = 1000.0;
  const origPerfNow = performance.now.bind(performance);
  window.__BORK_VCLOCK__ = {
    active: false,
    step(ms = 16.667) { vNow += ms; },
    now() { return this.active ? vNow : origPerfNow(); }
  };
  performance.now = () => window.__BORK_VCLOCK__.now();

  window.__ORACLE__ = {
    webglContexts: [],
    drawCalls: 0,
    instancedDrawCalls: 0,
    framebufferBinds: 0,
    pannerNodes: [],
    biquadFilters: [],
    oscillators: [],
    gainNodes: [],
    audioContexts: [],
    connects: 0,
  };

  const origGetContext = HTMLCanvasElement.prototype.getContext;
  HTMLCanvasElement.prototype.getContext = function(type, attrs) {
    if (type && type.indexOf('webgl') !== -1) {
      attrs = Object.assign({}, attrs || {}, { preserveDrawingBuffer: true });
    }
    const ctx = origGetContext.call(this, type, attrs);
    if (ctx && type && type.indexOf('webgl') !== -1 && !ctx.__oracleSpied) {
      ctx.__oracleSpied = true;
      window.__BORK_GL__ = ctx;
      window.__BORK_CANVAS__ = this;
      window.__ORACLE__.webglContexts.push({ canvas: this, gl: ctx });
      for (const fn of ['drawArrays', 'drawElements']) {
        if (typeof ctx[fn] === 'function') {
          const orig = ctx[fn].bind(ctx);
          ctx[fn] = function(...args) {
            window.__ORACLE__.drawCalls++;
            return orig(...args);
          };
        }
      }
      for (const fn of ['drawArraysInstanced', 'drawElementsInstanced']) {
        if (typeof ctx[fn] === 'function') {
          const orig = ctx[fn].bind(ctx);
          ctx[fn] = function(...args) {
            window.__ORACLE__.instancedDrawCalls++;
            window.__ORACLE__.drawCalls++;
            return orig(...args);
          };
        }
      }
      if (typeof ctx.bindFramebuffer === 'function') {
        const origBind = ctx.bindFramebuffer.bind(ctx);
        ctx.bindFramebuffer = function(target, fb) {
          if (fb !== null) window.__ORACLE__.framebufferBinds++;
          return origBind(target, fb);
        };
      }
    }
    return ctx;
  };

  const BaseCtx = window.BaseAudioContext || window.AudioContext || window.webkitAudioContext;
  if (BaseCtx && BaseCtx.prototype) {
    if (window.AudioNode && AudioNode.prototype.connect) {
      const origConnect = AudioNode.prototype.connect;
      AudioNode.prototype.connect = function(dest, ...rest) {
        window.__ORACLE__.connects++;
        return origConnect.call(this, dest, ...rest);
      };
    }
    const origCreatePanner = BaseCtx.prototype.createPanner;
    if (origCreatePanner) {
      BaseCtx.prototype.createPanner = function(...args) {
        if (!window.__ORACLE__.audioContexts.includes(this)) window.__ORACLE__.audioContexts.push(this);
        const node = origCreatePanner.apply(this, args);
        window.__ORACLE__.pannerNodes.push(node);
        return node;
      };
    }
    const origCreateStereo = BaseCtx.prototype.createStereoPanner;
    if (origCreateStereo) {
      BaseCtx.prototype.createStereoPanner = function(...args) {
        if (!window.__ORACLE__.audioContexts.includes(this)) window.__ORACLE__.audioContexts.push(this);
        const node = origCreateStereo.apply(this, args);
        window.__ORACLE__.pannerNodes.push(node);
        return node;
      };
    }
    const origCreateBiquad = BaseCtx.prototype.createBiquadFilter;
    if (origCreateBiquad) {
      BaseCtx.prototype.createBiquadFilter = function(...args) {
        if (!window.__ORACLE__.audioContexts.includes(this)) window.__ORACLE__.audioContexts.push(this);
        const node = origCreateBiquad.apply(this, args);
        window.__ORACLE__.biquadFilters.push(node);
        return node;
      };
    }
    const origCreateOsc = BaseCtx.prototype.createOscillator;
    if (origCreateOsc) {
      BaseCtx.prototype.createOscillator = function(...args) {
        if (!window.__ORACLE__.audioContexts.includes(this)) window.__ORACLE__.audioContexts.push(this);
        const node = origCreateOsc.apply(this, args);
        node.__freqHistory = [{ type: 'init', value: node.frequency.value, time: 0 }];
        const origSetVal = node.frequency.setValueAtTime.bind(node.frequency);
        node.frequency.setValueAtTime = function(val, t) {
          node.__freqHistory.push({ type: 'set', value: val, time: t });
          return origSetVal(val, t);
        };
        const origExpRamp = node.frequency.exponentialRampToValueAtTime.bind(node.frequency);
        node.frequency.exponentialRampToValueAtTime = function(val, t) {
          node.__freqHistory.push({ type: 'exp', value: val, time: t });
          return origExpRamp(val, t);
        };
        const origLinRamp = node.frequency.linearRampToValueAtTime.bind(node.frequency);
        node.frequency.linearRampToValueAtTime = function(val, t) {
          node.__freqHistory.push({ type: 'lin', value: val, time: t });
          return origLinRamp(val, t);
        };
        window.__ORACLE__.oscillators.push(node);
        return node;
      };
    }
  }

  window.__borkReadPixelsPatch = function() {
    if (window.__ORACLE__.webglContexts.length === 0) {
      return { hasGl: false, canvasWidth: 0, canvasHeight: 0, nonBlackRatio: 0, meanLuminance: 0, lumaSpread: 0, renderedNonBlankScene: false };
    }
    const sorted = [...window.__ORACLE__.webglContexts].sort(
      (a, b) => (b.canvas.width * b.canvas.height) - (a.canvas.width * a.canvas.height)
    );
    const { gl, canvas } = sorted[0];
    const cw = gl.drawingBufferWidth || canvas.width || 1280;
    const ch = gl.drawingBufferHeight || canvas.height || 720;
    if (cw < 10 || ch < 10) {
      return { hasGl: true, canvasWidth: cw, canvasHeight: ch, nonBlackRatio: 0, meanLuminance: 0, lumaSpread: 0, renderedNonBlankScene: false };
    }
    const sw = Math.min(cw, 320);
    const sh = Math.min(ch, 240);
    const x0 = Math.max(0, Math.floor((cw - sw) / 2));
    const y0 = Math.max(0, Math.floor((ch - sh) / 2));
    const pixels = new Uint8Array(sw * sh * 4);
    try { gl.bindFramebuffer(gl.FRAMEBUFFER, null); } catch (_) {}
    gl.readPixels(x0, y0, sw, sh, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
    let nonBlack = 0, lumaSum = 0, lumaMin = 255, lumaMax = 0;
    for (let i = 0; i < pixels.length; i += 4) {
      const luma = 0.2126 * pixels[i] + 0.7152 * pixels[i + 1] + 0.0722 * pixels[i + 2];
      if (luma > 2.0) nonBlack++;
      lumaSum += luma;
      if (luma < lumaMin) lumaMin = luma;
      if (luma > lumaMax) lumaMax = luma;
    }
    const nPx = sw * sh;
    return {
      hasGl: true,
      canvasWidth: cw,
      canvasHeight: ch,
      samplePatch: `${sw}x${sh}`,
      nonBlackRatio: +(nonBlack / nPx).toFixed(4),
      meanLuminance: +(lumaSum / nPx).toFixed(2),
      lumaSpread: +(lumaMax - lumaMin).toFixed(2),
      renderedNonBlankScene: (nonBlack / nPx) > 0.15 && (lumaMax - lumaMin) > 5.0,
    };
  };
})();
"""

IN_PAGE_EVAL_JS = r"""
async (candidateName) => {
  const report = {
    gate0_runtime: {},
    gate1_camera: {},
    gate2_webgl_pixels: {},
    gate3_webaudio_dsp: {},
    gate4_cat_fsm: {},
    gate5_system32_bom: {},
  };

  window.__BORK_VCLOCK__.active = true;
  for (let i = 0; i < 20; i++) window.__BORK_VCLOCK__.step(16.667);

  const api = window.studio || window.SIM || window.STUDIO || window.__studio || window.__WARDROBE_SIM__ || window.__sim || null;
  report.gate0_runtime.hasPublicApi = Boolean(api);
  report.gate0_runtime.version = api?.version || null;
  report.gate0_runtime.drawCalls = window.__ORACLE__.drawCalls;
  report.gate0_runtime.instancedDrawCalls = window.__ORACLE__.instancedDrawCalls;
  report.gate0_runtime.framebufferBinds = window.__ORACLE__.framebufferBinds;
  report.gate0_runtime.webglContextCount = window.__ORACLE__.webglContexts.length;

  if (api && typeof api.selfTest === 'function') {
    try {
      const st = api.selfTest();
      report.gate0_runtime.selfTest = {
        ok: Boolean(st?.ok),
        passed: st?.passed ?? (Array.isArray(st?.failures) ? 'see_failures' : null),
        total: st?.total ?? null,
      };
    } catch (e) {
      report.gate0_runtime.selfTest = { ok: false, error: String(e) };
    }
  }

  // Gate 2: Direct WebGL Pixel Readback + Day/Night A/B Luma Delta
  const pxDay = window.__borkReadPixelsPatch();
  let deltaLuma = 0;
  try {
    const sliders = Array.from(document.querySelectorAll('input[type="range"]'));
    for (const s of sliders) {
      const min = parseFloat(s.min || '0'), max = parseFloat(s.max || '24');
      if (max === 24 || max === 1440 || max === 23.9 || (s.id && /time|sun|hour/i.test(s.id))) {
        s.value = String(min + (max - min) * 0.95);
        s.dispatchEvent(new Event('input', { bubbles: true }));
        s.dispatchEvent(new Event('change', { bubbles: true }));
        for (let i = 0; i < 6; i++) window.__BORK_VCLOCK__.step(16.667);
        break;
      }
    }
    const pxNight = window.__borkReadPixelsPatch();
    deltaLuma = Math.abs((pxNight.meanLuminance || 0) - (pxDay.meanLuminance || 0));
  } catch (_) {}
  window.__BORK_VCLOCK__.active = false;

  report.gate2_webgl_pixels = Object.assign({}, pxDay, {
    abDayNightDeltaLuma: +deltaLuma.toFixed(2),
  });

  // Gate 3: Deterministic WebAudio DSP & Spatial Panner / BiquadFilter / OfflineAudioContext Probe
  const panners = [...window.__ORACLE__.pannerNodes];
  const filters = [...window.__ORACLE__.biquadFilters];
  const oscs = [...window.__ORACLE__.oscillators];
  const connectsCount = window.__ORACLE__.connects;
  const lowpassFilters = filters.filter(f => f.type === 'lowpass');
  let lpfTransfer = null;
  if (lowpassFilters.length > 0) {
    const winLpf = lowpassFilters.find(f => f.frequency.value >= 200 && f.frequency.value <= 2200) || lowpassFilters[0];
    const testFreqs = new Float32Array([100, 250, 900, 1800, 4000]);
    const magOut = new Float32Array(5);
    const phaseOut = new Float32Array(5);
    winLpf.getFrequencyResponse(testFreqs, magOut, phaseOut);
    lpfTransfer = {
      cutoffHz: +winLpf.frequency.value.toFixed(1),
      mag100Hz: +magOut[0].toFixed(4),
      mag250Hz: +magOut[1].toFixed(4),
      mag900Hz: +magOut[2].toFixed(4),
      mag1800Hz: +magOut[3].toFixed(4),
      mag4000Hz: +magOut[4].toFixed(4),
    };
  }

  let offlineVerify = null;
  if (window.OfflineAudioContext) {
    const sr = 44100;
    const offline = new OfflineAudioContext(2, Math.floor(sr * 0.16), sr);
    const osc = offline.createOscillator();
    osc.type = 'triangle';
    osc.frequency.setValueAtTime(90, 0.0);
    osc.frequency.exponentialRampToValueAtTime(38, 0.12);
    const pan = offline.createPanner();
    pan.panningModel = 'equalpower';
    pan.positionX.value = 2.0;
    pan.positionY.value = 1.68;
    pan.positionZ.value = -1.0;
    osc.connect(pan);
    pan.connect(offline.destination);
    osc.start(0);
    osc.stop(0.14);
    const buf = await offline.startRendering();
    const L = buf.getChannelData(0);
    const R = buf.getChannelData(1);
    let sL = 0, sR = 0;
    for (let i = 0; i < L.length; i++) { sL += L[i]*L[i]; sR += R[i]*R[i]; }
    const rmsL = Math.sqrt(sL / L.length);
    const rmsR = Math.sqrt(sR / R.length);
    offlineVerify = {
      ildRightMinusLeftDb: +(20 * Math.log10((rmsR + 1e-9) / (rmsL + 1e-9))).toFixed(2),
      rmsR: +rmsR.toFixed(4),
      rmsL: +rmsL.toFixed(4),
    };
  }

  report.gate3_webaudio_dsp = {
    pannerNodeCount: panners.length,
    hrtfPannerCount: panners.filter(p => p.panningModel === 'HRTF').length,
    biquadFilterCount: filters.length,
    oscillatorCount: oscs.length,
    connectCount: connectsCount,
    hasSpatialPanner: panners.length > 0,
    windowLpfTransfer: lpfTransfer,
    offlineAudioDspVerify: offlineVerify,
  };

  // Gate 4 & Gate 5: Extract Cat Bones/State & BOM Quote via candidate API + DOM fallback
  try {
    if (window.studio) {
      const s = window.studio;
      report.gate4_cat_fsm = {
        state: s.cat?.state ?? s.diagnostics?.catState ?? s.inspect?.()?.cat?.mode ?? null,
        bones: typeof s.cat?.bones === 'function' ? s.cat.bones() : null,
      };
      const bom = typeof s.bom === 'function' ? s.bom() : (typeof s.quote === 'function' ? s.quote() : null);
      report.gate5_system32_bom = {
        bruttoPLN: bom ? +(bom.brutto ?? bom.gross ?? 0).toFixed(2) : null,
        nettoPLN: bom ? +(bom.netto ?? bom.net ?? 0).toFixed(2) : null,
        walkBlockedCheck: typeof s.walk?.blocked === 'function' ? {
          wardrobeSolid: s.walk.blocked(0, -1.8),
          roomWalkable: !s.walk.blocked(0, 0.5),
        } : null,
      };
    } else if (window.SIM) {
      const d = window.SIM.diag ? window.SIM.diag() : {};
      const b = window.SIM.computeBOM ? window.SIM.computeBOM() : {};
      report.gate4_cat_fsm = { state: window.SIM.cat?.state, pos: window.SIM.cat?.pos };
      report.gate5_system32_bom = { bruttoPLN: b.brutto ? +b.brutto.toFixed(2) : null, diag: d };
    } else if (window.STUDIO) {
      const b = window.STUDIO.bom ? window.STUDIO.bom() : {};
      report.gate4_cat_fsm = {
        state: window.STUDIO.cat?.state?.(),
        bones: window.STUDIO.cat?.bones?.(),
      };
      report.gate5_system32_bom = {
        bruttoPLN: b.brutto ?? b.totalBrutto ?? null,
      };
    } else if (window.__studio) {
      // gta-grok47, gta-muse, gta-fugu, and gta-kimi expose window.__studio
      const s = window.__studio;
      const museBom = typeof s.computeBOM === 'function' ? s.computeBOM() : (typeof s.buildBOM === 'function' ? s.buildBOM() : null);
      const grossVal = s.quote?.brutto ?? museBom?.brutto ?? museBom?.gross ?? null;
      const netVal = s.quote?.netto ?? museBom?.netto ?? museBom?.net ?? null;
      report.gate4_cat_fsm = {
        state: s.cat?.snapshot?.()?.state ?? s.CAT?.state ?? s.catState ?? null,
      };
      report.gate5_system32_bom = {
        bruttoPLN: grossVal !== null ? +Number(grossVal).toFixed(2) : null,
        nettoPLN: netVal !== null ? +Number(netVal).toFixed(2) : null,
      };
    } else if (window.__WARDROBE_SIM__) {
      const S = window.__WARDROBE_SIM__;
      report.gate4_cat_fsm = { state: S.apartmentCat?.state };
      report.gate5_system32_bom = { bruttoPLN: S.state?.computed?.bom?.totalBrutto ?? null };
    } else if (window.__sim) {
      const st = window.__sim.stats?.() || {};
      report.gate4_cat_fsm = { state: window.__sim.cat?.state?.() };
      report.gate5_system32_bom = {
        bruttoPLN: st.brutto ?? st.totalBrutto ?? null,
        stats: st,
      };
    } else if (typeof computeBom === 'function') {
      // gta-minimax global computeBom()
      const b = computeBom();
      report.gate4_cat_fsm = { state: typeof cat !== 'undefined' ? cat.state : 'active' };
      report.gate5_system32_bom = {
        bruttoPLN: b?.total ? +b.total.toFixed(2) : null,
        nettoPLN: b?.sub ? +b.sub.toFixed(2) : null,
      };
    }

    // DOM fallback for BOM Brutto PLN if API didn't populate it
    if (!report.gate5_system32_bom.bruttoPLN) {
      for (const sel of ['#bomBrutto', '#tGross', '#bruttoVal', '#totalBrutto', '.brutto']) {
        const el = document.querySelector(sel);
        if (el && el.textContent) {
          const cleaned = el.textContent.replace(/\s+/g, '').replace(',', '.');
          const m = cleaned.match(/(\d{3,6}(?:\.\d{1,2})?)/);
          if (m) {
            report.gate5_system32_bom.bruttoPLN = +parseFloat(m[1]).toFixed(2);
            break;
          }
        }
      }
    }
  } catch (e) {
    report.gate5_system32_bom.extractError = String(e);
  }

  return report;
}
"""

STATIC_DEFECT_SIGNATURES = [
    ("locked_camera_view_reset", re.compile(r"if\s*\(\s*plc\.isLocked\s*\)[\s\S]{0,220}Math\.atan2\(-dir\.x,\s*-dir\.z\)")),
    ("zero_alpha_side_uv_beam", re.compile(r"smoothstep\(0\.0,\s*0\.35,\s*vUV\.x\)\s*\*\s*smoothstep\(0\.0,\s*0\.35,\s*1\.0\s*-\s*vUV\.x\)")),
    ("zero_alpha_box_alocal_beam", re.compile(r"float\s+ax\s*=\s*abs\(vLocal\.x\s*\*\s*2\.0\)[\s\S]{0,120}smoothstep\(1\.0,\s*0\.22,\s*ax\)")),
    ("zero_alpha_quad_auv_beam", re.compile(r"1\.0\s*-\s*smoothstep\(0\.52,\s*1\.0,\s*abs\(vuv\.x\)\)")),
    ("double_world_matrix_skinned_cat", re.compile(r"localToWorld\(new\s+THREE\.Vector3[\s\S]{0,260}geo\.applyMatrix4\(byName\[bone\]\.matrixWorld\)")),
    ("unreachable_cat_shelf_descent", re.compile(r"if\s*\(\s*CAT\.groundY\s*>\s*\.2\s*\)\s*\{\s*catSetState\('sit'\);\s*CAT\.jump\s*=\s*null;\s*\}")),
    ("sun_lastdir_undefined_throw", re.compile(r"SUN\.lastDir\.angleTo")),
    ("fov28_fake_ortho_elevation", re.compile(r"targetFov\s*=\s*28")),
    ("detached_root_reflector", re.compile(r"wardrobeGroup\.add\(mirrorReflector\)")),
    ("elev_cam_tween_override", re.compile(r"setMode\('cad'\);\s*elevView=!elevView;[\s\S]{0,120}camera\.position\.set\(0,1\.35,2\.35\)")),
]


def scan_static_signatures(html_path: Path) -> Dict[str, Any]:
    text = html_path.read_text(encoding="utf-8", errors="replace")
    sha256 = hashlib.sha256(text.encode("utf-8")).hexdigest()
    hits = [name for name, rx in STATIC_DEFECT_SIGNATURES if rx.search(text)]
    has_panner = bool(re.search(r"createPanner|PannerNode|PositionalAudio|createStereoPanner", text))
    has_reflector = bool(re.search(r"\bnew\s+Reflector\b|\bTHREE\.Reflector\b|CubeCamera|mirror", text, re.I))
    has_true_reflector = bool(re.search(r"\bnew\s+Reflector\b|\bTHREE\.Reflector\b|CubeCamera", text))
    has_ortho = bool(re.search(r"\bOrthographicCamera\b", text))
    has_instanced_holes = bool(re.search(r"InstancedMesh", text))
    has_pointer_lock = bool(re.search(r"requestPointerLock|PointerLockControls|pointerLockElement", text))
    has_quaternion_slerp = bool(re.search(r"\.slerp\s*\(|Quaternion", text))
    has_aabb_collision = bool(re.search(r"Box3|AABB|collide|blocked|clamp.*room|wall", text, re.I))
    has_volumetric_shader = bool(re.search(r"ShaderMaterial|gl_FragColor|godRay|sunbeam|volumetric", text, re.I))
    has_shadow_map = bool(re.search(r"PCFSoftShadowMap|shadow\.mapSize|castShadow\s*=\s*true", text))
    has_zero_ext_audio = not bool(re.search(r'src\s*=\s*["\'][^"\']+\.(mp3|wav|ogg)["\']', text, re.I))
    has_webaudio_synth = bool(re.search(r"AudioContext|webkitAudioContext|OfflineAudioContext", text))
    has_biquad_lpf = bool(re.search(r"createBiquadFilter|BiquadFilterNode|lowpass", text, re.I))
    has_cat_rig = bool(re.search(r"cat|kot|mruczek|purr|meow|jump", text, re.I))
    has_parabolic_jump = bool(re.search(r"jump|parabol|shelf_perch|JUMP_UP|jumpUp", text, re.I))
    has_system32 = bool(re.search(r"32\s*\*|/\s*32|%\s*32|37|System[\s-]*32|LINIA\s*32", text, re.I))
    has_vat_8_23 = bool(re.search(r"0\.08|1\.08|8%", text)) and bool(re.search(r"0\.23|1\.23|23%", text))
    has_blum_155 = bool(re.search(r"155|71B7550|CLIP\s*top|MOVENTO|Blum", text, re.I))
    has_egg_kronospan = bool(re.search(r"Egger|Kronospan|H1318|H3170|U999|K003", text, re.I))

    return {
        "file_bytes": len(text.encode("utf-8")),
        "sha256": sha256,
        "defect_signatures_triggered": hits,
        "static_capabilities": {
            "has_panner_node": has_panner,
            "has_planar_reflector": has_true_reflector,
            "has_mirror_surface": has_reflector,
            "has_orthographic_camera": has_ortho,
            "has_instanced_mesh": has_instanced_holes,
            "has_pointer_lock": has_pointer_lock,
            "has_quaternion_slerp": has_quaternion_slerp,
            "has_aabb_collision": has_aabb_collision,
            "has_volumetric_shader": has_volumetric_shader,
            "has_shadow_map": has_shadow_map,
            "has_zero_ext_audio": has_zero_ext_audio,
            "has_webaudio_synth": has_webaudio_synth,
            "has_biquad_lpf": has_biquad_lpf,
            "has_cat_rig": has_cat_rig,
            "has_parabolic_jump": has_parabolic_jump,
            "has_system32": has_system32,
            "has_vat_8_23": has_vat_8_23,
            "has_blum_155": has_blum_155,
            "has_egg_kronospan": has_egg_kronospan,
        },
    }


async def evaluate_candidate(
    sem: asyncio.Semaphore,
    playwright_instance,
    base_url: str,
    slug: str,
    label: str,
) -> Dict[str, Any]:
    index_path = OUT_DIR / slug / "index.html"
    self_qa_path = OUT_DIR / slug / "SELF-QA.md"
    size_bytes = index_path.stat().st_size if index_path.exists() else 0

    if size_bytes < 2000:
        return {
            "candidate": slug,
            "slug": slug,
            "label": label,
            "status": "BUILDING",
            "size_bytes": size_bytes,
            "size_kb": round(size_bytes / 1024, 1),
            "oracle_total_100": None,
            "oracle_score_out_of_70": None,
            "gates_passed_12": None,
            "gates_passed_16": None,
        }

    async with sem:
        t_start = time.time()
        static_info = scan_static_signatures(index_path)
        caps = static_info["static_capabilities"]
        defects = static_info["defect_signatures_triggered"]

        exe_candidates = [
            Path("/home/b00lean/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome"),
            Path("/home/b00lean/.cache/ms-playwright/chromium_headless_shell-1234/chrome-headless-shell-linux64/chrome-headless-shell"),
        ]
        exe_path = next((str(c) for c in exe_candidates if c.exists()), None)
        browser = await playwright_instance.chromium.launch(
            executable_path=exe_path,
            headless=True,
            args=[
                "--use-gl=angle",
                "--use-angle=swiftshader",
                "--enable-unsafe-swiftshader",
                "--enable-webgl",
                "--ignore-gpu-blocklist",
                "--autoplay-policy=no-user-gesture-required",
            ],
        )
        context = await browser.new_context(viewport={"width": 1280, "height": 720})
        await context.add_init_script(INIT_INSTRUMENTATION_JS)
        page = await context.new_page()

        console_errors: List[str] = []
        page_errors: List[str] = []
        failed_requests: List[str] = []

        page.on("console", lambda m: console_errors.append(m.text[:200]) if m.type == "error" else None)
        page.on("pageerror", lambda e: page_errors.append(str(e)[:240]))
        page.on("requestfailed", lambda r: failed_requests.append(r.url[:160]))

        t0 = time.time()
        rel_url = f"out/{slug}/index.html"
        try:
            await page.goto(f"{base_url}/{rel_url}", wait_until="load", timeout=45000)
            await page.wait_for_timeout(3500)
        except Exception as e:
            page_errors.append(f"goto_error: {str(e)[:180]}")
        boot_sec = round(time.time() - t0, 2)

        # Dismiss any intro modal or splash overlay
        try:
            await page.evaluate(
                """() => {
                  const splash = document.getElementById('splash');
                  if (splash) splash.click();
                  const btn = [...document.querySelectorAll('button')].find(
                    x => x.offsetParent && /wejd|enter|start|rozpocz/i.test(x.textContent)
                  );
                  if (btn) btn.click();
                }"""
            )
        except Exception:
            pass
        await page.wait_for_timeout(800)

        driver_logs = []
        for step_js in CANDIDATE_DRIVERS.get(slug, []):
            try:
                await page.evaluate(f"async () => {{ {step_js} }}")
                driver_logs.append({"step": step_js[:80], "status": "ok"})
            except Exception as e:
                driver_logs.append({"step": step_js[:80], "status": f"err: {str(e)[:120]}"})
            await page.wait_for_timeout(600)

        await page.wait_for_timeout(1000)
        probe_data = await page.evaluate(IN_PAGE_EVAL_JS, slug)
        await browser.close()
        eval_wall_sec = round(time.time() - t_start, 2)

        real_console_errs = [e for e in console_errors if "favicon" not in e.lower()]
        total_runtime_errs = len(real_console_errs) + len(page_errors)

        # Canonical 12-Gate Oracle (for backwards compatibility with V2-ORACLE-RESULTS.json)
        gates_12 = {
            "G0_zero_page_errors": len(page_errors) == 0,
            "G0_active_webgl_draws": probe_data["gate0_runtime"].get("drawCalls", 0) > 10,
            "G1_no_plc_view_reset": "locked_camera_view_reset" not in defects,
            "G1_true_ortho_camera": caps["has_orthographic_camera"] and ("fov28_fake_ortho_elevation" not in defects) and ("elev_cam_tween_override" not in defects),
            "G2_non_blank_webgl_pixels": bool(probe_data["gate2_webgl_pixels"].get("renderedNonBlankScene")),
            "G2_valid_godray_shader": "zero_alpha_side_uv_beam" not in defects,
            "G2_planar_reflector_wired": caps["has_planar_reflector"] and probe_data["gate0_runtime"].get("framebufferBinds", 0) > 0,
            "G3_spatial_panner_nodes": caps["has_panner_node"] and probe_data["gate3_webaudio_dsp"].get("pannerNodeCount", 0) > 0,
            "G3_window_lpf_biquad": probe_data["gate3_webaudio_dsp"].get("biquadFilterCount", 0) > 0,
            "G4_cat_mesh_contiguity": "double_world_matrix_skinned_cat" not in defects,
            "G5_bom_quote_reconciled": (probe_data["gate5_system32_bom"].get("bruttoPLN") or 0) > 3000,
            "G5_instanced_system32_or_selftest": caps["has_instanced_mesh"] or bool(probe_data["gate0_runtime"].get("selfTest", {}).get("ok")),
        }
        passed_12 = sum(1 for v in gates_12.values() if v)
        oracle_score_70 = round((passed_12 / len(gates_12)) * 70.0, 2)

        # Expanded 16-Gate v2.1 Behavioral & Shader Oracle on DELTA-AMD
        zero_alpha_any = any(
            d in defects for d in ("zero_alpha_side_uv_beam", "zero_alpha_box_alocal_beam", "zero_alpha_quad_auv_beam")
        )
        gates_16 = {
            **gates_12,
            "G2b_strict_non_zero_beam_uv": not zero_alpha_any,
            "G2c_attached_door_reflector": gates_12["G2_planar_reflector_wired"] and ("detached_root_reflector" not in defects),
            "G3c_zero_ext_audio_assets": caps["has_zero_ext_audio"] and caps["has_webaudio_synth"],
            "G4b_reachable_cat_shelf_descent": "unreachable_cat_shelf_descent" not in defects,
        }
        passed_16 = sum(1 for v in gates_16.values() if v)
        oracle_v21_score_70 = round((passed_16 / len(gates_16)) * 70.0, 2)

        # 4-Layer 100-Point Score (for V2-ORACLE-SCORECARD.md)
        mean_luma = probe_data["gate2_webgl_pixels"].get("meanLuminance", 0) or 0
        non_zero = probe_data["gate2_webgl_pixels"].get("nonBlackRatio", 0) or 0
        delta_luma = probe_data["gate2_webgl_pixels"].get("abDayNightDeltaLuma", 0) or 0

        l1 = 0.0
        if total_runtime_errs == 0:
            l1 += 10.0
        elif total_runtime_errs <= 2:
            l1 += 5.0
        if caps["has_pointer_lock"] and ("locked_camera_view_reset" not in defects):
            l1 += 5.0
        elif caps["has_pointer_lock"]:
            l1 += 2.0
        if caps["has_quaternion_slerp"]:
            l1 += 5.0
        if caps["has_aabb_collision"] and caps["has_orthographic_camera"] and ("fov28_fake_ortho_elevation" not in defects) and ("elev_cam_tween_override" not in defects):
            l1 += 5.0
        elif caps["has_aabb_collision"]:
            l1 += 2.5

        l2 = 0.0
        if probe_data["gate2_webgl_pixels"].get("hasGl") and non_zero >= 0.50 and mean_luma >= 5.0:
            l2 += 10.0
        elif probe_data["gate2_webgl_pixels"].get("hasGl") and non_zero > 0.10:
            l2 += 5.0
        if caps["has_volumetric_shader"] and not zero_alpha_any:
            l2 += 5.0
        elif caps["has_volumetric_shader"]:
            l2 += 2.0
        if caps["has_planar_reflector"] and ("detached_root_reflector" not in defects) and probe_data["gate0_runtime"].get("framebufferBinds", 0) > 0:
            l2 += 5.0
        elif caps["has_mirror_surface"]:
            l2 += 2.5
        if caps["has_shadow_map"]:
            l2 += 3.0
        if delta_luma >= 0.2 or caps["has_volumetric_shader"]:
            l2 += 2.0

        l3 = 0.0
        if caps["has_zero_ext_audio"] and caps["has_webaudio_synth"]:
            l3 += 8.0
        if caps["has_biquad_lpf"] and probe_data["gate3_webaudio_dsp"].get("biquadFilterCount", 0) > 0:
            l3 += 6.0
        elif caps["has_biquad_lpf"]:
            l3 += 3.0
        if caps["has_panner_node"] and probe_data["gate3_webaudio_dsp"].get("pannerNodeCount", 0) > 0:
            l3 += 6.0
        elif caps["has_panner_node"]:
            l3 += 2.0

        l4 = 0.0
        if caps["has_cat_rig"] and ("double_world_matrix_skinned_cat" not in defects):
            l4 += 7.0
        elif caps["has_cat_rig"]:
            l4 += 3.5
        if caps["has_parabolic_jump"] and ("unreachable_cat_shelf_descent" not in defects):
            l4 += 7.0
        elif caps["has_parabolic_jump"]:
            l4 += 3.5
        if caps["has_system32"]:
            l4 += 6.0
        if caps["has_vat_8_23"] and (probe_data["gate5_system32_bom"].get("bruttoPLN") or 0) > 3000:
            l4 += 5.0
        elif caps["has_vat_8_23"]:
            l4 += 2.5
        if caps["has_blum_155"] and caps["has_egg_kronospan"]:
            l4 += 5.0

        oracle_total_100 = round(l1 + l2 + l3 + l4, 1)

        j = LEAVE_ONE_OUT_JUDGES.get(slug)
        if j:
            raw_j = round((j["opus"] + j["astra"] + j["sol"]) / 3.0, 2)
            unbiased_vals = [v for k, v in [("opus", j["opus"]), ("astra", j["astra"]), ("sol", j["sol"])] if k != j["self"]]
            unbiased_j = round(sum(unbiased_vals) / len(unbiased_vals), 2)
            composite_v2 = round(0.60 * oracle_total_100 + 0.40 * unbiased_j, 2)
        else:
            raw_j = None
            unbiased_j = None
            composite_v2 = oracle_total_100

        print(
            f"[DELTA-AMD v2.1 Oracle] {slug:12s} | 12-Gate={passed_12:2d}/12 ({oracle_score_70:5.2f}/70) | "
            f"16-Gate={passed_16:2d}/16 ({oracle_v21_score_70:5.2f}/70) | 4-Layer={oracle_total_100:5.1f}/100 | "
            f"Draws={probe_data['gate0_runtime'].get('drawCalls', 0):6d} | "
            f"Panners={probe_data['gate3_webaudio_dsp'].get('pannerNodeCount', 0):2d} | "
            f"BOM={str(probe_data['gate5_system32_bom'].get('bruttoPLN')):8s} | {eval_wall_sec:.2f}s",
            flush=True,
        )

        return {
            "candidate": slug,
            "slug": slug,
            "label": label,
            "status": "LIVE",
            "size_bytes": size_bytes,
            "size_kb": round(size_bytes / 1024, 1),
            "has_self_qa": self_qa_path.exists(),
            "boot_seconds": boot_sec,
            "eval_wall_seconds": eval_wall_sec,
            "console_error_count": len(real_console_errs),
            "page_error_count": len(page_errors),
            "runtime_errors": total_runtime_errs,
            "failed_request_count": len(failed_requests),
            "page_errors_sample": page_errors[:3],
            "console_errors_sample": real_console_errs[:3],
            "static_analysis": static_info,
            "driver_steps": driver_logs,
            "runtime_probes": probe_data,
            "deterministic_gates": gates_12,
            "deterministic_gates_16": gates_16,
            "gates_passed": f"{passed_12}/{len(gates_12)}",
            "gates_passed_16": f"{passed_16}/{len(gates_16)}",
            "oracle_score_out_of_70": oracle_score_70,
            "oracle_v21_score_out_of_70": oracle_v21_score_70,
            "webgl_luma": mean_luma,
            "webgl_nonzero_ratio": non_zero,
            "webgl_ab_delta_luma": delta_luma,
            "layer1_runtime_camera_25": l1,
            "layer2_webgl_pixels_25": l2,
            "layer3_webaudio_dsp_20": l3,
            "layer4_cat_system32_30": l4,
            "oracle_total_100": oracle_total_100,
            "judge_raw_mean": raw_j,
            "judge_unbiased_mean": unbiased_j,
            "v2_composite_score": composite_v2,
        }


async def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--concurrency", type=int, default=4, help="Parallel Chromium instances on DELTA-AMD")
    args = parser.parse_args()

    class QuietHandler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, *h_args, **h_kwargs):
            super().__init__(*h_args, directory=str(PUBLIC_DIR), **h_kwargs)
        def do_GET(self):
            if self.path.startswith("/favicon.ico"):
                self.send_response(204)
                self.end_headers()
                return
            super().do_GET()
        def log_message(self, format, *args):
            pass

    httpd = socketserver.TCPServer(("127.0.0.1", 0), QuietHandler)
    port = httpd.server_address[1]
    server_thread = threading.Thread(target=httpd.serve_forever, daemon=True)
    server_thread.start()
    base_url = f"http://127.0.0.1:{port}"

    sem = asyncio.Semaphore(args.concurrency)
    t_suite = time.time()
    async with async_playwright() as pw:
        tasks = [
            evaluate_candidate(sem, pw, base_url, slug, label)
            for slug, label in CANDIDATES
        ]
        all_results = await asyncio.gather(*tasks)

    httpd.shutdown()
    suite_wall_s = round(time.time() - t_suite, 2)

    live_results = [r for r in all_results if r["status"] == "LIVE"]
    building_results = [r for r in all_results if r["status"] != "LIVE"]

    # Write V2-ORACLE-RESULTS.json (12-Gate + 16-Gate expanded schema)
    v2_oracle_summary = {
        "schema": "borkbork.v2_deterministic_oracle.v2.1",
        "generated_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "host_node": platform.node(),
        "cpu_threads": os.cpu_count(),
        "suite_wall_seconds": suite_wall_s,
        "oracle_model": "70/30 Deterministic Execution Oracle (12-Gate & 16-Gate v2.1) + Cryptographic Blinded Arena",
        "candidate_count": len(live_results),
        "building_candidates": [r["slug"] for r in building_results],
        "leaderboard_by_oracle_70": sorted(
            [
                {
                    "candidate": r["candidate"],
                    "gates_passed": r["gates_passed"],
                    "oracle_score_70": r["oracle_score_out_of_70"],
                    "gates_passed_16": r["gates_passed_16"],
                    "oracle_v21_score_70": r["oracle_v21_score_out_of_70"],
                    "oracle_4layer_100": r["oracle_total_100"],
                    "v2_composite_score": r["v2_composite_score"],
                    "page_errors": r["page_error_count"],
                    "webgl_draws": r["runtime_probes"]["gate0_runtime"].get("drawCalls"),
                    "instanced_draws": r["runtime_probes"]["gate0_runtime"].get("instancedDrawCalls"),
                    "framebuffer_binds": r["runtime_probes"]["gate0_runtime"].get("framebufferBinds"),
                    "panner_nodes": r["runtime_probes"]["gate3_webaudio_dsp"].get("pannerNodeCount"),
                    "biquad_filters": r["runtime_probes"]["gate3_webaudio_dsp"].get("biquadFilterCount"),
                    "bom_brutto_pln": r["runtime_probes"]["gate5_system32_bom"].get("bruttoPLN"),
                    "defect_signatures": r["static_analysis"]["defect_signatures_triggered"],
                }
                for r in live_results
            ],
            key=lambda x: (-x["oracle_v21_score_70"], -x["oracle_score_70"], x["page_errors"]),
        ),
        "candidates": live_results,
    }
    (RESEARCH_DIR / "V2-ORACLE-RESULTS.json").write_text(
        json.dumps(v2_oracle_summary, indent=2, ensure_ascii=False), encoding="utf-8"
    )

    # Also write v2-oracle-results.json (4-Layer scorecard schema)
    (RESEARCH_DIR / "v2-oracle-results.json").write_text(
        json.dumps(
            {
                "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                "host_node": platform.node(),
                "suite_wall_seconds": suite_wall_s,
                "results": all_results,
            },
            indent=2,
            ensure_ascii=False,
        ),
        encoding="utf-8",
    )
    print(f"[DELTA-AMD v2.1 Oracle] Completed in {suite_wall_s}s across {len(live_results)} live builds.", flush=True)


if __name__ == "__main__":
    asyncio.run(main())
