Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

79.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  Headless render verification runner (docs/REARCH_EDITOR_AUTOMATION.md P1).
 *
 * A standalone Electron entry — NOT the editor's production main — that proves a
 * scene renders by driving the headless render host: it static-serves the built
 * dist/ over loopback http (an http origin is required; the engine resolves its
 * wasm glue from location.origin, which file:// roots wrong), opens a show:false
 * window on headless.html, then loadScene → step → captureViewport and asserts
 * the frame is actually rasterized (color variation, not a uniform clear).
 *
 * This is the repeatable, in-repo form of the capability — `pnpm verify:render`.
 * It runs by Electron (for a real WebGL2 context), so it imports only `electron`
 * and node built-ins. Parametrize via env to point it at other scenes:
 *   ESTELLA_VERIFY_SCENE     scene url   (default the dev sprite scene)
 *   ESTELLA_VERIFY_MANIFEST  texture manifest url
 *   ESTELLA_VERIFY_W / _H    capture size (default 640×480)
 *   ESTELLA_VERIFY_STEPS     fixed-dt frames to advance before capture (default 30)
 *   ESTELLA_VERIFY_GRID      editor-grid on/off pixel-diff assertion (value = spacing)
 *   ESTELLA_VERIFY_GRID_EXPECT  what that diff must be: "frame" (default) or "nothing"
 *   ESTELLA_VERIFY_GRID_RESPACE  respace the drawn grid; the frame must change with it
 *   ESTELLA_VERIFY_DEVICE_LOSS  1 | auto | roundtrip (lose the device; roundtrip compares the frame)
 *   ESTELLA_VERIFY_LOSS_GRID  draw the editor grid through a roundtrip (value = spacing)
 *   ESTELLA_VERIFY_DEPTH_LAYERS  bitmask of layers resolved by depth (2.5D)
 *   ESTELLA_VERIFY_RENDER_RESOLUTION  render at the scene's own resolution and
 *                                scale the finished image (1 = design, 2 = integer)
 *   ESTELLA_VERIFY_PREFAB    .esprefab instantiated into the scene after load
 *   ESTELLA_VERIFY_SET_FIELD one inspector field written after load (JSON)
 *   ESTELLA_VERIFY_ANIMATOR  drive an animator to a point in time (JSON)
 *   ESTELLA_VERIFY_PICK      hit-test a viewport point, asserting the entity (JSON)
 *   ESTELLA_VERIFY_ORBIT     turn the editor eye before capture ("yaw,pitch" degrees)
 *   ESTELLA_VERIFY_STUDIO    the editor view's studio lighting and exposure (JSON: see the block)
 *   ESTELLA_VERIFY_SHADING   the editor view's clay and albedo shading (any non-empty value; see the block)
 *   ESTELLA_VERIFY_LIGHTING_SPLIT  the editor view's direct-only and indirect-only lighting against clay (see the block)
 *   ESTELLA_VERIFY_SKIN_WEIGHTS  colour a skinned entity by joint weights (JSON {id, joints}; see the block)
 *   ESTELLA_VERIFY_COUNTERS  engine counters the drawn frame must report (JSON)
 *   ESTELLA_VERIFY_COUNTERS_MAX  counters the frame must stay UNDER — a budget (JSON)
 *   ESTELLA_VERIFY_COUNTERS_MIN  counters the frame must reach at least — that something happened at all (JSON)
 *   ESTELLA_VERIFY_GPU_PASSES  print|require — the GPU time of each render-graph pass on this backend (local; needs a timer)
 *   ESTELLA_VERIFY_FRAME_DEBUG  capture the frame and replay it (the frame debugger)
 *   ESTELLA_VERIFY_UNIFORM   the frame is one colour on purpose; ESTELLA_VERIFY_COUNT says which
 *   ESTELLA_VERIFY_EDGE      how straight a straight edge is drawn (JSON: box, lit, dark, maxJag)
 *   ESTELLA_VERIFY_CUTOUT_EDGE  how often a cutout's edge pixel is a blend (JSON: box, lit, run, partial, minShare)
 *   ESTELLA_VERIFY_TWINS     pairs of points that must match (JSON: pairs [[x1,y1,x2,y2]], tol)
 *   ESTELLA_VERIFY_MINIFIED  how much a far-off texture shimmers pixel to pixel (JSON: box, maxRipple, minMean)
 *   ESTELLA_VERIFY_SCALE     copy the scene's content onto a grid (JSON), for a cost gate
 *   ESTELLA_VERIFY_OUTPUT_TRANSFORM  the frame's output curve ("aces" or "neutral")
 *   ESTELLA_VERIFY_MSAA      multisample count the scene asks for (the app's default otherwise)
 *   ESTELLA_VERIFY_PREPASS   1: draw the opaque scene twice, depth alone first (what a quality level does)
 *   ESTELLA_VERIFY_TEXTURES  "runtime": images upload through the engine, as a shipped game's do
 *   ESTELLA_VERIFY_PROFILE   record N further frames and report the TS/C++ cost split
 *   ESTELLA_VERIFY_TIMEOUT_MS  how long this run may take before it reports one
 */
import { app, BrowserWindow } from 'electron';

// The launcher that started this reads its output through a pipe. If that launcher is stopped, the pipe is gone and the next line printed
// would raise an uncaught exception, which Electron shows as a dialog box: a run nobody is listening to ends quietly instead.
for (const stream of [process.stdout, process.stderr]) stream.on('error', () => app.exit(0));
import os from 'node:os';
import { writeFile } from 'node:fs/promises';
import { appendFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { onRendererConsole } from '../lib/rendererConsole.mjs';
import { serveHost } from '../lib/staticServer.mjs';
import { checkSeam } from '../lib/seamProbe.mjs';
import { checkNineSliceCorners } from '../lib/nineSliceProbe.mjs';

// SwiftShader rasterizes on the CPU; run the whole electron tree below normal
// priority (child processes inherit the class) so a verify never starves the
// machine. Must happen before the renderer process spawns.
try {
  os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);
} catch { /* not fatal — some sandboxes forbid it */ }

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');

// Two hosts answer the same driving surface. The engine's is the default — a
// gate about the renderer should not need an editor to run — and the editor's
// keeps the handful whose subject IS an editor door.
const HOSTS = {
  engine: { dist: path.join(ROOT, 'build', 'render-host'), page: 'index.html' },
  editor: { dist: path.join(ROOT, 'desktop', 'dist'), page: 'headless.html' },
};
const HOST = process.env.ESTELLA_VERIFY_HOST ?? 'engine';
if (!HOSTS[HOST]) {
  console.error(`verify: unknown host "${HOST}" (have: ${Object.keys(HOSTS).join(', ')})`);
  process.exit(2);
}
const DIST = HOSTS[HOST].dist;
const PAGE = HOSTS[HOST].page;

const SCENE = process.env.ESTELLA_VERIFY_SCENE ?? '/scenes/sprite-rendering.esscene';
const MANIFEST = process.env.ESTELLA_VERIFY_MANIFEST ?? '/scenes/sprite-rendering.textures.json';
const W = Number(process.env.ESTELLA_VERIFY_W) || 640;
const H = Number(process.env.ESTELLA_VERIFY_H) || 480;
const STEPS = Number(process.env.ESTELLA_VERIFY_STEPS) || 30;
const ROUNDS = Number(process.env.ESTELLA_VERIFY_LOSS_ROUNDS) || 1;
// ESTELLA_VERIFY_BACKEND=webgpu runs the same scene + assertions on the WebGPU
// backend (needs a real adapter — local runs; CI runners have none).
const BACKEND = process.env.ESTELLA_VERIFY_BACKEND === 'webgpu' ? 'webgpu' : 'webgl2';
// ESTELLA_VERIFY_COLORSPACE=linear boots the linear-light pipeline (sRGB decode
// + linear blending + final OETF) — point expectations must be linear-derived.
const COLORSPACE = process.env.ESTELLA_VERIFY_COLORSPACE === 'linear' ? 'linear' : '';
// ESTELLA_VERIFY_OUTPUT_TRANSFORM=aces boots the project output transform, which
// is a curve on the way out and engages the capture on its own.
const OUTPUT_TRANSFORM = ['aces', 'neutral'].includes(process.env.ESTELLA_VERIFY_OUTPUT_TRANSFORM) ? process.env.ESTELLA_VERIFY_OUTPUT_TRANSFORM : '';
const MSAA = process.env.ESTELLA_VERIFY_MSAA ?? '';
const PREPASS = process.env.ESTELLA_VERIFY_PREPASS === '1';
const TEXTURES = process.env.ESTELLA_VERIFY_TEXTURES === 'runtime' ? 'runtime' : '';
// A scene whose emitters roll dice has no constant to assert until the run is
// seeded; the engine seeds itself from the clock when nobody says otherwise.
const SEED = process.env.ESTELLA_VERIFY_SEED ?? '';
// A cost gate's scene is a small fixture plus a count — see the loadScene call.
const SCALE = process.env.ESTELLA_VERIFY_SCALE ?? '';
// ESTELLA_VERIFY_DEPTH_LAYERS=<mask> turns layers into depth-resolved ones (2.5D).
const DEPTH_LAYERS = process.env.ESTELLA_VERIFY_DEPTH_LAYERS ?? '';
// ESTELLA_VERIFY_RENDER_RESOLUTION=<RenderResolution> renders the scene at its own
// resolution and scales the finished image to the surface (1 = design, 2 = integer).
const RENDER_RESOLUTION = process.env.ESTELLA_VERIFY_RENDER_RESOLUTION ?? '';

// Headless / GPU-less (CI) WebGL2 falls back to SwiftShader; harmless with a GPU.
app.commandLine.appendSwitch('enable-unsafe-swiftshader');
// CI's Linux runner has no GPU and rasterises in software, which is a different
// machine from any developer's. Reproducing a CI-only failure needs that
// machine, so ask for it explicitly rather than guessing from a log.
if (process.env.ESTELLA_VERIFY_SOFTWARE_GPU) app.commandLine.appendSwitch('disable-gpu');
// The GPU process runs its own sandbox, which ELECTRON_DISABLE_SANDBOX does not
// reach: on a runner with no device it died before any scene drew, on every
// retry. Harmless with a GPU — this is a headless verifier, not a shipped app.
app.commandLine.appendSwitch('disable-gpu-sandbox');
// ...and on Linux there is no GPU process at all. One Electron per scene meant
// 85 races between the page asking for WebGL2 and the service able to answer,
// and two in three lost. Same SwiftShader in-process, so the same pixels.
if (process.platform === 'linux') app.commandLine.appendSwitch('in-process-gpu');
// Pins the profile for anything that goes through the compositor (a screenshot
// for a human). The pixel assertions do not: a composited read is colour
// managed, turning rgb(0,255,0) into rgb(58,254,32) switch or no switch.
app.commandLine.appendSwitch('force-color-profile', 'srgb');
// ...and the same for the SIZE of a device pixel: this canvas is never attached to
// a document, so its rect is zeros and a client coordinate reaches the hit test as
// `client * devicePixelRatio` — whatever the machine's display happens to scale by.
app.commandLine.appendSwitch('force-device-scale-factor', '1');
// WebGPU: the unsafe flag covers non-default platforms (Linux CI); the optional
// software adapter (ESTELLA_VERIFY_WEBGPU_ADAPTER=swiftshader) gives GPU-less
// runners a real Dawn adapter through the bundled SwiftShader Vulkan — the
// WebGPU analog of the WebGL fallback above.
if (BACKEND === 'webgpu') {
  app.commandLine.appendSwitch('enable-unsafe-webgpu');
  if (process.env.ESTELLA_VERIFY_WEBGPU_ADAPTER) {
    app.commandLine.appendSwitch('use-webgpu-adapter', process.env.ESTELLA_VERIFY_WEBGPU_ADAPTER);
  }
}
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';

function finish(result, server) {
  // Both modes assert the loss was seen and reported and the device ended Live
  // with nothing left on the placeholder. Only the driven mode asserts the steps
  // between: the auto mode has none, which is the point of it.
  const dl = result.deviceLoss;
  const lossSeen = !dl || (dl.supported && dl.statusAfterLoss === 1
    && (dl.reportAfterLoss?.length ?? 0) > 0);
  // Every round, not just the last: a recovery can work once and never again,
  // which is what a single round reports as a pass.
  const cameBack = !dl || ((dl.statusAfterFull === 0 && (dl.awaitingAfterFull?.length ?? 0) === 0)
    && (dl.rounds ?? []).every((r) => r.status === 0 && (r.awaiting?.length ?? 0) === 0));
  // Recovering exactly while something is owed: a device with nothing left to
  // refill is whole the moment it is rebuilt, and one that still owes is not.
  const owedAfterRecover = (dl?.awaitingAfterRecover?.length ?? 0) + (dl?.meshesOwedAfterRecover?.length ?? 0);
  const drivenSteps = !dl || dl.mode === 'auto' || (dl.glLostAfterRestore === false
    && dl.recovered === true && dl.statusAfterRecover === (owedAfterRecover > 0 ? 2 : 0)
    && dl.fullRecovered === true);
  // Objects the dead context minted that nobody released — visible only across
  // rounds. From the SECOND, so the first recovery's one-off costs are not read
  // as a slope. What the ENGINE owns comes back to the same size, full stop: a
  // program it re-creates on every rebuild without releasing the last is a leak
  // the round count makes obvious and a single round never can.
  const rounds = dl?.rounds ?? [];
  const growthOk = rounds.length < 3 || ((first, last, spans) => {
    const owned = ['programs', 'textures', 'vaos', 'framebuffers']
      .every((k) => last.tables[k] <= first.tables[k]);
    // Buffers get one allowance per rebuild: the host mints an internal buffer
    // for each WebGL context it creates, and no engine call names it.
    return owned && (last.tables.buffers - first.tables.buffers) <= spans;
  })(rounds[1], rounds[rounds.length - 1], rounds.length - 2);
  // Geometry, which the pixels cannot speak for: a recovery that minted fresh
  // handles draws the same frame as one that put the geometry back behind the
  // old ones. Same identity set, every one realized, nothing still owed.
  const meshIdentityOk = !dl || !dl.meshesBefore?.length || (() => {
    const before = dl.meshesBefore;
    const after = dl.meshesAfterFull ?? [];
    const by = (rows) => new Map(rows.map((m) => [m.handle, m]));
    const [b, a] = [by(before), by(after)];
    if (b.size !== a.size) return false;
    for (const handle of b.keys()) {
      if (!a.get(handle)?.realized) return false;
    }
    if ((dl.meshesOwedAfterFull?.length ?? 0) !== 0) return false;
    // Between the rebuild and the replay, what is not realized is exactly what
    // the engine says it is owed: a mesh missing from the ledger never comes back.
    if (dl.mode !== 'auto') {
      const unrealized = (dl.meshesAfterRecover ?? []).filter((m) => !m.realized).length;
      if ((dl.meshesAfterRecover?.length ?? 0) !== before.length) return false;
      if ((dl.meshesOwedAfterRecover?.length ?? 0) !== unrealized) return false;
    }
    return true;
  })();
  // Programs come back behind their handles, so readiness taken before a rebuild
  // is still true. An epoch that moves would re-derive readiness nothing lost.
  const epochOk = !dl || dl.epochBefore < 0 || dl.epochAfterFull === dl.epochBefore;
  // The two are independent on purpose. A rebuilt device that left readiness
  // untouched, or readiness invalidated on a device that never moved, are both
  // states nothing downstream could reason about.
  const genOk = !dl || dl.genBefore === undefined || dl.genBefore < 0
    || dl.mode === 'auto' || dl.genAfterFull > dl.genBefore;
  const deviceLossOk = lossSeen && cameBack && drivenSteps && growthOk && meshIdentityOk
    && epochOk && genOk;
  // Freezing nothing would pass every pixel assertion by not having changed the
  // scene — the shape of a check that cannot fail.
  const meshOk = (!result.meshResident || result.meshResident.frozen > 0)
    && (!result.meshAsset || result.meshAsset.pointed > 0)
    && (!result.meshMaterial || result.meshMaterial.applied > 0)
    && (!result.meshPrefab || result.meshPrefab.spawned > 0);
  // A hit test answering the wrong entity (or nothing) is the box being wrong,
  // which no pixel in the frame can show.
  const pickOk = !result.pick || result.pick.hit === result.pick.want;
  // A frame of one colour reads as a bare clear. Where one colour IS the answer, a
  // count of that colour is what proves something drew it.
  const uniformByDesign = Boolean(process.env.ESTELLA_VERIFY_UNIFORM) && result.count?.ok === true;
  // The studio gate's own last frame is the scene's, which for the scene with no light is
  // black on purpose; what proves a frame was drawn there is the studio frame it measured.
  const studioDrew = result.studio?.ok === true && (result.studio.S?.litShare ?? 0) > 0;
  const shadingDrew = result.shading?.ok === true && (result.shading.C?.litShare ?? 0) > 0;
  const weightsDrew = result.skinWeights?.ok === true;
  const renderedOk = (result.capture?.rendered ?? false) || uniformByDesign || studioDrew || shadingDrew || weightsDrew;
  // A scene that could not load an asset it names draws a frame nobody declared, so
  // its pixels answer a different question — say which asset instead.
  const assetsOk = (result.missingAssets?.length ?? 0) === 0;
  const ok = result.ok && renderedOk && assetsOk && (result.expect?.ok ?? true) && (result.twins?.ok ?? true) && (result.count?.ok ?? true) &&
    (result.seam?.ok ?? true) && (result.nineSlice?.ok ?? true) &&
    (result.resize?.ok ?? true) && (result.preview?.ok ?? true) &&
    (result.meshPreview?.ok ?? true) && (result.grid?.ok ?? true) && (result.studio?.ok ?? true) && (result.shading?.ok ?? true) && (result.skinWeights?.ok ?? true) &&
    (result.draws?.ok ?? true) && (result.lightingSplit?.ok ?? true) && (result.counters?.ok ?? true) && (result.gpuPasses?.ok ?? true) && (result.gpuFrame?.ok ?? true) && (result.frameDebug?.ok ?? true) && (result.edge?.ok ?? true) && (result.cutoutEdge?.ok ?? true) && (result.minified?.ok ?? true) &&
    (result.roundtrip?.ok ?? true) && deviceLossOk && meshOk && pickOk;
  const why = assetsOk ? '' : `: could not load ${result.missingAssets.join(', ')}`;
  console.log(`\n[verify:render] ${ok ? 'PASS' : 'FAIL'} — ${SCENE} (${BACKEND})${why}`);
  console.log('DRIVE_RESULT ' + JSON.stringify(result));
  try {
    server?.close();
  } catch {
    /* ignore */
  }
  // app.exit, not process.exitCode + app.quit: Electron leaves the process with
  // status 0 on quit whatever exitCode says, so the FAIL above was printed and
  // then reported as a pass to everything that ran this.
  app.exit(ok ? 0 : 1);
}

app.whenReady().then(async () => {
  let server;
  try {
    server = await serveHost(DIST);
    const url = `http://127.0.0.1:${server.address().port}/${PAGE}?w=${W}&h=${H}&backend=${BACKEND}${COLORSPACE ? `&colorSpace=${COLORSPACE}` : ''}${OUTPUT_TRANSFORM ? `&outputTransform=${OUTPUT_TRANSFORM}` : ''}${MSAA ? `&msaa=${MSAA}` : ''}${PREPASS ? '&prepass=1' : ''}${TEXTURES ? `&textures=${TEXTURES}` : ''}${DEPTH_LAYERS ? `&depthLayers=${DEPTH_LAYERS}` : ''}${RENDER_RESOLUTION ? `&renderResolution=${RENDER_RESOLUTION}` : ''}${SEED ? `&seed=${SEED}` : ''}${process.env.ESTELLA_VERIFY_NO_COMPUTE === '1' ? '&noCompute=1' : ''}${process.env.ESTELLA_VERIFY_GL_TRACE ? '&gltrace=1' : ''}`;

    // useContentSize: the capture rectangle must be the page area, not the
    // outer frame (the same trap the parity runner documents).
    const win = new BrowserWindow({
      show: false, width: W, height: H, useContentSize: true,
      webPreferences: { offscreen: false },
    });
    // ESTELLA_VERIFY_GL_TRACE=<file>: every shader compiled, program linked, program used and draw made, in order, written to the
    // file as the page makes them — with each program's sources — so a GPU process that dies mid-frame leaves the call it died on as
    // the last line. Lines arrive through the console because the page may not live to be asked.
    const GL_TRACE = process.env.ESTELLA_VERIFY_GL_TRACE || '';
    if (GL_TRACE) writeFileSync(GL_TRACE, '');
    onRendererConsole(win.webContents, (msg) => {
      if (GL_TRACE && msg.startsWith('GLTRACE ')) { appendFileSync(GL_TRACE, msg.slice(8) + '\n'); return; }
      // `webgpu` spelled out: "webgl" does not match it, so the second backend's
      // boot — including which adapter served it — was the one thing never shown.
      // ESTELLA_VERIFY_CONSOLE=all: every line, whole. A WebGPU validation message names the call and the texture and none of the words below.
      if (process.env.ESTELLA_VERIFY_CONSOLE === 'all') { console.log('[renderer]', msg); return; }
      if (/error|fail|unwind|exception|webgl|webgpu|adapter|recovery|placeholder/i.test(msg)) console.log('[renderer]', msg.slice(0, 240));
    });
    await win.loadURL(url);

    const exec = (code) => win.webContents.executeJavaScript(code, true);
    let deviceLoss = null;
    let meshResident = null;
    let meshAsset = null;
    let cameraTarget = null;
    let meshMaterial = null;
    let meshPrefab = null;
    let setField = null;
    let animator = null;
    let pick = null;
    await exec('window.__estellaHeadless.ready');
    // ESTELLA_VERIFY_SCALE = {"copies":N,"cols":C,"spacing":[x,y]}: the fixture holds ONE
    // of the thing being measured and this lays N of it out on a grid — a scale scene as a
    // FILE would be a megabyte of JSON in every clone, for a pure function of those two.
    const { entities: entityCount, missing: missingAssets } = await exec(
      `window.__estellaHeadless.api.loadScene(${JSON.stringify(SCENE)}, ${JSON.stringify(MANIFEST)}`
      + `${SCALE ? ', ' + JSON.stringify(JSON.parse(SCALE)) : ''})`,
    );
    // Opt-in play mode (ESTELLA_VERIFY_PLAY=1): runs the SDK plugin updates — particle
    // emission/simulation, animation — so time-driven content actually renders.
    if (process.env.ESTELLA_VERIFY_PLACEMENTS) {
      for (const { entity, transforms } of JSON.parse(process.env.ESTELLA_VERIFY_PLACEMENTS)) {
        await exec(`window.__estellaHeadless.api.setMeshPlacements(${Number(entity)}, ${JSON.stringify(transforms)})`);
      }
    }
    if (process.env.ESTELLA_VERIFY_PLAY === '1') {
      await exec('window.__estellaHeadless.api.setRunMode(true)');
    }
    // The engine's per-frame counters are only recorded while profiling is on, and
    // it goes on BEFORE the steps: what is read afterwards is the last frame's.
    if (process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX || process.env.ESTELLA_VERIFY_COUNTERS_MIN || process.env.ESTELLA_VERIFY_FRAME_DEBUG || PREPASS) {
      await exec('window.__estellaHeadless.api.setCpuProfiling(true)');
    }
    // Project render config stand-in: ESTELLA_VERIFY_YSORT = layer bitmask
    // (Project Settings → Rendering → Y-sorted layers in a real project).
    if (process.env.ESTELLA_VERIFY_YSORT) {
      await exec(`window.__estellaHeadless.api.setYSortLayers(${Number(process.env.ESTELLA_VERIFY_YSORT)})`);
    }
    // ESTELLA_VERIFY_TRAIL = {"from":[x,y[,z]],"to":[x,y[,z]],"steps":N}: move the
    // entity carrying a TrailRenderer along a world-space path, one frame per
    // sample, so the trail system records points. A third component drives depth.
    // Requires play mode (ESTELLA_VERIFY_PLAY=1) for the trail update to run.
    // ESTELLA_VERIFY_MOVE = {"component":"TilemapLayer","to":[x,y],"steps":N}:
    // after the scene settles, teleport the first entity carrying the named
    // component to a world position and step N frames — proves render paths
    // that cache geometry still track a moving entity (e.g. tilemap origin).
    if (process.env.ESTELLA_VERIFY_MOVE) {
      const move = JSON.parse(process.env.ESTELLA_VERIFY_MOVE);
      await exec(`(async () => {
        const cfg = ${JSON.stringify(move)};
        const api = window.__estellaHeadless.api;
        const flat = [];
        const walk = (nodes) => { for (const n of nodes) { flat.push(n.id); if (n.children) walk(n.children); } };
        walk(api.getSceneTree());
        const want = cfg.component.replace(/\\s+/g, '');
        let target = null;
        for (const id of flat) {
          const e = api.getEntity(id);
          if (e && e.components && e.components.some((c) => c.replace(/\\s+/g, '') === want)) { target = id; break; }
        }
        if (target == null) throw new Error('no ' + cfg.component + ' entity in scene');
        await api.step(2, 1 / 60);
        api.setEntityXY(target, cfg.to[0], cfg.to[1]);
        await api.step(cfg.steps ?? 2, 1 / 60);
      })()`);
    }
    if (process.env.ESTELLA_VERIFY_WARM) {
      const warmed = await exec(`window.__estellaHeadless.api.warm(${Number(process.env.ESTELLA_VERIFY_WARM) > 1 ? Number(process.env.ESTELLA_VERIFY_WARM) : 60000})`);
      if (warmed.timedOut) throw new Error(`warm: the scene was still being made after ${Math.round(warmed.ms)} ms (${warmed.pending} shader(s) compiling)`);
    }
    if (process.env.ESTELLA_VERIFY_TRAIL) {
      const trail = JSON.parse(process.env.ESTELLA_VERIFY_TRAIL);
      await exec(`(async () => {
        const cfg = ${JSON.stringify(trail)};
        const api = window.__estellaHeadless.api;
        const flat = [];
        const walk = (nodes) => { for (const n of nodes) { flat.push(n.id); if (n.children) walk(n.children); } };
        walk(api.getSceneTree());
        // getEntity().components returns humanized display names ("Trail Renderer"),
        // so compare with whitespace stripped.
        let target = null;
        for (const id of flat) {
          const e = api.getEntity(id);
          if (e && e.components && e.components.some((c) => c.replace(/\\s+/g, '') === 'TrailRenderer')) { target = id; break; }
        }
        if (target == null) throw new Error('no TrailRenderer entity in scene');
        const [fx, fy, fz] = cfg.from, [tx, ty, tz] = cfg.to, N = cfg.steps;
        for (let i = 0; i <= N; i++) {
          const t = N === 0 ? 1 : i / N;
          const z = fz === undefined ? undefined : fz + ((tz ?? fz) - fz) * t;
          api.setEntityXY(target, fx + (tx - fx) * t, fy + (ty - fy) * t, z);
          await api.step(1, 1 / 60);
        }
      })()`);
    } else if (process.env.ESTELLA_VERIFY_SETTLE_MS) {
      // Real-time settle: some content decodes on the wall clock, not engine dt
      // — video (HTMLVideoElement) decodes frames in real time and its system
      // uploads the newest frame each tick. Interleave engine steps with real
      // delays so frames actually arrive before the capture. Requires play mode.
      // ESTELLA_VERIFY_SETTLE_STEPS: at least this many steps as well. Content that takes frames rather than time — a
      // probe capture draws a face a frame — would otherwise lose the race on a loaded machine, whose steps run slow.
      const ms = Number(process.env.ESTELLA_VERIFY_SETTLE_MS) || 1500;
      const minSteps = Number(process.env.ESTELLA_VERIFY_SETTLE_STEPS) || 0;
      await exec(`(async () => {
        const api = window.__estellaHeadless.api;
        const end = performance.now() + ${ms};
        for (let n = 0; performance.now() < end || n < ${minSteps}; n++) {
          await api.step(1, 1 / 60);
          await new Promise((r) => setTimeout(r, 16));
        }
      })()`);
    } else {
      await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);
    }

    // ESTELLA_VERIFY_PROFILE = N: record N more frames through the SDK's own
    // ProfileRecorder — TS system ms beside the engine's C++ scope ms. Recorded
    // AFTER the steps above, so scene load is not charged to a frame.
    let profile = null;
    if (process.env.ESTELLA_VERIFY_PROFILE) {
      const n = Number(process.env.ESTELLA_VERIFY_PROFILE) || 60;
      await exec('window.__estellaHeadless.api.startProfile()');
      await exec(`window.__estellaHeadless.api.step(${n}, 1 / 60)`);
      profile = await exec('window.__estellaHeadless.api.takeProfile()');
    }

    // Loads an .esmesh through the asset layer and points the scene's meshes at
    // it, replacing their inline geometry. The fixture holds the SAME vertices,
    // so the assertions stand: a file drawing what the scene draws is the claim.
    if (process.env.ESTELLA_VERIFY_MESH_ASSET) {
      meshAsset = await exec(`(async () => {
        const pointed = await window.__estellaHeadless.loadMeshAsset(
          ${JSON.stringify(process.env.ESTELLA_VERIFY_MESH_ASSET)});
        await window.__estellaHeadless.api.step(2, 1 / 60);
        return { pointed };
      })()`);
    }

    // ESTELLA_VERIFY_CAMERA_TARGET={"camera","sprite","width","height"}: point a
    // camera at an offscreen texture and show that texture on a sprite. Nothing
    // else can produce the probe's colour, so it says the camera drew there.
    if (process.env.ESTELLA_VERIFY_CAMERA_TARGET) {
      const spec = JSON.parse(process.env.ESTELLA_VERIFY_CAMERA_TARGET);
      cameraTarget = await exec(`(async () => {
        const out = window.__estellaHeadless.renderToTexture(${JSON.stringify(spec)});
        await window.__estellaHeadless.api.step(3, 1 / 60);
        return out;
      })()`);
    }

    // ESTELLA_VERIFY_ANIMATOR={"entity","param","value","warmup","frames"}: settle,
    // write one animator parameter, advance a FIXED number of frames. A crossfade
    // is a stretch of time, so a gate wanting a point inside one must stop at it.
    if (process.env.ESTELLA_VERIFY_ANIMATOR) {
      const spec = JSON.parse(process.env.ESTELLA_VERIFY_ANIMATOR);
      animator = await exec(`(async () => {
        const api = window.__estellaHeadless.api;
        api.setRunMode(true);
        await api.step(${Number(spec.warmup ?? 2)}, 1 / 60);
        api.setAnimatorParam(${JSON.stringify(spec.entity)},
                             ${JSON.stringify(spec.param)}, ${JSON.stringify(spec.value)});
        const before = api.animatorReport(${JSON.stringify(spec.entity)});
        await api.step(${Number(spec.frames ?? 1)}, 1 / 60);
        const after = api.animatorReport(${JSON.stringify(spec.entity)});
        return { param: ${JSON.stringify(spec.param)}, frames: ${Number(spec.frames ?? 1)},
                 before, after };
      })()`);
    }

    // ESTELLA_VERIFY_SET_FIELD={"entity","component","key","value"} writes one
    // inspector field the way the editor's own door does, then waits: an asset
    // assigned after load is COLD, and reaching the World is an async load away.
    // An ARRAY of those is a route rather than a position, which is what a gate
    // about where a frame CAME FROM needs — the LOD hysteresis gates park one
    // object at one place along two different roads and read two answers.
    if (process.env.ESTELLA_VERIFY_SET_FIELD) {
      const parsed = JSON.parse(process.env.ESTELLA_VERIFY_SET_FIELD);
      const writes = Array.isArray(parsed) ? parsed : [parsed];
      setField = await exec(`(async () => {
        const api = window.__estellaHeadless.api;
        const writes = ${JSON.stringify(writes)};
        for (const w of writes) {
          api.setField(w.entity, w.component, w.key, "asset", w.value);
          for (let i = 0; i < (w.steps ?? 40); i++) {
            await api.step(1, 1 / 60);
            await new Promise((r) => setTimeout(r, 16));
          }
        }
        return { wrote: writes.map((w) => w.key).join(',') };
      })()`);
    }

    // ESTELLA_VERIFY_PERSPECTIVE=1 looks at the scene as a 3D one and
    // ESTELLA_VERIFY_ORBIT="<yaw>,<pitch>" turns the eye. Perspective first: it
    // parks the eye at an angle of its own, which the orbit then overrides.
    if (process.env.ESTELLA_VERIFY_PERSPECTIVE || process.env.ESTELLA_VERIFY_ORBIT) {
      const [yaw, pitch] = (process.env.ESTELLA_VERIFY_ORBIT ?? '0,0').split(',').map(Number);
      await exec(`(async () => {
        const api = window.__estellaHeadless.api;
        // The eye belongs to the editor, so the frame has to be drawn through it
        // rather than through the scene's own camera.
        api.useEditorView(true);
        ${process.env.ESTELLA_VERIFY_PERSPECTIVE ? 'api.setViewPerspective(true);' : ''}
        api.setViewOrbit(${yaw || 0}, ${pitch || 0});
        await api.step(2, 1 / 60);
      })()`);
    }

    // ESTELLA_VERIFY_PICK={"x","y","entity"} clicks a point (viewport fractions)
    // and asserts which entity answers — the editor's own hit test, whose box for
    // a mesh is its geometry rather than the icon square a shapeless entity gets.
    if (process.env.ESTELLA_VERIFY_PICK) {
      const spec = JSON.parse(process.env.ESTELLA_VERIFY_PICK);
      pick = await exec(`(() => ({
        hit: window.__estellaHeadless.api.pick(${spec.x * W}, ${spec.y * H}),
        want: ${JSON.stringify(spec.entity)},
      }))()`);
    }

    // ESTELLA_VERIFY_PREFAB=<path> instantiates a prefab into the scene. For an
    // import's products this is the whole chain: the prefab names the geometry,
    // the image and the tint, and nothing here repeats what it should say.
    if (process.env.ESTELLA_VERIFY_PREFAB) {
      meshPrefab = await exec(`(async () => {
        const spawned = await window.__estellaHeadless.loadPrefabAsset(
          ${JSON.stringify(process.env.ESTELLA_VERIFY_PREFAB)});
        await window.__estellaHeadless.api.step(2, 1 / 60);
        return { spawned };
      })()`);
    }

    // ESTELLA_VERIFY_MESH_MATERIAL=<path> puts a material on the scene's meshes,
    // through the asset layer, after the geometry is in place.
    if (process.env.ESTELLA_VERIFY_MESH_MATERIAL) {
      meshMaterial = await exec(`(async () => {
        const applied = await window.__estellaHeadless.loadMaterialAsset(
          ${JSON.stringify(process.env.ESTELLA_VERIFY_MESH_MATERIAL)});
        await window.__estellaHeadless.api.step(2, 1 / 60);
        return { applied };
      })()`);
    }

    // Freezes the scene's inline geometry onto the GPU, keeping every other
    // assertion: nothing about the geometry changes, so the frame after must
    // equal the frame before. That equality IS the claim.
    if (process.env.ESTELLA_VERIFY_MESH_RESIDENT === '1') {
      meshResident = await exec(`(async () => {
        const frozen = window.__estellaHeadless.makeMeshesResident();
        await window.__estellaHeadless.api.step(2, 1 / 60);
        return { frozen };
      })()`);
    }

    // ESTELLA_VERIFY_DEVICE_LOSS=auto is the player's case: the GPU goes away,
    // the browser hands a context back, and NOTHING here asks for a recovery.
    // Only frames pass. What comes back has to come back on the engine's own.
    if (process.env.ESTELLA_VERIFY_DEVICE_LOSS === 'auto') {
      deviceLoss = await exec(`(async () => {
        const d = window.__estellaHeadless.device;
        const api = window.__estellaHeadless.api;
        // Rounds, because losing a context is not a one-off: backgrounding a
        // tab does it again and again, and what a single round cannot show is
        // whether the engine hands the last one's objects back.
        const out = { mode: 'auto', supported: true, rounds: [], tablesBefore: d.glTables(),
                      meshesBefore: d.meshes(), epochBefore: d.programEpoch() };
        for (let r = 0; r < ${ROUNDS}; r++) {
          if (!d.lose()) return { ...out, supported: false };

          for (let i = 0; i < 30 && d.status() === 0; i++) {
            await api.step(1, 1 / 60);
            await new Promise((r2) => setTimeout(r2, 50));
          }
          out.statusAfterLoss = d.status();
          out.reportAfterLoss = d.report();

          // Standing in for the browser, not for the engine: a page gets its
          // context back on its own, and there is no such event to wait for.
          out.restoreCalled = d.restore();
          await new Promise((r2) => setTimeout(r2, 200));

          for (let i = 0; i < 200 && d.status() !== 0; i++) {
            await api.step(1, 1 / 60);
            await new Promise((r2) => setTimeout(r2, 16));
          }
          out.rounds.push({ status: d.status(), tables: d.glTables(), awaiting: d.awaiting() });
        }
        out.statusAfterFull = d.status();
        out.awaitingAfterFull = d.awaiting();
        out.meshesAfterFull = d.meshes();
        out.meshesOwedAfterFull = d.meshesOwed();
        out.epochAfterFull = d.programEpoch();
        out.recovered = out.statusAfterFull === 0;
        out.fullRecovered = out.recovered;
        out.tablesAfterFull = d.glTables();
        await api.step(${STEPS}, 1 / 60);
        out.drawCallsAfterRecover = api.getStats ? api.getStats().drawCalls : -1;
        return out;
      })()`);
    }

    // ESTELLA_VERIFY_DEVICE_LOSS=1 takes the GPU away for real (WEBGL_lose_context)
    // and drives the whole cycle, because everything downstream of a loss is
    // reachable only by actually losing one.
    if (process.env.ESTELLA_VERIFY_DEVICE_LOSS === '1') {
      deviceLoss = await exec(`(async () => {
        const d = window.__estellaHeadless.device;
        const api = window.__estellaHeadless.api;
        const out = { meshesBefore: d.meshes(), epochBefore: d.programEpoch(),
                      genBefore: d.deviceGen(), supported: d.lose() };
        if (!out.supported) return out;

        // The browser reports the loss asynchronously and the engine polls on its
        // own frame, so both are waited for rather than assumed.
        for (let i = 0; i < 30 && d.status() === 0; i++) {
          api.step(1, 1 / 60);
          await new Promise((r) => setTimeout(r, 50));
        }
        out.statusAfterLoss = d.status();
        out.reportAfterLoss = d.report();

        out.guard = d.guard();
        out.tablesAtLoss = d.glTables();
        out.awaitingAtLoss = d.awaiting();
        out.meshesAtLoss = d.meshes();
        out.meshesOwedAtLoss = d.meshesOwed();
        out.glLostBeforeRestore = d.contextLost();
        out.restoreCalled = d.restore();
        await new Promise((r) => setTimeout(r, 500));
        out.glLostAfterRestore = d.contextLost();

        // A context comes back when the browser is ready, not when asked.
        out.recovered = false;
        for (let i = 0; i < 20 && !out.recovered; i++) {
          out.recovered = d.recover();
          if (!out.recovered) await new Promise((r) => setTimeout(r, 100));
        }
        out.statusAfterRecover = d.status();
        out.awaitingAfterRecover = d.awaiting();
        // Between the rebuild and the replay: the one moment the realization is
        // gone and the identity is not. Sampled at the loss instead, this proves
        // nothing — the engine has not been told about it yet.
        out.meshesAfterRecover = d.meshes();
        out.meshesOwedAfterRecover = d.meshesOwed();

        // The full cycle: rebuild, re-upload the textures, and declare it whole.
        out.fullRecovered = await d.recoverFull();
        out.statusAfterFull = d.status();
        out.tablesAfterFull = d.glTables();
        out.awaitingAfterFull = d.awaiting();
        out.meshesAfterFull = d.meshes();
        out.meshesOwedAfterFull = d.meshesOwed();
        out.epochAfterFull = d.programEpoch();
        out.genAfterFull = d.deviceGen();
        await api.step(${STEPS}, 1 / 60);
        out.drawCallsAfterRecover = api.getStats ? api.getStats().drawCalls : -1;
        return out;
      })()`);
    }

    // Both backends are read the same way: the ENGINE's pixels, in the page.
    // Reading the composited page instead answers what a display would show —
    // rgb(0,255,0) comes back as rgb(58,254,32).
    // A build that CAN answer and does not is a failure, not a reason to read the
    // page: on a hidden window that page is blank, so falling back turns a refused
    // readback into a frame that rendered nothing, which every probe then agrees with.
    const readFrame = (expr) => exec(`(async () => {
      const api = window.__estellaHeadless.api;
      let c = null;
      if (api.captureViewportPixels) {
        c = await api.captureViewportPixels();
        if (!c) throw new Error('captureViewportPixels: no pixels — the engine refused the readback, or it was still pending when the wait gave up');
      }
      c = c ?? api.captureViewport();
      const px = c.rgba, w = c.width, h = c.height;
      ${expr}
    })()`);


    const capture = await readFrame(`
      const min = [255, 255, 255], max = [0, 0, 0]; let nonZero = 0;
      for (let i = 0; i < px.length; i += 4) {
        for (let k = 0; k < 3; k++) { const v = px[i + k]; if (v < min[k]) min[k] = v; if (v > max[k]) max[k] = v; }
        if (px[i] | px[i + 1] | px[i + 2]) nonZero++;
      }
      const spread = (max[0] - min[0]) + (max[1] - min[1]) + (max[2] - min[2]);
      return { w, h, totalPixels: px.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };
    `);

    // ESTELLA_VERIFY_DEVICE_LOSS=roundtrip: frames pass until the device says Live,
    // and the frame must be the one from before the loss. A second capture before
    // any loss proves the scene holds still, or the comparison proves nothing.
    let roundtrip = null;
    if (process.env.ESTELLA_VERIFY_DEVICE_LOSS === 'roundtrip') {
      const gridSpacing = Number(process.env.ESTELLA_VERIFY_LOSS_GRID) || 0;
      if (gridSpacing > 0) {
        await exec(`window.__estellaHeadless.api.setGrid(true, ${gridSpacing})`);
        await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
      }
      const tolerance = Number(process.env.ESTELLA_VERIFY_LOSS_TOLERANCE) || 0;
      const diffAgainstReference = `
        const ref = window.__estellaRoundtripRef;
        let differing = 0;
        for (let i = 0; i < px.length; i += 4) {
          if (Math.abs(ref[i] - px[i]) + Math.abs(ref[i + 1] - px[i + 1]) + Math.abs(ref[i + 2] - px[i + 2]) > 24) differing++;
        }
        return differing;
      `;
      await readFrame('window.__estellaRoundtripRef = px.slice(); return true;');
      await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);
      const still = await readFrame(diffAgainstReference);
      const rounds = [];
      for (let r = 0; r < ROUNDS; r++) {
        const round = await exec(`(async () => {
          const d = window.__estellaHeadless.device;
          const api = window.__estellaHeadless.api;
          if (!d.lose()) return { supported: false };
          for (let i = 0; i < 30 && d.status() === 0; i++) {
            await api.step(1, 1 / 60);
            await new Promise((r2) => setTimeout(r2, 50));
          }
          const lost = d.status() !== 0;
          d.restore();
          await new Promise((r2) => setTimeout(r2, 200));
          let frames = 0;
          for (; frames < 300 && d.status() !== 0; frames++) {
            await api.step(1, 1 / 60);
            await new Promise((r2) => setTimeout(r2, 16));
          }
          return { supported: true, lost, status: d.status(), frames };
        })()`);
        await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);
        round.differing = await readFrame(diffAgainstReference);
        rounds.push(round);
      }
      roundtrip = {
        still, tolerance, rounds,
        ok: still === 0 && rounds.length > 0 && rounds.every((x) => x.supported && x.lost
          && x.status === 0 && x.differing <= tolerance),
      };
    }

    const drawCalls = await exec('window.__estellaHeadless.api.getStats().drawCalls');
    // What the frame COST, which no pixel shows: the same geometry drawn N times
    // is one instanced call, and the picture is identical either way. Asserted as
    // an exact number so a regression in EITHER direction is a failure.
    const wantDrawCalls = process.env.ESTELLA_VERIFY_DRAW_CALLS;
    const draws = wantDrawCalls === undefined ? null
      : { want: Number(wantDrawCalls), got: drawCalls, ok: drawCalls === Number(wantDrawCalls) };
    // What the frame cost where no draw call and no pixel can show it — the passes a
    // shadow atlas took. ESTELLA_VERIFY_COUNTERS is a JSON object of counter name → exact
    // value; a name the frame never set reports null, which fails rather than reading 0.
    // ESTELLA_VERIFY_COUNTERS_MAX is the same object read as a CEILING, a different claim:
    // exact pins a scene small enough to enumerate, a ceiling asks whether cost stayed
    // bounded where nobody can. ESTELLA_VERIFY_COUNTERS_MIN is a FLOOR: that a thing happened
    // at all, where how often is the engine's business. All fail on a counter the frame never set.
    let counters = null;
    if (process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX || process.env.ESTELLA_VERIFY_COUNTERS_MIN || PREPASS) {
      const want = JSON.parse(process.env.ESTELLA_VERIFY_COUNTERS ?? '{}');
      const ceiling = JSON.parse(process.env.ESTELLA_VERIFY_COUNTERS_MAX ?? '{}');
      const floor = JSON.parse(process.env.ESTELLA_VERIFY_COUNTERS_MIN ?? '{}');
      const got = await exec('window.__estellaHeadless.api.getCounters()');
      const points = [
        ...Object.entries(want).map(([name, value]) => ({
          name, want: value, got: got?.[name] ?? null, ok: got?.[name] === value,
        })),
        ...Object.entries(ceiling).map(([name, value]) => ({
          name, max: value, got: got?.[name] ?? null,
          ok: typeof got?.[name] === 'number' && got[name] <= value,
        })),
        ...Object.entries(floor).map(([name, value]) => ({
          name, min: value, got: got?.[name] ?? null,
          ok: typeof got?.[name] === 'number' && got[name] >= value,
        })),
        // A prepass twin of a scene that never had a prepass proves nothing about it: the draw it took part in is counted.
        ...(PREPASS ? [{ name: 'render.prepass.draws', min: 1, got: got?.['render.prepass.draws'] ?? null,
                         ok: (got?.['render.prepass.draws'] ?? 0) >= 1 }] : []),
      ];
      counters = { points, ok: points.every((p) => p.ok) };
    }
    // ESTELLA_VERIFY_GPU_FRAME=print|require: the frame's GPU time read the way a shipped game reads it (profiler
    // off, one span over the graph) beside the sum of its passes (profiler on). They are the same question asked two
    // ways, and a backend that answers the first with one pass of the frame reads far under the second — which is
    // how a phone held 37 fps with dynamic resolution on (#120). `require` fails when the two disagree by more than
    // half; local-only like the pass timer, and for a scene with passes off the surface, or there is nothing to miss.
    let gpuFrame = null;
    if (process.env.ESTELLA_VERIFY_GPU_FRAME) {
      const settle = async (read, done) => {
        const seen = [];
        for (let i = 0; i < 60 && seen.length < 8; i++) {
          await exec('window.__estellaHeadless.api.step(1, 1 / 60)');
          await new Promise((r) => setTimeout(r, 40));
          const value = await exec(read);
          if (done(value)) seen.push(value);
        }
        return seen;
      };
      const mean = (values) => (values.length ? values.reduce((a, b) => a + b, 0) / values.length : -1);
      await exec('window.__estellaHeadless.api.setCpuProfiling(false)');
      const spans = await settle('window.__estellaHeadless.api.getGpuTimeMs()', (ms) => ms > 0);
      await exec('window.__estellaHeadless.api.setCpuProfiling(true)');
      const scoped = await settle('window.__estellaHeadless.api.getGpuScopes()', (s) => Object.keys(s).some((k) => k.startsWith('pass/')));
      // Left as the run had it: a gate below that reads the last frame's counters needs the profiler it turned on.
      if (!(process.env.ESTELLA_VERIFY_COUNTERS || process.env.ESTELLA_VERIFY_COUNTERS_MAX || process.env.ESTELLA_VERIFY_COUNTERS_MIN || process.env.ESTELLA_VERIFY_FRAME_DEBUG || PREPASS)) {
        await exec('window.__estellaHeadless.api.setCpuProfiling(false)');
      }
      const sums = scoped.map((s) => Object.entries(s).filter(([k]) => k.startsWith('pass/')).reduce((a, [, v]) => a + v, 0));
      const passCount = scoped.length ? Object.keys(scoped[scoped.length - 1]).filter((k) => k.startsWith('pass/')).length : 0;
      const frameMs = mean(spans), passesMs = mean(sums);
      const agree = frameMs > 0 && passesMs > 0 && frameMs >= passesMs * 0.5 && frameMs <= passesMs * 2;
      console.log(`gpu frame (${BACKEND}): span ${frameMs.toFixed(3)} ms over ${spans.length} frames, passes ${passesMs.toFixed(3)} ms (${passCount} passes) — ${agree ? 'agree' : 'DISAGREE'}`);
      gpuFrame = { frameMs, passesMs, passCount, ok: process.env.ESTELLA_VERIFY_GPU_FRAME !== 'require' || agree };
    }
    // ESTELLA_VERIFY_GPU_PASSES=print|require: per-pass GPU time on this backend. The device answers a few frames
    // late and between tasks, so frames are stepped with a pause until the render graph's passes report. `require`
    // fails a backend that can time and reported nothing; it is local-only, a CI adapter may not offer a timer.
    let gpuPasses = null;
    if (process.env.ESTELLA_VERIFY_GPU_PASSES) {
      await exec('window.__estellaHeadless.api.setCpuProfiling(true)');
      // The eighth frame that reports, not the first: the first one a timer answers for carries whatever the device did
      // once on the way (32 lit sprite layers read 50 ms there and 5.4 ms on every frame after), and a cost is the steady one.
      let scopes = {};
      for (let i = 0, reported = 0; i < 60 && reported < 8; i++) {
        await exec('window.__estellaHeadless.api.step(1, 1 / 60)');
        await new Promise((r) => setTimeout(r, 40));
        const read = await exec('window.__estellaHeadless.api.getGpuScopes()');
        if (Object.keys(read).some((k) => k.startsWith('pass/'))) { scopes = read; reported++; }
      }
      const rows = Object.entries(scopes).filter(([k]) => k.startsWith('pass/')).sort((a, b) => b[1] - a[1]);
      console.log(`gpu passes (${BACKEND}): graph ${(scopes.graph ?? -1).toFixed(3)} ms, ${rows.length} passes`);
      for (const [k, v] of rows) console.log(`  ${k.slice(5).padEnd(30)} ${v.toFixed(3)} ms`);
      gpuPasses = { count: rows.length, ok: process.env.ESTELLA_VERIFY_GPU_PASSES !== 'require' || rows.length > 0 };
    }
    // The frame debugger on this backend: its reasons are the merge's own counters
    // for the frame, and a replay through the last draw of a pass shows more than
    // one through the first.
    let frameDebug = null;
    if (process.env.ESTELLA_VERIFY_FRAME_DEBUG) {
      const got = await exec('window.__estellaHeadless.api.frameDebug()');
      const raw = await exec('window.__estellaHeadless.api.getCounters()');
      const lower = (entries) => Object.fromEntries(entries.map(([k, v]) => [k.toLowerCase(), v]).sort());
      const counted = lower(Object.entries(raw ?? {}).filter(([k]) => k.startsWith('batch.break.'))
        .map(([k, v]) => [k.slice('batch.break.'.length), v]));
      const reported = lower(Object.entries(got?.breaks ?? {}).filter(([k]) => k !== 'None'));
      const sameReasons = JSON.stringify(counted) === JSON.stringify(reported);
      frameDebug = {
        ...got, counted, sameReasons,
        ok: Boolean(got) && got.draws > 0 && got.matches && sameReasons && got.last > 0 && (got.differ === null || got.differ > 0),
      };
    }
    // Optional color/orientation assertion: ESTELLA_VERIFY_EXPECT is a JSON array of
    // { x, y, rgb:[r,g,b], tol? } where x,y are normalized [0,1] from the TOP-LEFT.
    // This is the guard the all-textures-upside-down upload bug would have tripped
    // (TextureLoader imageOrientation) — `rendered` (color variation) alone misses it.
    let expect = null;
    if (process.env.ESTELLA_VERIFY_EXPECT) {
      expect = await readFrame(`
        const pts = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_EXPECT))};
        const out = pts.map((p) => {
          const pxX = Math.round(p.x * (w - 1));
          const row = (h - 1) - Math.round(p.y * (h - 1)); // readback rows are bottom-up
          const i = (row * w + pxX) * 4;
          const got = [px[i], px[i + 1], px[i + 2]];
          const tol = p.tol ?? 24;
          const ok = got.every((g, k) => Math.abs(g - p.rgb[k]) <= tol);
          return { x: p.x, y: p.y, want: p.rgb, got, ok };
        });
        return { points: out, ok: out.every((o) => o.ok) };
      `);
    }
    // ESTELLA_VERIFY_TWINS = { pairs: [[x1, y1, x2, y2], ...], tol }: points that must match —
    // one surface drawn two ways, as a conformance model pairs a normal-mapped bump with the
    // same bump built as geometry. Pins only that the two agree, not the lighting.
    let nineSlice = null;
    if (process.env.ESTELLA_VERIFY_NINE_SLICE) {
      const rects = JSON.parse(process.env.ESTELLA_VERIFY_NINE_SLICE);
      nineSlice = await readFrame(`return (${checkNineSliceCorners.toString()})(px, w, h, ${JSON.stringify(rects)});`);
    }
    let twins = null;
    if (process.env.ESTELLA_VERIFY_TWINS) {
      twins = await readFrame(`
        const t = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_TWINS))};
        const at = (x, y) => {
          const i = (((h - 1) - Math.round(y * (h - 1))) * w + Math.round(x * (w - 1))) * 4;
          return [px[i], px[i + 1], px[i + 2]];
        };
        const pairs = t.pairs.map(([x1, y1, x2, y2]) => {
          const a = at(x1, y1), b = at(x2, y2);
          return { a, b, d: Math.max(...a.map((v, k) => Math.abs(v - b[k]))) };
        });
        const worst = Math.max(...pairs.map((p) => p.d));
        return { pairs, worst, tol: t.tol, ok: worst <= t.tol };
      `);
    }
    // ESTELLA_VERIFY_EDGE = { box (0..1, top-left), lit, dark, maxJag }: how far each
    // row's crossing of a straight edge, found from the right to sub-pixel, strays from
    // a line through its neighbours — a sampling grid drawn into the edge shows as that.
    let edge = null;
    if (process.env.ESTELLA_VERIFY_EDGE) {
      edge = await readFrame(`
        const e = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_EDGE))};
        const lum = (x, y) => { const i = (((h - 1) - y) * w + x) * 4; return (px[i] + px[i + 1] + px[i + 2]) / 3; };
        const mid = (e.lit + e.dark) / 2;
        const [x0, y0, x1, y1] = [e.box[0] * w, e.box[1] * h, e.box[2] * w, e.box[3] * h].map(Math.round);
        const pos = [];
        for (let y = y0; y < y1; y++) {
          for (let x = x1 - 1; x > x0; x--) {
            const a = lum(x, y), b = lum(x - 1, y);
            if (a >= mid && b < mid) { pos.push([y, x - (a - mid) / (a - b)]); break; }
          }
        }
        const res = [];
        for (let k = 4; k < pos.length - 4; k++) {
          const win = pos.slice(k - 4, k + 5);
          const my = win.reduce((s, p) => s + p[0], 0) / win.length;
          const mx = win.reduce((s, p) => s + p[1], 0) / win.length;
          const sxy = win.reduce((s, p) => s + (p[0] - my) * (p[1] - mx), 0);
          const syy = win.reduce((s, p) => s + (p[0] - my) ** 2, 0);
          res.push(Math.abs(pos[k][1] - (mx + (sxy / syy) * (pos[k][0] - my))));
        }
        const jag = res.length ? res.reduce((s, v) => s + v, 0) / res.length : Infinity;
        return { rows: pos.length, jag, maxJag: e.maxJag, ok: pos.length >= (y1 - y0) * 0.8 && jag <= e.maxJag };
      `);
    }
    // ESTELLA_VERIFY_CUTOUT_EDGE = { box, lit, run, partial, minShare }: the share of rows
    // whose texel before a cutout's edge is a blend, which coverage from alpha makes and
    // an alpha test does not. The edge is the first `run` texels whose weakest channel is lit.
    let cutoutEdge = null;
    if (process.env.ESTELLA_VERIFY_CUTOUT_EDGE) {
      cutoutEdge = await readFrame(`
        const e = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_CUTOUT_EDGE))};
        const weakest = (x, y) => { const i = (((h - 1) - y) * w + x) * 4; return Math.min(px[i], px[i + 1], px[i + 2]); };
        const [x0, y0, x1, y1] = [e.box[0] * w, e.box[1] * h, e.box[2] * w, e.box[3] * h].map(Math.round);
        let rows = 0, blended = 0;
        for (let y = y0; y < y1; y++) {
          for (let x = x0 + 1; x < x1 - e.run; x++) {
            let lit = weakest(x - 1, y) < e.lit;
            for (let k = 0; lit && k < e.run; k++) lit = weakest(x + k, y) >= e.lit;
            if (!lit) continue;
            rows++;
            const v = weakest(x - 1, y);
            if (v > e.partial[0] && v < e.partial[1]) blended++;
            break;
          }
        }
        const share = rows ? blended / rows : 0;
        return { rows, blended, share, minShare: e.minShare, ok: rows >= (y1 - y0) * 0.8 && share >= e.minShare };
      `);
    }
    // ESTELLA_VERIFY_MINIFIED = { box, maxRipple, minMean }: the mean gap between each pixel
    // and its four neighbours over a far-off texture — flat through a mip chain, shimmering
    // from the top level. minMean keeps a blank box from passing.
    let minified = null;
    if (process.env.ESTELLA_VERIFY_MINIFIED) {
      minified = await readFrame(`
        const e = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_MINIFIED))};
        const lum = (x, y) => { const i = (((h - 1) - y) * w + x) * 4; return (px[i] + px[i + 1] + px[i + 2]) / 3; };
        const [x0, y0, x1, y1] = [e.box[0] * w, e.box[1] * h, e.box[2] * w, e.box[3] * h].map(Math.round);
        let ripple = 0, sum = 0, n = 0;
        for (let y = y0 + 1; y < y1 - 1; y++) {
          for (let x = x0 + 1; x < x1 - 1; x++) {
            const v = lum(x, y);
            ripple += Math.abs(v - (lum(x - 1, y) + lum(x + 1, y) + lum(x, y - 1) + lum(x, y + 1)) / 4);
            sum += v; n++;
          }
        }
        const mean = n ? sum / n : 0;
        ripple = n ? ripple / n : Infinity;
        return { ripple, maxRipple: e.maxRipple, mean, minMean: e.minMean, ok: ripple <= e.maxRipple && mean >= e.minMean };
      `);
    }
    // ESTELLA_VERIFY_COUNT is a JSON array of { rgb:[r,g,b], tol?, atLeast?, atMost? }:
    // HOW MANY pixels of the frame are that colour, rather than which ones — a
    // point probe cannot ask that without also naming where a font put them.
    let count = null;
    if (process.env.ESTELLA_VERIFY_COUNT) {
      count = await readFrame(`
        const specs = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_COUNT))};
        const rows = specs.map((s) => {
          const tol = s.tol ?? 24;
          let n = 0;
          for (let i = 0; i < px.length; i += 4) {
            if (Math.abs(px[i] - s.rgb[0]) <= tol
              && Math.abs(px[i + 1] - s.rgb[1]) <= tol
              && Math.abs(px[i + 2] - s.rgb[2]) <= tol) n++;
          }
          const ok = (s.atLeast === undefined || n >= s.atLeast)
            && (s.atMost === undefined || n <= s.atMost);
          return { rgb: s.rgb, tol, count: n, atLeast: s.atLeast ?? null, atMost: s.atMost ?? null, ok };
        });
        return { rows, ok: rows.every((r) => r.ok) };
      `);
    }
    // ESTELLA_VERIFY_SEAM is JSON { period, phase, band:{y0,y1}, limit?, atLeast? }
    // in TOP-DOWN screen pixels. The pixels come back to node so seamProbe stays
    // one implementation rather than being re-typed into an injected script.
    let seam = null;
    if (process.env.ESTELLA_VERIFY_SEAM) {
      const spec = JSON.parse(process.env.ESTELLA_VERIFY_SEAM);
      const frame = await readFrame(`
        let s = '';
        const CH = 0x8000;
        for (let i = 0; i < px.length; i += CH) {
          s += String.fromCharCode.apply(null, px.subarray(i, Math.min(i + CH, px.length)));
        }
        return { b64: btoa(s), w, h };
      `);
      const raw = Buffer.from(frame.b64, 'base64');
      // Readback rows are bottom-up; the band is stated the way a viewer reads a
      // frame, so the rows are flipped rather than the caller doing the arithmetic.
      const rows = Buffer.alloc(raw.length);
      const stride = frame.w * 4;
      for (let y = 0; y < frame.h; y++) {
        raw.copy(rows, y * stride, (frame.h - 1 - y) * stride, (frame.h - y) * stride);
      }
      seam = checkSeam(rows, frame.w, frame.h, spec);
    }
    // Optional PNG dump (ESTELLA_VERIFY_OUT) of the engine framebuffer (not the
    // page) so the rendered frame can be eyeballed. GL readback is bottom-up → flip.
    if (process.env.ESTELLA_VERIFY_OUT) {
      const dataUrl = await readFrame(`
        const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
        const ctx = cv.getContext('2d'); const img = ctx.createImageData(w, h);
        for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(px.subarray(sy, sy + w * 4), y * w * 4); }
        ctx.putImageData(img, 0, 0);
        return cv.toDataURL('image/png');
      `);
      await writeFile(process.env.ESTELLA_VERIFY_OUT, Buffer.from(dataUrl.split(',')[1], 'base64'));
    }
    // Optional resize assertion (ESTELLA_VERIFY_RESIZE = "WxH"): shrink the
    // canvas mid-run, step, and re-capture — the backbuffer must follow the
    // viewport (the WebGPU swapchain reconfigure; a no-op contract on GL).
    let resize = null;
    if (process.env.ESTELLA_VERIFY_RESIZE) {
      const [rw, rh] = process.env.ESTELLA_VERIFY_RESIZE.split('x').map(Number);
      await exec(`window.__estellaHeadless.api.resizeViewport(${rw}, ${rh})`);
      await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
      resize = await readFrame(`
        let nonZero = 0;
        for (let i = 0; i < px.length; i += 4) if (px[i] | px[i + 1] | px[i + 2]) nonZero++;
        return { w, h, nonZeroPixels: nonZero, ok: w === ${rw} && h === ${rh} && nonZero > 0 };
      `);
    }
    // Optional offscreen material-preview assertion (ESTELLA_VERIFY_PREVIEW =
    // {w,h,rgb:[r,g,b],tol?}): renders a scene material to an offscreen target and checks the
    // center pixel — proves the render-to-texture preview primitive, not just the viewport.
    // The readback rides the engine's async seam, so the same awaited call
    // verifies BOTH backends (GL resolves immediately; WebGPU when the map lands).
    let preview = null;
    if (process.env.ESTELLA_VERIFY_PREVIEW) {
      const cfg = JSON.parse(process.env.ESTELLA_VERIFY_PREVIEW);
      preview = await exec(`(async () => {
        const cfg = ${JSON.stringify(cfg)};
        const cap = await window.__estellaHeadless.api.renderSceneMaterialPreview(cfg.w, cfg.h);
        if (!cap) return { ok: false, reason: 'no scene material' };
        const { width: w, height: h, rgba } = cap;
        const i = (Math.floor(h / 2) * w + Math.floor(w / 2)) * 4;
        const got = [rgba[i], rgba[i + 1], rgba[i + 2]];
        const tol = cfg.tol ?? 40;
        return { ok: got.every((g, k) => Math.abs(g - cfg.rgb[k]) <= tol), want: cfg.rgb, got, w, h };
      })()`);
    }
    // Optional offscreen MESH-preview assertion (ESTELLA_VERIFY_MESH_PREVIEW =
    // {w,h}). The claim is the FRAMING a mesh thumbnail adds over a material ball:
    // the geometry lands inside the frame and reaches it, at any authored scale.
    let meshPreview = null;
    if (process.env.ESTELLA_VERIFY_MESH_PREVIEW) {
      const cfg = JSON.parse(process.env.ESTELLA_VERIFY_MESH_PREVIEW);
      meshPreview = await exec(`(async () => {
        const cfg = ${JSON.stringify(cfg)};
        const cap = await window.__estellaHeadless.api.renderSceneMeshPreview(cfg.w, cfg.h);
        if (!cap) return { ok: false, reason: 'no scene mesh' };
        const { width: w, height: h, rgba } = cap;
        const lit = (x, y) => { const i = (y * w + x) * 4; return rgba[i] | rgba[i + 1] | rgba[i + 2]; };
        let border = 0;
        for (let x = 0; x < w; x++) { if (lit(x, 0)) border++; if (lit(x, h - 1)) border++; }
        for (let y = 0; y < h; y++) { if (lit(0, y)) border++; if (lit(w - 1, y)) border++; }
        // Reaching the outer eighth is what "fitted" means, and it holds for any
        // shape — a fill ratio would only hold for one that is roughly square.
        const pad = Math.floor(w / 8);
        let reach = 0;
        for (let y = 0; y < h; y++) {
          for (let x = 0; x < w; x++) {
            const outer = x < pad || y < pad || x >= w - pad || y >= h - pad;
            if (outer && lit(x, y)) reach++;
          }
        }
        return { ok: border === 0 && reach > 0, border, reach, w, h };
      })()`);
    }
    // Optional editor-grid assertion (ESTELLA_VERIFY_GRID = minor spacing, world
    // units): flip the grid on (this activates the editor view it draws through),
    // capture, flip it off, and assert the frames differ — proving the custom-draw
    // drawMeshWithMaterial path rasterizes on this backend. Run standalone:
    // activating the editor view reframes the camera for any later capture.
    let grid = null;
    if (process.env.ESTELLA_VERIFY_GRID) {
      const spacing = Number(process.env.ESTELLA_VERIFY_GRID) || 64;
      // "nothing": a plane the eye lies IN meets every ray at its own point and
      // has no picture. "grazing": a plane the eye looks ALONG lights one half far
      // more than the other, where one it FACES lights the frame evenly.
      const wantGrid = process.env.ESTELLA_VERIFY_GRID_EXPECT ?? 'frame';
      if (!['frame', 'nothing', 'grazing'].includes(wantGrid)) {
        throw new Error(`ESTELLA_VERIFY_GRID_EXPECT is "frame", "grazing" or "nothing", not "${wantGrid}"`);
      }
      await exec(`window.__estellaHeadless.api.setGrid(true, ${spacing})`);
      await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
      // Optional PNG of the grid-on frame (ESTELLA_VERIFY_GRID_OUT) for eyeballing.
      // Same per-backend readback split as ESTELLA_VERIFY_OUT (GL page capture of a
      // hidden window never composites — read the framebuffer in-page instead).
      if (process.env.ESTELLA_VERIFY_GRID_OUT) {
        const dataUrl = await readFrame(`
          const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
          const ctx = cv.getContext('2d'); const img = ctx.createImageData(w, h);
          for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(px.subarray(sy, sy + w * 4), y * w * 4); }
          ctx.putImageData(img, 0, 0);
          return cv.toDataURL('image/png');
        `);
        await writeFile(process.env.ESTELLA_VERIFY_GRID_OUT, Buffer.from(dataUrl.split(',')[1], 'base64'));
      }
      await readFrame('window.__estellaGridOn = px.slice(); return true;');
      // ESTELLA_VERIFY_GRID_RESPACE: the spacing rides a material uniform the frames
      // above already uploaded, so a backend that keeps binding the first upload
      // draws the old grid again. The view does not move, so only the grid can differ.
      let respaced = null;
      if (process.env.ESTELLA_VERIFY_GRID_RESPACE) {
        await exec(`window.__estellaHeadless.api.setGrid(true, ${Number(process.env.ESTELLA_VERIFY_GRID_RESPACE)})`);
        await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
        respaced = await readFrame(`
          const on = window.__estellaGridOn;
          let differing = 0;
          for (let i = 0; i < px.length; i += 4) {
            if (Math.abs(on[i] - px[i]) + Math.abs(on[i + 1] - px[i + 1]) + Math.abs(on[i + 2] - px[i + 2]) > 12) differing++;
          }
          return differing;
        `);
      }
      await exec('window.__estellaHeadless.api.setGrid(false)');
      await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
      grid = await readFrame(`
        const on = window.__estellaGridOn;
        const quadrants = [0, 0, 0, 0];
        let differing = 0;
        for (let y = 0; y < h; y++) {
          for (let x = 0; x < w; x++) {
            const i = (y * w + x) * 4;
            const d = Math.abs(on[i] - px[i]) + Math.abs(on[i + 1] - px[i + 1]) + Math.abs(on[i + 2] - px[i + 2]);
            if (d <= 12) continue;
            differing++;
            quadrants[(y < h / 2 ? 0 : 2) + (x < w / 2 ? 0 : 1)]++;
          }
        }
        // A grid is there everywhere you look, so every quarter of the frame has
        // some of it. A plane seen edge-on lights one band and passes a total.
        const covers = differing > 300 && quadrants.every((q) => q > 20);
        // Lopsided by half the frame: 1.4 sits between what the two cases measure
        // (a floor at 4 degrees is ~1.7, a plane turned to face the eye ~1.1).
        const top = quadrants[0] + quadrants[1];
        const bottom = quadrants[2] + quadrants[3];
        const lopsided = differing > 300 && Math.min(top, bottom) > 0
          && Math.max(top, bottom) >= 1.4 * Math.min(top, bottom);
        const want = ${JSON.stringify(wantGrid)};
        return {
          differingPixels: differing, quadrants, want, halves: [top, bottom],
          ok: want === 'nothing' ? differing === 0 : want === 'grazing' ? lopsided : covers,
        };
      `);
      if (respaced != null) grid = { ...grid, respacedPixels: respaced, ok: grid.ok && respaced > 300 };
    }
    // ESTELLA_VERIFY_STUDIO = { studio?: {...lighting}, dark?, exposure?, scene? }: the editor
    // view's own lighting, the one thing that is NOT the scene. Four frames through the
    // same eye — scene A, studio S, scene A' (switched back), and A under exposure — and
    // the claims are about their relations:
    //   dark: false -> S differs from A and the scene was already lit (the studio replaces it);
    //   dark: true  -> A is unreadable (almost no lit pixels) and S is readable: a lit share and
    //                  a spread of tones, because a flat blob is not a model;
    //   A' == A byte for byte, whatever the studio did in between;
    //   exposure: EV   -> mean display luma of A under EV scales by 2^EV (gamma frame), and
    //                  resetting returns A exactly.
    let studio = null;
    if (process.env.ESTELLA_VERIFY_STUDIO) {
      const spec = JSON.parse(process.env.ESTELLA_VERIFY_STUDIO);
      const api = (call) => exec(`(async () => { const api = window.__estellaHeadless.api; ${call}; await api.step(2, 1 / 60); })()`);
      const stats = (name) => readFrame(`
        window.__studio = window.__studio || {};
        window.__studio[${JSON.stringify(name)}] = px.slice();
        const lum = (i) => 0.2126 * px[i] + 0.7152 * px[i + 1] + 0.0722 * px[i + 2];
        const dec = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };
        const l = []; let lit = 0, sum = 0, lin = 0;
        for (let i = 0; i < px.length; i += 4) { const v = lum(i); l.push(v); sum += v; if (v > 30) lit++; lin += 0.2126 * dec(px[i]) + 0.7152 * dec(px[i + 1]) + 0.0722 * dec(px[i + 2]); }
        const n = l.length;
        // The spread of tones among the pixels that carry any: a model reads by its shading.
        const on = l.filter((v) => v > 30).sort((a, b) => a - b);
        const spread = on.length ? on[Math.floor(on.length * 0.95)] - on[Math.floor(on.length * 0.05)] : 0;
        return { litShare: lit / n, mean: sum / n, meanLinear: lin / n, spread };
      `);
      const diff = (a, b) => readFrame(`
        const A = window.__studio[${JSON.stringify(a)}], B = window.__studio[${JSON.stringify(b)}];
        let max = 0, differing = 0;
        for (let i = 0; i < A.length; i++) { const d = Math.abs(A[i] - B[i]); if (d > max) max = d; if (d > 0) differing++; }
        return { max, differing };
      `);
      await api('api.setViewLighting()');
      const A = await stats('A');
      let S = null, back = null, dStudio = null;
      if (spec.studio) {
        await api(`api.setViewLighting(${JSON.stringify({ mode: 'studio', ...spec.studio })})`);
        S = await stats('S');
        dStudio = await diff('A', 'S');
        await api('api.setViewLighting()');
        await stats('A2');
        back = await diff('A', 'A2');
      }
      // Seeing the sky and being lit by it are separate: showSky draws the scene's environment
      // behind the studio-lit model ('adds'), and a scene with none has nothing to draw ('noop').
      let sky = null;
      if (spec.sky) {
        await api(`api.setViewLighting(${JSON.stringify({ mode: 'studio', ...spec.studio, showSky: true })})`);
        await stats('SS');
        const d = await diff('S', 'SS');
        await api('api.setViewLighting()');
        await stats('A4');
        const reset = await diff('A', 'A4');
        sky = { differing: d.differing, resetMax: reset.max,
          ok: reset.max === 0 && (spec.sky === 'adds' ? d.differing > 2000 : d.differing === 0) };
      }
      let exp = null;
      if (spec.exposure !== undefined) {
        await api(`api.setViewLighting(${JSON.stringify({ mode: 'scene', exposure: spec.exposure })})`);
        const E = await stats('E');
        await api('api.setViewLighting()');
        await stats('A3');
        const reset = await diff('A', 'A3');
        const want = Math.pow(2, spec.exposure);
        // In a linear frame the exposure is a scale of radiance, so it is measured there.
        const ratio = spec.linear ? E.meanLinear / A.meanLinear : E.mean / A.mean;
        exp = { ev: spec.exposure, ratio, want, resetMax: reset.max,
          ok: Math.abs(ratio - want) <= (spec.tol ?? 0.08) * want && reset.max === 0 };
      }
      const darkOk = spec.dark === undefined ? true
        : spec.dark ? (A.litShare < 0.02 && S && S.litShare > 0.08 && S.spread > 40)
          : (S && dStudio.differing > 200);
      studio = { A, S, dStudio, back, sky, exp, ok: Boolean(darkOk) && (!spec.studio || back.max === 0) && (!sky || sky.ok) && (!exp || exp.ok) };
    }
    // ESTELLA_VERIFY_SHADING: authored A, clay C, albedo L, wireframe W, authored again A2.
    // Clay has no chroma but a spread of tones (it is lit); albedo keeps colour and is flatter;
    // wireframe is neutral lines on a dark surface; A2 == A byte for byte afterwards.
    let shading = null;
    if (process.env.ESTELLA_VERIFY_SHADING) {
      const api = (call) => exec(`(async () => { const api = window.__estellaHeadless.api; ${call}; await api.step(2, 1 / 60); })()`);
      const stats = (name) => readFrame(`
        window.__shade = window.__shade || {};
        window.__shade[${JSON.stringify(name)}] = px.slice();
        const lum = (i) => 0.2126 * px[i] + 0.7152 * px[i + 1] + 0.0722 * px[i + 2];
        const tones = []; let chroma = 0;
        for (let i = 0; i < px.length; i += 4) {
          if (lum(i) <= 30) continue;
          tones.push(lum(i));
          chroma += Math.max(px[i], px[i + 1], px[i + 2]) - Math.min(px[i], px[i + 1], px[i + 2]);
        }
        tones.sort((a, b) => a - b);
        const n = tones.length;
        return { litShare: n / (px.length / 4), chroma: n ? chroma / n : 0, spread: n ? tones[Math.floor(n * 0.95)] - tones[Math.floor(n * 0.05)] : 0 };
      `);
      const diff = (a, b) => readFrame(`
        const A = window.__shade[${JSON.stringify(a)}], B = window.__shade[${JSON.stringify(b)}];
        let max = 0, differing = 0;
        for (let i = 0; i < A.length; i++) { const d = Math.abs(A[i] - B[i]); if (d > max) max = d; if (d > 0) differing++; }
        return { max, differing };
      `);
      await api(`api.setViewShading('shaded')`);
      const A = await stats('A');
      await api(`api.setViewShading('clay')`);
      const C = await stats('C');
      await api(`api.setViewShading('albedo')`);
      const L = await stats('L');
      await api(`api.setViewShading('wireframe')`);
      const W = await stats('W');
      const dClay = await diff('A', 'C');
      const dAlbedo = await diff('A', 'L');
      const dWire = await diff('A', 'W');
      await api(`api.setViewShading('shaded')`);
      await stats('A2');
      const back = await diff('A', 'A2');
      shading = { A, C, L, W, dClay, dAlbedo, dWire, back,
        ok: A.chroma > 12 && C.chroma < 6 && C.litShare > 0.05 && C.spread > 20 && dClay.differing > 500
          && L.chroma > 12 && L.spread < A.spread && dAlbedo.differing > 200
          && W.chroma < 6 && W.litShare > 0.003 && W.litShare < 0.2 && dWire.differing > 500 && back.max === 0 };
    }
    // ESTELLA_VERIFY_LIGHTING_SPLIT: clay C, direct-only D, indirect-only I, authored again. Over the pixels clay lights (the
    // meshes), I keeps the fill and loses the sun, so it is flatter than C and still above black; D keeps the sun and loses
    // the fill, so its dark end sits a fill below C's; and the two halves add up to C (a gamma frame adds as it stores).
    let lightingSplit = null;
    if (process.env.ESTELLA_VERIFY_LIGHTING_SPLIT) {
      const api = (call) => exec(`(async () => { const api = window.__estellaHeadless.api; ${call}; await api.step(2, 1 / 60); })()`);
      await api(`api.setViewShading('clay')`);
      await readFrame(`window.__split = { C: px.slice() }; return 0;`);
      await api(`api.setViewShading('directLighting')`);
      await readFrame(`window.__split.D = px.slice(); return 0;`);
      await api(`api.setViewShading('indirectLighting')`);
      await readFrame(`window.__split.I = px.slice(); return 0;`);
      await api(`api.setViewShading('shaded')`);
      // ESTELLA_VERIFY_SPLIT_OUT=<prefix>: the three frames as <prefix>-clay.png, -direct.png, -indirect.png, to be looked at.
      if (process.env.ESTELLA_VERIFY_SPLIT_OUT) {
        for (const [key, name] of [['C', 'clay'], ['D', 'direct'], ['I', 'indirect']]) {
          const url = await readFrame(`
            const P = window.__split[${JSON.stringify(key)}];
            const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
            const ctx = cv.getContext('2d'); const img = ctx.createImageData(w, h);
            for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(P.subarray(sy, sy + w * 4), y * w * 4); }
            ctx.putImageData(img, 0, 0);
            return cv.toDataURL('image/png');
          `);
          await writeFile(`${process.env.ESTELLA_VERIFY_SPLIT_OUT}-${name}.png`, Buffer.from(url.split(',')[1], 'base64'));
        }
      }
      lightingSplit = await readFrame(`
        const { C, D, I } = window.__split;
        const lum = (P, i) => 0.2126 * P[i] + 0.7152 * P[i + 1] + 0.0722 * P[i + 2];
        const lc = [], ld = [], li = []; let chroma = 0;
        for (let i = 0; i < C.length; i += 4) {
          if (lum(C, i) <= 30) continue;
          lc.push(lum(C, i)); ld.push(lum(D, i)); li.push(lum(I, i));
          chroma += Math.max(D[i], D[i + 1], D[i + 2]) - Math.min(D[i], D[i + 1], D[i + 2]);
          chroma += Math.max(I[i], I[i + 1], I[i + 2]) - Math.min(I[i], I[i + 1], I[i + 2]);
        }
        const n = lc.length;
        const mean = (a) => a.reduce((s, v) => s + v, 0) / Math.max(a.length, 1);
        const q = (a, f) => { const b = a.slice().sort((x, y) => x - y); return b[Math.floor((b.length - 1) * f)] ?? 0; };
        return { pixels: n, chroma: n ? chroma / (2 * n) : 0,
                 clay: { mean: mean(lc), p10: q(lc, 0.1), p90: q(lc, 0.9) },
                 direct: { mean: mean(ld), p10: q(ld, 0.1), p90: q(ld, 0.9) },
                 indirect: { mean: mean(li), p10: q(li, 0.1), p90: q(li, 0.9) } };
      `);
      const { clay, direct, indirect } = lightingSplit;
      lightingSplit.ok = lightingSplit.pixels > 500 && lightingSplit.chroma < 6
        && indirect.mean > 20 && indirect.mean < clay.mean && (indirect.p90 - indirect.p10) < (clay.p90 - clay.p10)
        && direct.p10 < clay.p10 - 0.5 * indirect.mean
        && Math.abs(direct.mean + indirect.mean - clay.mean) < 0.1 * clay.mean;
      console.log('lighting split', JSON.stringify(lightingSplit));
    }
    // ESTELLA_VERIFY_SKIN_WEIGHTS = {id, joints:[a, b]}: authored A, the entity coloured by joint a,
    // by joint b, authored again. Each joint moves a different part, so the two heat frames differ
    // from each other and from A, each carries the hot end of the ramp, and A2 == A byte for byte.
    let skinWeights = null;
    if (process.env.ESTELLA_VERIFY_SKIN_WEIGHTS) {
      const spec = JSON.parse(process.env.ESTELLA_VERIFY_SKIN_WEIGHTS);
      const api = (call) => exec(`(async () => { const api = window.__estellaHeadless.api; ${call}; await api.step(2, 1 / 60); })()`);
      const grab = (name) => readFrame(`
        window.__heat = window.__heat || {};
        window.__heat[${JSON.stringify(name)}] = px.slice();
        let hot = 0;
        for (let i = 0; i < px.length; i += 4) if (px[i] > 200 && px[i + 1] < 110 && px[i + 2] < 110) hot++;
        return { hot };
      `);
      const diff = (a, b) => readFrame(`
        const A = window.__heat[${JSON.stringify(a)}], B = window.__heat[${JSON.stringify(b)}];
        let differing = 0, max = 0;
        for (let i = 0; i < A.length; i++) { const d = Math.abs(A[i] - B[i]); if (d > max) max = d; if (d > 0) differing++; }
        return { max, differing };
      `);
      await api('api.setSkinWeights(null)');
      await grab('A');
      await api(`api.setSkinWeights(${spec.id}, ${spec.joints[0]})`);
      const H0 = await grab('H0');
      await api(`api.setSkinWeights(${spec.id}, ${spec.joints[1]})`);
      const H1 = await grab('H1');
      const dA = await diff('A', 'H0');
      const dJoints = await diff('H0', 'H1');
      await api('api.setSkinWeights(null)');
      await grab('A2');
      const back = await diff('A', 'A2');
      skinWeights = { H0, H1, dA, dJoints, back,
        ok: H0.hot > 20 && H1.hot > 20 && dA.differing > 300 && dJoints.differing > 300 && back.max === 0 };
    }
    finish({ ok: true, studio, shading, lightingSplit, skinWeights, entityCount, missingAssets, drawCalls, draws, counters, gpuPasses, gpuFrame, frameDebug, edge, cutoutEdge, minified, profile, capture, expect, twins, nineSlice, count, seam, resize, preview, meshPreview, grid, deviceLoss, roundtrip, meshResident, meshAsset, meshMaterial, meshPrefab, setField, animator, pick, cameraTarget }, server);
  } catch (e) {
    finish({ ok: false, error: String((e && e.stack) || e) }, server);
  }
});

// A verdict of "it took too long" is one this process can report; the runner
// kills it a launch margin later, and that one names no scene.
const TIMEOUT_MS = Number(process.env.ESTELLA_VERIFY_TIMEOUT_MS) || 45000;
setTimeout(() => finish({ ok: false, error: `timeout after ${TIMEOUT_MS} ms` }), TIMEOUT_MS);