@wildshard/engine 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lint/engine-sides.json +5 -0
  3. package/package.json +5 -2
  4. package/scripts/app-build/gen.ts +11 -0
  5. package/scripts/cell-mem-bench.mjs +2 -0
  6. package/scripts/chaos-proxy-core.mjs +14 -1
  7. package/scripts/chaos-proxy-proof.mjs +22 -0
  8. package/scripts/check-devserver.mjs +1 -1
  9. package/scripts/failmode-cases.d.mts +8 -0
  10. package/scripts/failmode-cases.mjs +97 -0
  11. package/scripts/failmode-proof.mjs +532 -0
  12. package/scripts/grid-crossing-nightly.mjs +5 -4
  13. package/scripts/grid-crossing-report.mjs +5 -2
  14. package/scripts/grid-crossing-tour.mjs +36 -12
  15. package/scripts/grid-crossing-walk-proof.mjs +4 -2
  16. package/scripts/hover-speed-probe.mjs +136 -0
  17. package/scripts/land.mjs +2 -1
  18. package/scripts/loading-flow/benchmax.mjs +34 -11
  19. package/scripts/loading-flow/deskbench.mjs +276 -0
  20. package/scripts/loading-flow/stalls.d.mts +17 -3
  21. package/scripts/loading-flow/stalls.mjs +82 -3
  22. package/scripts/net-lag-proof.mjs +3 -2
  23. package/scripts/nightly-model.ts +9 -6
  24. package/scripts/offline-proof.mjs +7 -1
  25. package/scripts/online-rig.mjs +9 -7
  26. package/scripts/parity/boot-smoke.mjs +13 -2
  27. package/scripts/pin-format.ts +5 -2
  28. package/scripts/pins-reuse.d.mts +1 -0
  29. package/scripts/pins-reuse.mjs +22 -0
  30. package/scripts/release-cook.mjs +109 -0
  31. package/scripts/scratch-dir.mjs +95 -0
  32. package/scripts/scratch-sweep.mjs +182 -0
  33. package/scripts/tsconfig.json +2 -12
  34. package/scripts/vps/harden-prometheus.sh +3 -0
  35. package/scripts/vps/rebuild.sh +35 -9
  36. package/scripts/vps/wildshard-apply.mjs +5 -1
  37. package/scripts/vps/wildshard-config +117 -1
  38. package/scripts/worktree-reap.mjs +54 -8
  39. package/scripts/worktree.mjs +19 -5
  40. package/src/client/engine/anim/rigParser.ts +2 -2
  41. package/src/client/engine/boot/contentRead.ts +54 -5
  42. package/src/client/engine/boot/gpuFiles.ts +3 -3
  43. package/src/client/engine/boot/leaveAfterPaint.ts +4 -1
  44. package/src/client/engine/core/Game.ts +63 -19
  45. package/src/client/engine/core/gpuOnly.ts +10 -0
  46. package/src/client/engine/core/renderBudget.ts +134 -0
  47. package/src/client/engine/core/shadowLayer.ts +18 -0
  48. package/src/client/engine/explore/pick.ts +13 -1
  49. package/src/client/engine/net/predictor.ts +12 -4
  50. package/src/client/engine/net/redial.ts +40 -5
  51. package/src/client/engine/player/TouchControls.ts +3 -2
  52. package/src/client/engine/render/dataLook.ts +70 -7
  53. package/src/client/engine/render/families/pbr.ts +2 -0
  54. package/src/client/engine/render/families/registry.ts +11 -2
  55. package/src/client/engine/render/families/sceneSurface.ts +118 -0
  56. package/src/client/engine/render/look.ts +7 -1
  57. package/src/client/engine/render/precompile.ts +4 -2
  58. package/src/client/engine/render/tiers.ts +4 -1
  59. package/src/client/engine/telemetry/browserErrors.ts +3 -1
  60. package/src/client/engine/ui/ErrorModal.ts +1 -1
  61. package/src/client/engine/ui/Loading.ts +14 -2
  62. package/src/client/engine/ui/errorScreen.ts +51 -9
  63. package/src/client/engine/ui/hoverBoost.ts +31 -4
  64. package/src/client/engine/ui/styles/touch.css +6 -0
  65. package/src/client/engine/world/declaredProps.ts +5 -1
  66. package/src/client/engine/world/skyRig.ts +4 -1
  67. package/src/client/engine/world/terrainTileView.ts +64 -23
  68. package/src/client/game/boot/spawnDownload.ts +44 -6
  69. package/src/client/game/devScene/hook.ts +149 -12
  70. package/src/client/game/devScene/liveLook.ts +21 -0
  71. package/src/client/game/grid/live.ts +47 -10
  72. package/src/client/game/grid/liveSession.ts +25 -6
  73. package/src/client/game/grid/pageEntry.ts +12 -1
  74. package/src/client/game/grid/productInputs.ts +22 -11
  75. package/src/client/game/grid/session.ts +15 -4
  76. package/src/client/game/grid/shardfileFar.ts +13 -2
  77. package/src/client/game/session/finish.ts +4 -1
  78. package/src/client/game/shardfile/client.ts +24 -7
  79. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  80. package/src/client/game/shardfile/clientSource.ts +7 -3
  81. package/src/client/game/shardfile/clientViews.ts +36 -8
  82. package/src/client/game/shardfile/clientWorker.ts +4 -4
  83. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  84. package/src/client/game/shardfile/groundMerge.ts +59 -5
  85. package/src/client/game/shardfile/hybrid.ts +2 -0
  86. package/src/client/game/shardfile/look.ts +1 -1
  87. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  88. package/src/client/game/shardfile/tileContent.ts +1 -1
  89. package/src/client/game/shardfile/tileDriver.ts +38 -11
  90. package/src/client/game/shardfile/wirePage.ts +7 -3
  91. package/src/client/game/shardfile/worldScenes.ts +17 -10
  92. package/src/client/host/online/doctor.ts +20 -7
  93. package/src/client/host/online/doctorView.ts +2 -0
  94. package/src/client/host/online/linkScreens.ts +95 -11
  95. package/src/client/host/online/reconnectStrip.ts +3 -2
  96. package/src/client/host/online/release.ts +87 -16
  97. package/src/client/host/online/releaseScreens.ts +108 -0
  98. package/src/client/host/online/shell.ts +24 -5
  99. package/src/client/host/online/voice.ts +45 -1
  100. package/src/client/host/online/voiceUi.ts +24 -6
  101. package/src/client/host/standalone/shell.ts +37 -1
  102. package/src/server/engine/sim/playerSim.ts +1 -1
  103. package/src/server/game/grid/simulation.ts +12 -6
  104. package/src/server/game/quest/eliteDrops.ts +7 -3
  105. package/src/server/game/riding/nativeTaming.ts +13 -2
  106. package/src/server/host/dedicated/cellHost.ts +21 -2
  107. package/src/server/host/dedicated/cellProtocol.ts +2 -0
  108. package/src/server/host/dedicated/cellWorker.ts +1 -1
  109. package/src/server/host/dedicated/dedicatedRoom.ts +38 -8
  110. package/src/server/host/dedicated/roadRoom.ts +3 -0
  111. package/src/server/host/dedicated/serverMetrics.ts +9 -0
  112. package/src/server/host/dedicated/workerTable.ts +31 -24
  113. package/src/server/host/standalone/gridServer.ts +1 -1
  114. package/src/server/host/standalone/serverHost.ts +56 -10
  115. package/src/server/host/standalone/serverProduct.ts +9 -7
  116. package/src/server/host/standalone/serverRuntime.ts +1 -1
  117. package/src/shared/engine/boot/loadingWaits.ts +10 -2
  118. package/src/shared/engine/core/config.ts +3 -0
  119. package/src/shared/engine/core/framePacing.ts +12 -1
  120. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  121. package/src/shared/engine/player/hoverSpeed.ts +3 -3
  122. package/src/shared/engine/strings.ts +12 -1
  123. package/src/shared/game/devColliders.ts +60 -0
  124. package/src/shared/game/devGameplay.ts +41 -0
  125. package/src/shared/game/grid/rules.ts +12 -0
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env node
2
+ // NINE-DRAGON-BENCHMAX NB5, widened (meta QA-FEEDBACK-2026-11-14 rows 2, 3 and 5): the desktop frame on Jake's window.
3
+ // Headless Chromium (ANGLE Metal, vsync and the frame-rate limit off, so a frame shows its real cost), 1496x717 CSS px at
4
+ // device scale 2 by default (Jake's Chrome on his Mac: 2992x1434 device pixels), the desktop tier, entering a shard
5
+ // through the title as he does (SHARD SELECT, the card, ENTER WORLD: the grid at the shard's cell). At each pose it prints
6
+ // the drawn frame (median / p95 / max), the game's main-thread work in it (update, render), the draws and triangles and
7
+ // the drawing buffer (pixel ratio, megapixels).
8
+ // scripts/browser-lane.sh node scripts/loading-flow/deskbench.mjs --base <url> [--shards Nine,Nalati,Driftwood]
9
+ // [--frames 240] [--poses 6] [--width 1496 --height 717 --scale 2] [--gfx-dpr 1|1.5|2|native] [--json <out.json>]
10
+ // [--shots <dir>] [--profile <dir>] [--census] [--ab] [--capped] [--stalls]
11
+ // --stalls: NB6's play-stall ratchet at each pose (exits 1 on a stall); with --capped, the desktop check Ring 1 can't run.
12
+ // --ab: at the last pose, each lever against the baseline, interleaved over 6 rounds so a busy machine's drift cancels
13
+ // (render scale 1 and 0.75, the shadow maps held, AO off, the post passes off, the viewmodel hidden).
14
+ // --hide <regex>: at each pose a second shot with every object whose name matches and everything under it drawn on no layer (what is behind it).
15
+ // --census: one frame's renderer.render calls (target, draws, CPU ms) and the scene graph's size.
16
+ // --profile: a Chromium CPU profile of each pose's sample. GPU timer queries are left out: ANGLE Metal's TIME_ELAPSED
17
+ // read 17-24 ms for frames drawn every 7-10 ms (2026-11-14), so a cost here is a drawn interval or a subtraction.
18
+ import { mkdirSync, writeFileSync } from 'node:fs';
19
+ import { join } from 'node:path';
20
+ import { parseArgs } from 'node:util';
21
+ import { chromium } from 'playwright';
22
+ import { KEYCHAIN_ARGS } from '../chromium-keychain.mjs';
23
+ import { finishPlayProfile, startStallProfile } from './stalls.mjs';
24
+ import { NAME_ASKED, developerSettings, saveFixture, levelDownloadFixtures, hideDeveloperOverlays, harnessPins } from '../debug-settings.mjs';
25
+
26
+ const { values } = parseArgs({ options: { base: { type: 'string' }, shards: { type: 'string', default: 'Nine,Nalati,Driftwood' },
27
+ frames: { type: 'string', default: '240' }, poses: { type: 'string', default: '6' }, width: { type: 'string', default: '1496' },
28
+ height: { type: 'string', default: '717' }, scale: { type: 'string', default: '2' }, json: { type: 'string' }, shots: { type: 'string' },
29
+ 'gfx-dpr': { type: 'string' }, extra: { type: 'string' }, walk: { type: 'string', default: '0' }, ab: { type: 'boolean', default: false }, capped: { type: 'boolean', default: false }, stalls: { type: 'boolean', default: false }, census: { type: 'boolean', default: false }, profile: { type: 'string' }, hide: { type: 'string' }, settle: { type: 'string', default: '2500' } } });
30
+ if (values.base === undefined) { console.error('usage: deskbench.mjs --base <url> [--shards Nine,Nalati,Driftwood] [--frames 240] [--poses 6] [--json <file>] [--shots <dir>] [--profile <dir>] [--census] [--ab]'); process.exit(2); }
31
+ // --stalls reads busy time: an uncapped frame loop keeps the main thread busy by design and would fault every pose
32
+ if (values.stalls && !values.capped) { console.error('deskbench: --stalls needs --capped (an uncapped frame loop is busy by design)'); process.exit(2); }
33
+ const base = values.base.replace(/\/$/u, ''), frames = Number(values.frames), maxPoses = Number(values.poses), settle = Number(values.settle);
34
+ const walkSeconds = Number(values.walk);
35
+ const viewport = { width: Number(values.width), height: Number(values.height) }, scale = Number(values.scale);
36
+ /** @param {number} ms */
37
+ const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms); });
38
+ if (values.shots !== undefined) mkdirSync(values.shots, { recursive: true });
39
+
40
+ /** Browser side: `n` drawn frames by rAF timestamp (the frame interval, uncapped), with the game's work per frame. */
41
+ function sampleFrames(/** @type {number} */ n) {
42
+ const g = /** @type {any} */ (window).__wildshard.world.game;
43
+ return new Promise((resolve, reject) => {
44
+ /** @type {number[]} */ const intervals = [];
45
+ /** @type {number[]} */ const work = [];
46
+ /** @type {number[]} */ const update = [];
47
+ /** @type {number[]} */ const render = [];
48
+ let count = g.frameCount, last = -1;
49
+ const timeout = setTimeout(() => { reject(new Error('sampler stalled')); }, 60_000);
50
+ const tick = (/** @type {number} */ t) => {
51
+ if (g.frameCount !== count) {
52
+ if (last >= 0) { const i = (g.frameI + g.frameMs.length - 1) % g.frameMs.length; intervals.push(t - last); work.push(g.workMs[i]); update.push(g.updateMs[i]); render.push(g.renderMs[i]); }
53
+ count = g.frameCount; last = t;
54
+ }
55
+ if (intervals.length < n) { requestAnimationFrame(tick); return; }
56
+ clearTimeout(timeout);
57
+ const pct = (/** @type {number[]} */ v, /** @type {number} */ p) => { const s = [...v].sort((a, b) => a - b); return s[Math.max(0, Math.ceil(s.length * p) - 1)] ?? 0; };
58
+ const r = (/** @type {number} */ v) => Math.round(v * 10) / 10;
59
+ const r2 = g.renderer, size = { x: g.canvas.width, y: g.canvas.height };
60
+ resolve({ p50: r(pct(intervals, 0.5)), p95: r(pct(intervals, 0.95)), max: r(Math.max(...intervals)), mean: r(intervals.reduce((a, b) => a + b, 0) / intervals.length),
61
+ workP50: r(pct(work, 0.5)), workP95: r(pct(work, 0.95)), updateP50: r(pct(update, 0.5)), renderP50: r(pct(render, 0.5)), calls: g.lastFrame.calls, triangles: g.lastFrame.triangles,
62
+ pixelRatio: r2.getPixelRatio(), buffer: [size.x, size.y], mpx: Math.round(size.x * size.y / 1e4) / 100 });
63
+ };
64
+ requestAnimationFrame(tick);
65
+ });
66
+ }
67
+
68
+ /** Browser side: two drawn frames' renderer.render calls (scene, camera, target, draws, CPU ms) and the scene graph's size. */
69
+ function frameCensus() {
70
+ const g = /** @type {any} */ (window).__wildshard.world.game, r = g.renderer;
71
+ /** @type {any[]} */
72
+ const calls = [];
73
+ const own = Object.getOwnPropertyDescriptor(r, 'render'), main = r.render.bind(r);
74
+ r.render = function render(/** @type {any} */ scene, /** @type {any} */ camera) {
75
+ const t = r.getRenderTarget(), before = r.info.render.calls, start = performance.now();
76
+ main(scene, camera);
77
+ calls.push({ scene: scene.name === '' ? scene.type : scene.name, camera: camera.name === '' ? camera.type : camera.name, target: t ? `${t.width}x${t.height}` : 'screen', draws: r.info.render.calls - before, ms: Math.round((performance.now() - start) * 100) / 100 });
78
+ };
79
+ let objects = 0, meshes = 0, visibleMeshes = 0, autoUpdate = 0, lights = 0, skinned = 0;
80
+ g.rootScene.traverse((/** @type {any} */ o) => { objects++; if (o.matrixAutoUpdate) autoUpdate++; if (o.isLight) lights++; if (o.isSkinnedMesh) skinned++; if (o.isMesh || o.isPoints || o.isLine) meshes++; });
81
+ g.rootScene.traverseVisible((/** @type {any} */ o) => { if (o.isMesh || o.isPoints || o.isLine) visibleMeshes++; });
82
+ return new Promise((resolve) => {
83
+ const start = g.frameCount;
84
+ const tick = () => {
85
+ if (g.frameCount - start < 2) { requestAnimationFrame(tick); return; }
86
+ if (own === undefined) Reflect.deleteProperty(r, 'render'); else Object.defineProperty(r, 'render', own);
87
+ resolve({ objects, meshes, visibleMeshes, autoUpdate, lights, skinned, programs: r.info.programs?.length ?? -1, calls: calls.slice(0, 80), perFrame: calls.length / (g.frameCount - start) });
88
+ };
89
+ requestAnimationFrame(tick);
90
+ });
91
+ }
92
+
93
+ /** Browser side: walk `seconds` from where the player stands, recording drawn intervals and long animation frames. */
94
+ function walkHitches(/** @type {number} */ seconds) {
95
+ const w = /** @type {any} */ (window).__wildshard.world, g = w.game, input = g.app.input, p = w.player;
96
+ /** @type {any[]} */
97
+ const loafs = [];
98
+ const t0 = performance.now();
99
+ const observer = new PerformanceObserver((list) => { for (const e of /** @type {any[]} */ (list.getEntries())) loafs.push(e); });
100
+ try { observer.observe({ type: 'long-animation-frame', buffered: false }); } catch { /* no LoAF: intervals only */ }
101
+ return new Promise((resolve) => {
102
+ /** @type {number[]} */
103
+ const intervals = [];
104
+ let count = g.frameCount, last = -1;
105
+ const step = () => { if (performance.now() - t0 < seconds * 1000) { input.setHeld('move.forward', true); p.yaw += 0.004; setTimeout(step, 16); } };
106
+ step();
107
+ const tick = (/** @type {number} */ t) => {
108
+ if (g.frameCount !== count) { if (last >= 0) intervals.push(t - last); count = g.frameCount; last = t; }
109
+ if (performance.now() - t0 < seconds * 1000) { requestAnimationFrame(tick); return; }
110
+ input.setHeld('move.forward', false); observer.disconnect();
111
+ const s = [...intervals].sort((a, b) => a - b), at = (/** @type {number} */ q) => Math.round((s[Math.min(s.length - 1, Math.floor(s.length * q))] ?? 0) * 10) / 10;
112
+ const r = (/** @type {number} */ v) => Math.round(v);
113
+ resolve({ frames: intervals.length, p50: at(0.5), p95: at(0.95), p99: at(0.99), max: r(s.at(-1) ?? 0),
114
+ over33: intervals.filter((v) => v > 33).length, over50: intervals.filter((v) => v > 50).length, over100: intervals.filter((v) => v > 100).length,
115
+ loafs: loafs.sort((a, b) => b.duration - a.duration).slice(0, 12).map((e) => ({ at: Math.round((e.startTime - t0) / 100) / 10, duration: r(e.duration), blocking: r(e.blockingDuration ?? 0),
116
+ scripts: (e.scripts ?? []).sort((/** @type {any} */ a, /** @type {any} */ b) => b.duration - a.duration).slice(0, 3).map((/** @type {any} */ x) => ({ fn: x.sourceFunctionName === "" ? x.invoker : x.sourceFunctionName, src: `${String(x.sourceURL).split('/').pop()}:${x.sourceCharPosition}`, ms: r(x.duration) })) })) });
117
+ };
118
+ requestAnimationFrame(tick);
119
+ });
120
+ }
121
+
122
+ /** Browser side: each variant against the baseline, interleaved (A B A B …) so a busy machine's drift cancels. */
123
+ async function abCosts(/** @type {any} */ sampler) {
124
+ const g = /** @type {any} */ (window).__wildshard.world.game, r = g.renderer, ratio = r.getPixelRatio();
125
+ const wait = (/** @type {number} */ ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
126
+ const setRatio = (/** @type {number} */ v) => { r.setPixelRatio(v); g.resize(); };
127
+ /** @type {any[]} */
128
+ let held = [];
129
+ /** @type {any[]} */
130
+ const hidden = [];
131
+ const passes = () => g.composer.passes.slice(1).filter((/** @type {any} */ p) => p.enabled);
132
+ /** @type {[string, () => void, () => void][]} */
133
+ const variants = [
134
+ ['render scale 1.0', () => { setRatio(1); }, () => { setRatio(ratio); }],
135
+ ['render scale 0.75', () => { setRatio(0.75); }, () => { setRatio(ratio); }],
136
+ ['shadow maps held', () => { r.shadowMap.autoUpdate = false; }, () => { r.shadowMap.autoUpdate = true; }],
137
+ ['AO off', () => { const ao = g.post?.ao; if (ao) { ao.enabled = false; } }, () => { const ao = g.post?.ao; if (ao) ao.enabled = true; }],
138
+ ['post passes off', () => { for (const p of held = passes()) p.enabled = false; }, () => { for (const p of held) p.enabled = true; }],
139
+ ['viewmodel hidden', () => { g.camera.children.forEach((/** @type {any} */ c) => { if (c.visible) { hidden.push(c); c.visible = false; } }); }, () => { for (const c of hidden.splice(0)) c.visible = true; }],
140
+ ];
141
+ /** @type {Map<string, any[]>} */
142
+ const rows = new Map([['baseline', []], ...variants.map(([name]) => /** @type {[string, any[]]} */ ([name, []]))]);
143
+ for (let round = 0; round < 6; round++) {
144
+ for (const [name, off, on] of variants) {
145
+ await wait(150); rows.get('baseline')?.push(await sampler(60));
146
+ off(); await wait(250);
147
+ try { rows.get(name)?.push(await sampler(60)); } finally { on(); }
148
+ }
149
+ }
150
+ const med = (/** @type {number[]} */ v) => { const s = [...v].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] ?? 0; };
151
+ const baseline = med((rows.get('baseline') ?? []).map((x) => x.p50));
152
+ return [...rows].map(([variant, xs]) => { const p50 = med(xs.map((x) => x.p50)); return { variant, p50, saves: Math.round((baseline - p50) * 10) / 10, work: med(xs.map((x) => x.workP50)), render: med(xs.map((x) => x.renderP50)), calls: med(xs.map((x) => x.calls)) }; });
153
+ }
154
+
155
+ // --capped: vsync and the frame-rate limit kept (shots, look checks, CI): Jake plays on this Mac, and an uncapped page halves
156
+ // his frame rate (meta lane rules, opus-deskperf 11-14); uncapped only to read a frame's real cost
157
+ const browser = await chromium.launch({ headless: true, args: [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist',
158
+ ...(values.capped ? [] : ['--disable-gpu-vsync', '--disable-frame-rate-limit'])] });
159
+ /** @type {any[]} */
160
+ const report = [];
161
+ try {
162
+ for (const shardName of (values.shards ?? '').split(',').filter(Boolean)) {
163
+ const shard = new RegExp(shardName, 'iu');
164
+ const context = await browser.newContext({ viewport, deviceScaleFactor: scale });
165
+ await developerSettings(context, { tier: 'desktop', volume: 0 });
166
+ for (const fixture of levelDownloadFixtures('packs')) await saveFixture(context, fixture);
167
+ // --gfx-dpr: Settings ▸ Graphics' saved render scale (1, 1.25, 1.5, 2, native), for a pixel-count sweep at one window
168
+ if (values['gfx-dpr'] !== undefined) await saveFixture(context, { scope: 'global', key: 'gfx', data: { dpr: values['gfx-dpr'], aa: 'auto' } });
169
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
170
+ await saveFixture(context, NAME_ASKED);
171
+ await context.addInitScript(hideDeveloperOverlays);
172
+ await harnessPins(context, { seed: 357, capture: null }); // frame-floor's pins: the probe's pose control
173
+ const page = await context.newPage();
174
+ page.setDefaultTimeout(240_000);
175
+ /** @type {string[]} */
176
+ const errors = [];
177
+ page.on('pageerror', e => { errors.push(String(e).slice(0, 200)); });
178
+ const until = async (/** @type {string} */ expression, /** @type {number} */ ms) => { try { await page.waitForFunction(expression, null, { timeout: ms, polling: 200 }); return true; } catch { return false; } };
179
+ const tap = (/** @type {string} */ selector) => page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.click()`);
180
+ await page.goto(`${base}/`);
181
+ if (!await until(`!!document.querySelector('.ws-main-select')?.getClientRects().length`, 120_000)) throw new Error('title never ready');
182
+ await sleep(1500);
183
+ await tap('.ws-main-select');
184
+ if (!await until(`!!document.querySelector('.ws-menu-card')?.getClientRects().length`, 30_000)) throw new Error('shard select never ready');
185
+ await sleep(800);
186
+ const titles = await page.evaluate(`[...document.querySelectorAll('.ws-menu-card')].map(c => (c.querySelector('b')?.textContent ?? c.textContent ?? '').trim().slice(0, 40))`);
187
+ const target = titles.findIndex((/** @type {string} */ title) => shard.test(title));
188
+ if (target === -1) throw new Error(`no card matches ${shard} in ${JSON.stringify(titles)}`);
189
+ await tap(`.ws-menu-dots i[data-i="${target}"]`);
190
+ if (!await until(`document.querySelector('.ws-menu-card.selected')?.dataset.i === '${target}' && !document.querySelector('.ws-menu-play')?.disabled`, 15_000)) throw new Error(`${titles[target]} never selectable`);
191
+ await sleep(800);
192
+ const t0 = Date.now();
193
+ await page.evaluate(`setTimeout(() => document.querySelector('.ws-menu-play').click(), 0)`);
194
+ const control = `(() => { const w = window.__wildshard?.world, l = document.querySelector('.ws-load');
195
+ const shown = !!l && l.isConnected && l.getClientRects().length > 0 && getComputedStyle(l).display !== 'none' && Number(getComputedStyle(l).opacity) > .05;
196
+ try { return !!w?.hud.entered && !w.hud.paused && w.game.frameGate() && !shown; } catch { return false; } })()`;
197
+ if (!await until(control, 300_000)) throw new Error(`${titles[target]} never reached control`);
198
+ const controlS = (Date.now() - t0) / 1000;
199
+ await sleep(5000);
200
+ const meta = await page.evaluate(`(() => { const w = window.__wildshard.world, g = w.game, gl = g.renderer.getContext(), ext = gl.getExtension('WEBGL_debug_renderer_info');
201
+ return { level: g.level.id, renderer: ext ? String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL)) : '', dpr: devicePixelRatio, viewport: [innerWidth, innerHeight],
202
+ spawn: { name: 'spawn', x: w.player.position.x, y: w.player.position.y, z: w.player.position.z, yaw: w.player.yaw, pitch: w.player.pitch },
203
+ passes: g.composer.passes.map(p => (p.name || p.constructor.name) + (p.effects ? ' (' + p.effects.map(e => e.name || e.constructor.name).join('+') + ')' : '')) }; })()`);
204
+ const profileDir = values.profile, cdp = profileDir === undefined ? null : await context.newCDPSession(page);
205
+ if (cdp !== null && profileDir !== undefined) { mkdirSync(profileDir, { recursive: true }); await cdp.send('Profiler.enable'); await cdp.send('Profiler.setSamplingInterval', { interval: 200 }); }
206
+ const authored = await page.evaluate(`(async () => { const a = await window.__wildshard.world.game.level.capturePoses?.() ?? {};
207
+ return Object.entries(a).flatMap(([name, c]) => c.probe ? [{ ...c.probe, name: c.probe.name ?? name }] : c.feet ? [{ name, x: c.feet[0], y: c.feet[1], z: c.feet[2], yaw: -c.yaw * Math.PI / 180, pitch: c.pitch * Math.PI / 180 }] : []); })()`);
208
+ // --extra 'forward,right,yawDeg[,pitchDeg];…': more poses from the spawn, in metres along its facing and degrees off it
209
+ const extra = (values.extra ?? '').split(';').filter(Boolean).map((row, i) => {
210
+ const [forward = 0, right = 0, yawDeg = 0, pitchDeg = 0] = row.split(',').map(Number), yaw = meta.spawn.yaw;
211
+ // the probe's yaw faces -z at 0 (three's camera): forward is (-sin, -cos), right is (cos, -sin)
212
+ return { name: `extra-${i}`, x: meta.spawn.x - Math.sin(yaw) * forward + Math.cos(yaw) * right, y: meta.spawn.y, z: meta.spawn.z - Math.cos(yaw) * forward - Math.sin(yaw) * right,
213
+ yaw: yaw + yawDeg * Math.PI / 180, pitch: pitchDeg * Math.PI / 180 };
214
+ });
215
+ const poses = [meta.spawn, { ...meta.spawn, name: 'spawn-reverse', yaw: meta.spawn.yaw + Math.PI }, ...authored].slice(0, maxPoses).concat(extra);
216
+ console.log(`deskbench ${titles[target]} (${meta.level}) at ${base}: control ${controlS.toFixed(1)} s · ${meta.viewport.join('x')} @${meta.dpr} · ${meta.renderer}`);
217
+ console.log(` passes: ${meta.passes.join(' | ')}`);
218
+ /** @type {any[]} */
219
+ const rows = [];
220
+ for (const pose of poses) {
221
+ await page.evaluate(`window.__wildshard.pose(${JSON.stringify(pose)})`);
222
+ await sleep(settle);
223
+ if (cdp !== null) await cdp.send('Profiler.start');
224
+ // --stalls (NB6, desktop): ring 1's play-stall ratchet over this pose's sample (scripts/loading-flow/stalls.mjs)
225
+ const stallSession = values.stalls && cdp === null ? await startStallProfile(page) : null, stallFrom = Number(await page.evaluate('performance.now()'));
226
+ const frame = await page.evaluate(`(${sampleFrames.toString()})(${frames})`);
227
+ if (stallSession !== null) {
228
+ const read = await finishPlayProfile(page, stallSession, stallFrom);
229
+ console.log(` ${pose.name.padEnd(22)} play stall: worst ${(read.stall.busyMs / 1000).toFixed(2)} s busy of a 1.5 s window${read.faults.length === 0 ? '' : ` · ${read.faults.join('; ')} · ${read.leaves.join(', ')}`}`);
230
+ if (read.faults.length > 0) process.exitCode = 1;
231
+ }
232
+ if (cdp !== null && values.profile !== undefined) { const { profile } = await cdp.send('Profiler.stop'); writeFileSync(join(values.profile, `${shardName}-${pose.name}.cpuprofile`.replaceAll(/[^\w.-]+/gu, '_')), JSON.stringify(profile)); }
233
+ rows.push({ pose, frame });
234
+ console.log(` ${pose.name.padEnd(22)} ${(1000 / frame.p50).toFixed(0).padStart(4)} fps · p50 ${frame.p50} p95 ${frame.p95} max ${frame.max} ms · work p50 ${frame.workP50} (update ${frame.updateP50} render ${frame.renderP50}) p95 ${frame.workP95} · ${frame.calls} draws · ${(frame.triangles / 1e6).toFixed(2)} M tris · ratio ${frame.pixelRatio} ${frame.buffer.join('x')} (${frame.mpx} Mpx)`);
235
+ if (values.shots !== undefined) await page.screenshot({ path: join(values.shots, `${shardName}-${pose.name}.jpg`.replaceAll(/[^\w.-]+/gu, '_')), type: 'jpeg', quality: 82, scale: 'css' });
236
+ if (values.shots !== undefined && values.hide !== undefined) {
237
+ // --hide: every scene the frame draws (the shard's own and each region's), matching objects off every layer
238
+ const hidden = await page.evaluate(`(() => { const g = window.__wildshard.world.game, re = new RegExp(${JSON.stringify(values.hide)}, 'u'), names = new Map();
239
+ window.__deskHide = [];
240
+ for (const scene of [g.scene, ...(g.sceneFrames ?? []).map(f => f.scene)]) scene.traverse(o => { if (re.test(o.name)) { o.traverse(c => { window.__deskHide.push([c, c.layers.mask]); c.layers.mask = 0; }); names.set(o.name, (names.get(o.name) ?? 0) + 1); } });
241
+ return [...names].map(([n, c]) => n + ' x' + c).join(', '); })()`);
242
+ await sleep(600);
243
+ await page.screenshot({ path: join(values.shots, `${shardName}-${pose.name}-hidden.jpg`.replaceAll(/[^\w.-]+/gu, '_')), type: 'jpeg', quality: 82, scale: 'css' });
244
+ await page.evaluate(`(() => { for (const [o, m] of window.__deskHide) o.layers.mask = m; })()`);
245
+ console.log(` hidden: ${hidden === '' ? 'nothing matched' : hidden}`);
246
+ }
247
+ }
248
+ if (values.census) {
249
+ const c = await page.evaluate(`(${frameCensus.toString()})()`);
250
+ console.log(` census: ${c.objects} objects (${c.autoUpdate} auto-update), ${c.meshes} meshes (${c.visibleMeshes} visible), ${c.lights} lights, ${c.skinned} skinned, ${c.programs} programs, ${c.perFrame} renderer.render calls a frame`);
251
+ for (const k of c.calls.slice(0, Math.ceil(c.perFrame))) console.log(` ${k.scene} / ${k.camera} to ${k.target}: ${k.draws} draws, ${k.ms} ms`);
252
+ }
253
+ /** @type {any} */
254
+ let walk = null;
255
+ if (walkSeconds > 0) {
256
+ // --walk: from the spawn, walk forward turning slowly for N seconds (benchmax's input), every drawn interval kept, and
257
+ // Chromium's long animation frames (their scripts, by source position) for the hitches
258
+ await page.evaluate(`window.__wildshard.pose(${JSON.stringify(meta.spawn)})`);
259
+ await sleep(settle);
260
+ walk = await page.evaluate(`(${walkHitches.toString()})(${walkSeconds})`);
261
+ console.log(` walk ${walkSeconds} s: ${walk.frames} frames · p50 ${walk.p50} p95 ${walk.p95} p99 ${walk.p99} max ${walk.max} ms · over 33 ms ${walk.over33} · over 50 ms ${walk.over50} · over 100 ms ${walk.over100}`);
262
+ for (const loaf of walk.loafs.slice(0, 8)) console.log(` +${loaf.at} s ${loaf.duration} ms (blocking ${loaf.blocking}): ${loaf.scripts.map((/** @type {any} */ x) => `${x.fn}@${x.src} ${x.ms} ms`).join(' | ')}`);
263
+ }
264
+ /** @type {any} */
265
+ let ab = null;
266
+ if (values.ab) {
267
+ ab = await page.evaluate(`(${abCosts.toString()})(${sampleFrames.toString()})`);
268
+ console.log(' interleaved A/B at the last pose (median of 6 rounds, 60 frames each; saved ms = baseline minus variant):');
269
+ for (const v of ab) console.log(` ${v.variant.padEnd(34)} p50 ${v.p50} (saves ${v.saves}) · work ${v.work} · render ${v.render} · ${v.calls} draws`);
270
+ }
271
+ if (errors.length > 0) console.log(` page errors: ${errors.slice(0, 5).join(' | ')}`);
272
+ report.push({ shard: titles[target], meta, controlS, rows, walk, ab, errors });
273
+ await context.close();
274
+ }
275
+ } finally { await browser.close(); }
276
+ if (values.json !== undefined) writeFileSync(values.json, `${JSON.stringify(report, null, 1)}\n`);
@@ -7,7 +7,7 @@ export interface Span { start: number; end: number }
7
7
  /** A stage's worst window: its unexplained idle (ms) and where the window starts in the stage. */
8
8
  export interface StageStall { stage: string; from: number; idleMs: number; stageMs: number }
9
9
  /** A Chromium CPU profile, as `Profiler.stop` returns it. */
10
- export interface CpuProfile { nodes: readonly { id: number; callFrame: { functionName: string } }[]; samples?: readonly number[]; timeDeltas?: readonly number[]; startTime: number; endTime: number }
10
+ export interface CpuProfile { nodes: readonly { id: number; callFrame: { functionName: string; url?: string } }[]; samples?: readonly number[]; timeDeltas?: readonly number[]; startTime: number; endTime: number }
11
11
 
12
12
  /** The window a stall is judged over (ms). */
13
13
  export const STALL_WINDOW_MS: number;
@@ -17,8 +17,8 @@ export const STALL_IDLE_SHARE: number;
17
17
  export const STALL_STAGES: readonly string[];
18
18
  /** The page function the clock mark runs, by this name in the profile. */
19
19
  export const CLOCK_MARK: string;
20
- /** The page expression that runs the clock mark and returns its start on the page clock. */
21
- export const CLOCK_MARK_EXPRESSION: string;
20
+ /** A fresh page expression (new text each call) that runs the clock mark and returns its start on the page clock. */
21
+ export function clockMarkExpression(): string;
22
22
  /** Idle spans merged, minus holes, cut to [from, to]. */
23
23
  export function idleWithin(spans: readonly Span[], holes: readonly Span[], from: number, to: number): Span[];
24
24
  /** The most of the spans inside any window of `width`, and where that window starts. */
@@ -37,3 +37,17 @@ export function bootTimelineEntries(): StallEntry[];
37
37
  export function startStallProfile(page: Page): Promise<CDPSession | null>;
38
38
  /** End a stall profile at control: the ratcheted stages' worst windows and their faults. */
39
39
  export function finishStallProfile(page: Page, session: CDPSession): Promise<{ stalls: StageStall[]; faults: string[] }>;
40
+ /** NB6, play: a stretch of live frames' worst window of unbroken main-thread work (ms), where it starts, and play's length. */
41
+ export interface PlayStall { from: number; busyMs: number; playMs: number }
42
+ /** The share of the window unbroken main-thread work must reach to be a play stall. */
43
+ export const PLAY_BUSY_SHARE: number;
44
+ /** A profile's main-thread work on the page clock: neither idle, `(program)`, nor a WebGL call's native leaf. */
45
+ export function profileBusy(profile: CpuProfile, anchor: { pageMs: number; profileUs: number }): Span[];
46
+ /** Play's worst window of [from, to]. */
47
+ export function playStall(busy: readonly Span[], from: number, to: number): PlayStall;
48
+ /** A play stall at or over the share, as a fault line. */
49
+ export function playStallFaults(stall: PlayStall): string[];
50
+ /** End a play profile: play's worst window from `fromPageMs` and its fault. */
51
+ export function finishPlayProfile(page: Page, session: CDPSession, fromPageMs: number): Promise<{ stall: PlayStall; faults: string[]; leaves: string[] }>;
52
+ /** The leaves that held a window of a profile, most sampled first (at most three), as `name (file) ms`. */
53
+ export function busiestLeaves(profile: CpuProfile, anchor: { pageMs: number; profileUs: number }, at: number, width: number): string[];
@@ -108,10 +108,16 @@ export function profileIdle(profile, anchor) {
108
108
  return out;
109
109
  }
110
110
 
111
- /** The page expression that runs the clock mark: 30 ms busy inside CLOCK_MARK, returning its start on the page clock. */
112
- export const CLOCK_MARK_EXPRESSION = `(() => { const start = performance.now(), until = start + 30;
111
+ let clockMarks = 0;
112
+ /** The page expression that runs the clock mark: 30 ms busy inside CLOCK_MARK, returning its start on the page clock. Each
113
+ * call's text is new: V8 reuses a repeated eval's compiled script, and a second mark (play's profile after boot's) then
114
+ * ran with CLOCK_MARK inlined into its caller and never sampled by name (NB6).
115
+ * @returns {string} */
116
+ export function clockMarkExpression() {
117
+ return `/* clock mark ${++clockMarks} */ (() => { const start = performance.now(), until = start + 30;
113
118
  function ${CLOCK_MARK}() { while (performance.now() < until) { /* busy: the profiler samples this function */ } }
114
119
  ${CLOCK_MARK}(); return start; })()`;
120
+ }
115
121
 
116
122
  /** Browser-side: the page's boot timeline entries (its own collector, as Copy diagnostics reads it). */
117
123
  export function bootTimelineEntries() {
@@ -133,9 +139,82 @@ export async function startStallProfile(page) {
133
139
  /** End a stall profile at control: pin its clock with the mark, then the ratcheted stages' worst windows and their faults.
134
140
  * @param {import('playwright').Page} page @param {import('playwright').CDPSession} session */
135
141
  export async function finishStallProfile(page, session) {
136
- const markPageMs = Number(await page.evaluate(CLOCK_MARK_EXPRESSION));
142
+ const markPageMs = Number(await page.evaluate(clockMarkExpression()));
137
143
  const { profile } = await session.send('Profiler.stop');
138
144
  await session.detach().catch(() => undefined);
139
145
  const entries = await page.evaluate(bootTimelineEntries), idle = profileIdle(profile, profileAnchor(profile, markPageMs));
140
146
  return { stalls: stageStalls(entries, idle), faults: stallFaults(entries, idle) };
141
147
  }
148
+
149
+ // NINE-DRAGON-BENCHMAX NB6, widened to play (meta QA-FEEDBACK-2026-11-14 rows 2, 3, 5): a play stall is a stretch of live
150
+ // frames in which the page's main thread ran its own work without a break: script, layout, style or GC, but not idle and
151
+ // not a WebGL call waiting on the GPU process. A slow or software GPU (CI's SwiftShader draws a frame every few seconds)
152
+ // makes frames slower and the main thread idler or GPU-bound, not busier; a 2 s busy sleep in a frame is busy for its whole
153
+ // length whatever the GPU. Ring 1's boot smoke refuses one over the ten gameplay frames it already waits on, every case.
154
+ /** The share of a STALL_WINDOW_MS stretch of play that unbroken main-thread work must reach to be a stall. */
155
+ export const PLAY_BUSY_SHARE = 0.8;
156
+ /** Native leaves that are still the page's own work: the clock read a busy loop spins on, and the collector. Every other
157
+ * native leaf (no script url) is left out: on CI's SwiftShader any WebGL entry point can wait seconds on the GPU process
158
+ * (a link finishing under `getUniformLocation`, a fence under `getError`), and a named list missed some (ring 1, sunscar
159
+ * dunes, 2026-11-14: a 1.5 s "stall" 15 s into play at 2.4 s a frame). A page stall is script; its builtins undercount it. */
160
+ const PAGE_NATIVE = new Set(['now', '(garbage collector)']);
161
+
162
+ /** A Chromium CPU profile's main-thread work on the page clock: every sample whose leaf is script (it has a url) or one of
163
+ * PAGE_NATIVE, over [its time, the next sample's).
164
+ * @param {CpuProfile & { nodes: readonly { id: number, callFrame: { functionName: string, url?: string } }[] }} profile
165
+ * @param {{ pageMs: number, profileUs: number }} anchor @returns {Span[]} */
166
+ export function profileBusy(profile, anchor) {
167
+ const quiet = new Set(profile.nodes.filter(node => (node.callFrame.url ?? '') === '' && !PAGE_NATIVE.has(node.callFrame.functionName)).map(node => node.id));
168
+ const samples = profile.samples ?? [], page = (/** @type {number} */ us) => anchor.pageMs + (us - anchor.profileUs) / 1000;
169
+ let at = profile.startTime;
170
+ const times = (profile.timeDeltas ?? []).map(delta => (at += delta));
171
+ /** @type {Span[]} */ const out = [];
172
+ for (let i = 0; i + 1 < samples.length; i++) {
173
+ if (quiet.has(samples[i] ?? -1)) continue;
174
+ out.push({ start: page(times[i] ?? 0), end: page(times[i + 1] ?? 0) });
175
+ }
176
+ return merged(out);
177
+ }
178
+
179
+ /** Play's worst window: the most main-thread work in any STALL_WINDOW_MS stretch of [from, to].
180
+ * @param {readonly Span[]} busy @param {number} from @param {number} to @returns {{ from: number, busyMs: number, playMs: number }} */
181
+ export function playStall(busy, from, to) {
182
+ const worst = busiestWindow(idleWithin(busy, [], from, to), STALL_WINDOW_MS);
183
+ return { from: Math.max(0, worst.at - from), busyMs: worst.ms, playMs: to - from };
184
+ }
185
+
186
+ /** A play stall as a fault line, when its window's work reaches PLAY_BUSY_SHARE of it.
187
+ * @param {{ from: number, busyMs: number, playMs: number }} stall @returns {string[]} */
188
+ export function playStallFaults(stall) {
189
+ return stall.busyMs < STALL_WINDOW_MS * PLAY_BUSY_SHARE ? []
190
+ : [`Play stall: the main thread worked ${(stall.busyMs / 1000).toFixed(2)} s of a ${(STALL_WINDOW_MS / 1000).toFixed(1)} s window without a break (from +${(stall.from / 1000).toFixed(1)} s of ${(stall.playMs / 1000).toFixed(1)} s of play; NINE-DRAGON-BENCHMAX NB6)`];
191
+ }
192
+
193
+ /** End a play profile (started with `startStallProfile` at the first gameplay frame): pin its clock with the mark, then
194
+ * play's worst window and its fault.
195
+ * @param {import('playwright').Page} page @param {import('playwright').CDPSession} session @param {number} fromPageMs */
196
+ export async function finishPlayProfile(page, session, fromPageMs) {
197
+ const markPageMs = Number(await page.evaluate(clockMarkExpression()));
198
+ const { profile } = await session.send('Profiler.stop');
199
+ await session.detach().catch(() => undefined);
200
+ // the clock mark's own 30 ms of busy work ends the window
201
+ const anchor = profileAnchor(profile, markPageMs), stall = playStall(profileBusy(profile, anchor), fromPageMs, markPageMs);
202
+ return { stall, faults: playStallFaults(stall), leaves: busiestLeaves(profile, anchor, fromPageMs + stall.from, STALL_WINDOW_MS) };
203
+ }
204
+
205
+ /** The leaves that held a window of a profile, most sampled first, as `name (file) ms` (at most three): what a stall was.
206
+ * @param {CpuProfile & { nodes: readonly { id: number, callFrame: { functionName: string, url?: string } }[] }} profile
207
+ * @param {{ pageMs: number, profileUs: number }} anchor @param {number} at @param {number} width @returns {string[]} */
208
+ export function busiestLeaves(profile, anchor, at, width) {
209
+ const byId = new Map(profile.nodes.map(node => [node.id, node.callFrame])), held = new Map();
210
+ const samples = profile.samples ?? [];
211
+ let us = profile.startTime;
212
+ const times = (profile.timeDeltas ?? []).map(delta => (us += delta));
213
+ for (let i = 0; i + 1 < samples.length; i++) {
214
+ const start = anchor.pageMs + ((times[i] ?? 0) - anchor.profileUs) / 1000, end = anchor.pageMs + ((times[i + 1] ?? 0) - anchor.profileUs) / 1000;
215
+ if (end <= at || start >= at + width) continue;
216
+ const frame = byId.get(samples[i] ?? -1), name = frame === undefined ? '?' : `${frame.functionName || '(anonymous)'}${frame.url ? ` (${frame.url.split('/').pop()})` : ''}`;
217
+ held.set(name, (held.get(name) ?? 0) + Math.min(end, at + width) - Math.max(start, at));
218
+ }
219
+ return [...held].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([name, ms]) => `${name} ${Math.round(ms)} ms`);
220
+ }
@@ -107,7 +107,7 @@ async function runOne(browser, engineName, layout, slug, site, socket) {
107
107
  if (await page.evaluate(() => /** @type {any} */ (window).__wildshard?.world?.game.app.clock.paused === true)) await page.getByRole('button', { name: /^resume$/iu }).click().catch(() => undefined);
108
108
  row.enterMs = Date.now() - t0;
109
109
  const entered = Date.now(), delays = /** @type {{ t: number, delay: number }[]} */ ([]), heldFrom = await page.evaluate(() => window.__workerClient?.().interpHeld ?? 0);
110
- const report = () => page.evaluate(() => { const w = window.__workerClient?.(); return w === undefined ? null : { corrections: w.corrections, worst: w.worstOffset, delay: w.delayMs, held: w.interpHeld, falls: w.falls, missed: { ...w.missed } }; });
110
+ const report = () => page.evaluate(() => { const w = window.__workerClient?.(); return w === undefined ? null : { corrections: w.corrections, worst: w.worstOffset, delay: w.delayMs, held: w.interpHeld, falls: w.falls, missed: { ...w.missed }, authoritative: { ...w.authoritative } }; });
111
111
  sampler = setInterval(() => { void report().then(r => { if (r !== null) delays.push({ t: Date.now() - entered, delay: r.delay }); return undefined; }).catch(() => undefined); }, 250);
112
112
  await sleep(2000);
113
113
  // the budget: the drawn rate standing still, against the display's 60 Hz (headless)
@@ -131,7 +131,8 @@ async function runOne(browser, engineName, layout, slug, site, socket) {
131
131
  const drawn = await page.evaluate(() => /** @type {any} */ (window).__netLag.drawn.slice()), to = await report();
132
132
  // what this phase's corrections disagreed on (position, grounded, board, swim, ride), for the row a miss becomes
133
133
  const missed = Object.fromEntries(Object.entries(to?.missed ?? {}).filter(([key]) => key !== 'gap').map(([key, value]) => [key, value - (/** @type {Record<string, number> | undefined} */ (from?.missed)?.[key] ?? 0)]).filter(([, value]) => value !== 0));
134
- return { name, corrections: (to?.corrections ?? 0) - (from?.corrections ?? 0), missed, frames: drawn.length, p50: at(drawn, 0.5), p99: at(drawn, 0.99), max: at(drawn, 1), over2x: drawn.filter((/** @type {number} */ ms) => ms > 2 * row.budgetMs).length, over50: drawn.filter((/** @type {number} */ ms) => ms > 50).length };
134
+ const authoritative = Object.fromEntries(Object.entries(to?.authoritative ?? {}).map(([key, value]) => [key, value - (/** @type {Record<string, number> | undefined} */ (from?.authoritative)?.[key] ?? 0)]).filter(([, value]) => value !== 0));
135
+ return { name, corrections: (to?.corrections ?? 0) - (from?.corrections ?? 0), missed, authoritative, frames: drawn.length, p50: at(drawn, 0.5), p99: at(drawn, 0.99), max: at(drawn, 1), over2x: drawn.filter((/** @type {number} */ ms) => ms > 2 * row.budgetMs).length, over50: drawn.filter((/** @type {number} */ ms) => ms > 50).length };
135
136
  };
136
137
  row.walk = await phase('walk', ['KeyW']);
137
138
  row.sprint = await phase('sprint', ['KeyW', 'ShiftLeft']);
@@ -24,7 +24,9 @@ export const read = (path: string): unknown => JSON.parse(readFileSync(path, 'ut
24
24
  export function plan(root = process.cwd()): Plan {
25
25
  const {shards} = read(`${root}/test/pins/shardfiles.json`) as {shards: Head[]};
26
26
  const tests = read(`${root}/test/pins/ring-2-tests.json`) as string[];
27
- if (shards.length !== 28 || new Set(shards.map(row => row.slug)).size !== 28) throw new Error('Ring 2 requires 28 distinct pinned heads');
27
+ // Every pinned head, none twice. The count follows the pins file: a hard 28 turned every night red for days after
28
+ // `8f613824` dropped open-plot-showcase-template (27 heads, 2026-11-13).
29
+ if (shards.length === 0 || new Set(shards.map(row => row.slug)).size !== shards.length) throw new Error('Ring 2 requires distinct pinned heads');
28
30
  if (shards.some(row => !/^[a-z0-9-]+$/u.test(row.slug) || !/^[a-f0-9]{64}$/u.test(row.hash))) throw new Error('Unsafe pinned head');
29
31
  if (tests.length === 0 || new Set(tests).size !== tests.length) throw new Error('Empty or duplicate Ring 2 list');
30
32
  const heads = [...shards].sort((a, b) => a.slug.localeCompare(b.slug));
@@ -51,21 +53,22 @@ export function verdict(expected: Plan, reports: Receipt[], previous?: Verdict,
51
53
  .flatMap(report => report.results ?? []).filter(row => row.slug === head.slug && row.hash === head.hash);
52
54
  for (const phase of phases) {
53
55
  const witnesses = matches.flatMap(row => row.phases ?? []).filter(row => row.name === phase);
54
- const ok = witnesses.length === 1 && witnesses[0].ok;
56
+ const [only] = witnesses, ok = witnesses.length === 1 && only !== undefined && only.ok;
55
57
  const key = `${browser}/${head.slug}@${head.hash}/${phase}`;
56
- const error = witnesses.length === 1 ? witnesses[0].error ?? 'phase did not pass' : `Expected one receipt, got ${witnesses.length}`;
58
+ const error = witnesses.length === 1 ? only?.error ?? 'phase did not pass' : `Expected one receipt, got ${witnesses.length}`;
57
59
  rows.push({browser, slug: head.slug, hash: head.hash, phase, ok, ...(ok ? {} : {error})});
58
60
  if (!ok) failures.push({key, error});
59
61
  }
60
62
  }
61
63
  const suites = reports.filter((row): row is TestsReport => row.version === expected.version && row.kind === 'tests' && row.sha === expected.sha && row.pins === expected.pins && row.testList === expected.testList);
62
- if (suites.length !== 1) failures.push({key: 'shared/tests', error: `Expected one suite, got ${suites.length}`});
64
+ const [suite] = suites;
65
+ if (suites.length !== 1 || suite === undefined) failures.push({key: 'shared/tests', error: `Expected one suite, got ${suites.length}`});
63
66
  else {
64
- const suite = suites[0];
65
67
  if (suite.exitCode !== 0 || suite.kitExitCode !== 0 || suite.totalTests < 1) failures.push({key: 'shared/tests', error: `Vitest exit ${suite.exitCode}, kit exit ${suite.kitExitCode}, ${suite.totalTests} tests`});
66
68
  for (const path of expected.tests) {
67
69
  const executions = suite.files.filter(row => row.path === path);
68
- if (executions.length !== 1 || !executions[0].ok || executions[0].assertions < 1 || executions[0].skipped !== 0) failures.push({key: `shared/${path}`, error: 'Listed test missing, skipped or failed'});
70
+ const [run] = executions;
71
+ if (executions.length !== 1 || run === undefined || !run.ok || run.assertions < 1 || run.skipped !== 0) failures.push({key: `shared/${path}`, error: 'Listed test missing, skipped or failed'});
69
72
  }
70
73
  for (const file of suite.files.filter(row => !row.ok)) {
71
74
  if (!failures.some(row => row.key === `shared/${file.path}`)) failures.push({key: `shared/${file.path}`, error: 'Suite failure outside the slow-test list'});
@@ -37,6 +37,7 @@
37
37
  //
38
38
  // scripts/browser-lane.sh node scripts/offline-proof.mjs [--channel=staging|preview|both] [--mode=offline|slow|nobackend]
39
39
  // [--shard=<slug>[,<slug>]] [--entry=deck|resume|both] [--jobs=<n>] [--base=<served build>] [--out=<dir>] [--require-world] [--staging-port=<n>] [--one-origin] [--cells=<n>] [--cold] [--report]
40
+ // --real (OF18): with --base=https://staging.wildshard.io, the staging channel loads that site itself; never prod.
40
41
  // scripts/browser-lane.sh node scripts/offline-proof.mjs --walkthrough <slug> [--base=…] [--out=…] [--report]
41
42
  // With no `--base` it builds this working tree with scripts/serve-build.sh and stops that server at the end. `--jobs` above 1
42
43
  // gives each shard its own profile (one profile can't hold two browsers), which trades the shared-device shape for time.
@@ -82,6 +83,10 @@ const report = argv.includes('--report');
82
83
  const cold = argv.includes('--cold');
83
84
  /** OF12: both channels on one origin and one profile (see above). */
84
85
  const oneOrigin = argv.includes('--one-origin');
86
+ /** OF18 `--real`: the staging channel is the `--base` site itself (real staging's own documents, world stamp, release file and packs),
87
+ * never the stamping proxy, whose 127.0.0.1 origin real staging's packs refuse (no CORS). The world door is still the stand-in. */
88
+ const real = argv.includes('--real');
89
+ if (real && (option('base') === undefined || oneOrigin)) throw new Error('--real needs --base=<the staging site> and no --one-origin');
85
90
  if (oneOrigin && (jobs !== 1 || walkthrough !== undefined)) throw new Error('--one-origin runs one profile: --jobs=1, no --walkthrough');
86
91
  const out = resolvePath(ROOT, option('out') ?? join('tmp', 'offline-proof', new Date().toISOString().replaceAll(/[:.]/gu, '-')));
87
92
  mkdirSync(out, { recursive: true });
@@ -115,6 +120,7 @@ if (base === undefined) {
115
120
  process.once('SIGINT', () => { spawnSync('bash', ['scripts/serve-build.sh', 'stop', builtPort], { cwd: ROOT, stdio: 'ignore' }); process.exit(130); });
116
121
  }
117
122
  const upstream = new URL(base);
123
+ if (real && upstream.origin === CHANNELS.production.origin) throw new Error('--real never runs against prod (OF18)');
118
124
  const version = /** @type {{ build: string }} */ (await (await fetch(new URL('/version.json', upstream))).json());
119
125
  log('build', version.build, 'at', upstream.origin);
120
126
 
@@ -187,7 +193,7 @@ await new Promise((resolve, reject) => { stamper.once('error', reject); stamper.
187
193
  const stamperAddress = stamper.address();
188
194
  if (stamperAddress === null || typeof stamperAddress === 'string') throw new Error('offline-proof: the stamping server has no port');
189
195
  /** @type {Record<Channel, string>} */
190
- const ORIGINS = { preview: oneOrigin ? `http://127.0.0.1:${String(stamperAddress.port)}` : upstream.origin, staging: `http://127.0.0.1:${String(stamperAddress.port)}` };
196
+ const ORIGINS = { preview: oneOrigin ? `http://127.0.0.1:${String(stamperAddress.port)}` : upstream.origin, staging: real ? upstream.origin : `http://127.0.0.1:${String(stamperAddress.port)}` };
191
197
  STAMP = `globalThis.__WS_WORLD__=${JSON.stringify({ release: `${ORIGINS.staging}${RELEASE_PATH}`, key: RELEASE_PUBLIC_KEY })};`;
192
198
 
193
199
  /** A free loopback port for a browser's own DevTools endpoint. */
@@ -48,9 +48,11 @@ export async function intoWorld(page) {
48
48
  * `more` are other shards the release names, `cells` the server's `WORLD_CELLS` (default `shard`), and `socket` the address the
49
49
  * release names when a proof puts its own front door before the server (grid-gate-proof.mjs). `crossing` (on by default, GC35 / J322; false sets
50
50
  * `WORLD_CROSSING=off`, a bench's lone cells) is `WORLD_CROSSING=worker` (GC15): each worker hosts the road between its cells from the grid pack the bake left in this checkout (grid-crossing-walk-proof.mjs),
51
- * and `workers` sets `WORLD_WORKERS` (the rig's release is production's, 4 by default; staging runs 2).
52
- * @param {{ dist: string, nextDist?: string, work: string, keyFile: string, pgBin: string, pgData: string, shard?: string, seats?: number, more?: string[], cells?: string, socket?: string, crossing?: boolean, workers?: number }} options */
53
- export async function openRig({ dist, nextDist = '', work, keyFile, pgBin, pgData, shard = 'driftwood-isle', seats, more = [], cells = shard, socket = `ws://127.0.0.1:${String(WORLD_PORT)}/`, crossing = true, workers }) {
51
+ * and `workers` sets `WORLD_WORKERS` (the rig's release is production's, 4 by default; staging runs 2). FM3: `origins` are page origins the
52
+ * server also lets in (a loopback proxy before the page server, failmode-proof.mjs), and `channel` the release file's channel (`production`).
53
+ * @param {{ dist: string, nextDist?: string, work: string, keyFile: string, pgBin: string, pgData: string, shard?: string, seats?: number, more?: string[], cells?: string, socket?: string, crossing?: boolean, workers?: number, origins?: string[], channel?: string }} options */
54
+ export async function openRig({ dist, nextDist = '', work, keyFile, pgBin, pgData, shard = 'driftwood-isle', seats, more = [], cells = shard, socket = `ws://127.0.0.1:${String(WORLD_PORT)}/`, crossing = true, workers, origins = [], channel = 'production' }) {
55
+ if (origins.some(origin => new URL(origin).origin !== origin || new URL(origin).hostname !== '127.0.0.1')) throw new Error('A rig lets in loopback page origins only');
54
56
  const memory = pgBin === 'memory:';
55
57
  const key = JSON.parse(readFileSync(keyFile, 'utf8')), build = buildOf(dist), nextBuild = nextDist === '' ? '' : buildOf(nextDist), DATABASE = memory ? 'memory:' : database('saves_online');
56
58
  mkdirSync(work, { recursive: true });
@@ -62,9 +64,9 @@ export async function openRig({ dist, nextDist = '', work, keyFile, pgBin, pgDat
62
64
  run(['scripts/build-server.mjs', '--build', build, '--out', server], 'the server build');
63
65
 
64
66
  let signed = '';
65
- /** @param {number} serial @param {string} engineBuild */
66
- const publish = (serial, engineBuild) => {
67
- const body = JSON.stringify({ channel: 'production', serial, engineBuild, saveEpoch: 1, shards: slugs.map(slug => ({ slug, revision: 1 })), socket });
67
+ /** @param {number} serial @param {string} engineBuild @param {string} [signedChannel] */
68
+ const publish = (serial, engineBuild, signedChannel = channel) => {
69
+ const body = JSON.stringify({ channel: signedChannel, serial, engineBuild, saveEpoch: 1, shards: slugs.map(slug => ({ slug, revision: 1 })), socket });
68
70
  signed = JSON.stringify({ body, signature: sign(null, Buffer.from(body), key.private).toString('hex') });
69
71
  };
70
72
  publish(1, build);
@@ -81,7 +83,7 @@ export async function openRig({ dist, nextDist = '', work, keyFile, pgBin, pgDat
81
83
 
82
84
  const world = (running = build) => {
83
85
  const room = spawn(process.execPath, [join(server, 'main.mjs')], { cwd: ROOT, stdio: ['ignore', 'pipe', 'pipe'],
84
- env: { ...process.env, RELEASE_URL: `http://127.0.0.1:${String(RELEASE_PORT)}/release.json`, RELEASE_PUBLIC_KEY: key.public, PACK_ORIGIN: `file://${origin}/`, PACK_CACHE: join(work, 'packs'), DATABASE_URL: DATABASE, SEAT_SECRET: 'online-proof', HOST: '127.0.0.1', PORT: String(WORLD_PORT), ALLOWED_ORIGINS: `http://127.0.0.1:${String(PAGE_PORT)}`, WILDSHARD_BUILD: running, WORLD_CELLS: cells, RELEASE_POLL_MS: '500', GRACE_MS: '6000', ...seats === undefined ? {} : { WORLD_SEATS: String(seats) }, WORLD_CROSSING: crossing ? 'worker' : 'off', ...workers === undefined ? {} : { WORLD_WORKERS: String(workers) } } });
86
+ env: { ...process.env, RELEASE_URL: `http://127.0.0.1:${String(RELEASE_PORT)}/release.json`, RELEASE_PUBLIC_KEY: key.public, PACK_ORIGIN: `file://${origin}/`, PACK_CACHE: join(work, 'packs'), DATABASE_URL: DATABASE, SEAT_SECRET: 'online-proof', HOST: '127.0.0.1', PORT: String(WORLD_PORT), ALLOWED_ORIGINS: [`http://127.0.0.1:${String(PAGE_PORT)}`, ...origins].join(','), WILDSHARD_BUILD: running, WORLD_CELLS: cells, RELEASE_POLL_MS: '500', GRACE_MS: '6000', ...seats === undefined ? {} : { WORLD_SEATS: String(seats) }, WORLD_CROSSING: crossing ? 'worker' : 'off', ...workers === undefined ? {} : { WORLD_WORKERS: String(workers) } } });
85
87
  room.stdout.pipe(log, { end: false }); room.stderr.pipe(log, { end: false });
86
88
  return room;
87
89
  };
@@ -12,7 +12,7 @@ import { captureBootFrame } from './black-frame.mjs';
12
12
  import { observeTitleCapture } from './title-trace.mjs';
13
13
  import { gridBootWaitHistory } from './grid-boot-waits.mjs';
14
14
  import { gridFloorDocumentIdentity, runFloorGridRoute, gridFloorWitnessFailures } from '../frame-floor-grid.mjs';
15
- import { finishStallProfile, startStallProfile } from '../loading-flow/stalls.mjs';
15
+ import { finishPlayProfile, finishStallProfile, startStallProfile } from '../loading-flow/stalls.mjs';
16
16
 
17
17
  /** A locked experimental card is not a public gameplay entry. Its direct chunk
18
18
  * page must still hydrate under the unwaived public playing envelope (call44).
@@ -530,14 +530,25 @@ export async function bootCase(browser, base, mode, out, shard = 'driftwood-isle
530
530
  const overhead = await page.evaluate(spawnOverhead);
531
531
  if (overhead !== null) throw new Error(`grid spawn is under a collider: ${JSON.stringify(overhead)}`);
532
532
  }
533
+ // NINE-DRAGON-BENCHMAX NB6 (play): the ten gameplay frames are profiled too, and a stretch in which the main thread
534
+ // worked without a break (a 2 s busy sleep in a frame) is refused, whatever the GPU (scripts/loading-flow/stalls.mjs)
535
+ const playProfile = await startStallProfile(page), playFrom = Number(await page.evaluate('performance.now()'));
533
536
  await until(page, faults, async () => (await page.evaluate(bootObservation)).frame >= initial.frame + 10, 'ten live gameplay frames', deadline);
534
537
  gameplayFrames.final = (await page.evaluate(bootObservation)).frame;
538
+ /** @type {{ from: number, busyMs: number, playMs: number, leaves: string[] } | null} */ let playStall = null;
539
+ // report only in Ring 1 (2026-11-14): on CI's SwiftShader (frames 1-2.4 s apart) two lands' play windows read 1.5 s busy
540
+ // in script with no sleep (sunscar-dunes, blender-template), so the line names the window's leaves and Ring 1 stays
541
+ // green; desktop enforces it through `deskbench --capped --stalls`, and the props stall above still fails Ring 1
542
+ if (playProfile !== null) {
543
+ const read = await finishPlayProfile(page, playProfile, playFrom); playStall = { ...read.stall, leaves: read.leaves };
544
+ if (read.faults.length > 0) console.log(`${shard}: play stall (report only): ${read.faults.join('; ')} · ${read.leaves.join(', ')}`);
545
+ }
535
546
  phases.framesCompleteMs = Date.now() - started;
536
547
  await captureBootFrame(page, mode === 'grid' ? 'grid HOME' : `${shard} gameplay`, deadline, frames);
537
548
  const roadDeadline = Date.now() + 90000;
538
549
  const templateRoad = mode === 'grid' ? await bootTemplateRoad(page, faults, frames, roadDeadline) : null;
539
550
  const road = mode === 'grid' ? await bootSignalRoad(page, faults, frames, roadDeadline) : null;
540
- const result = { mode, phases, frames, gameplayFrames, stalls, gridWaits: gridWaits.samples, templateRoad, road, telemetryPosts, lifecycleReports, gridNavigationObserved, elapsedMs: Date.now() - started, ...await page.evaluate(bootObservation), faults, reports };
551
+ const result = { mode, phases, frames, gameplayFrames, stalls, playStall, gridWaits: gridWaits.samples, templateRoad, road, telemetryPosts, lifecycleReports, gridNavigationObserved, elapsedMs: Date.now() - started, ...await page.evaluate(bootObservation), faults, reports };
541
552
  if (faults.length > 0 || result.fatal.length > 0) throw new Error(JSON.stringify(result));
542
553
  if (afterGameplay !== null) await afterGameplay(page);
543
554
  if (faults.length > 0) throw new Error(JSON.stringify(faults));