@wildshard/engine 0.1.23 → 0.1.24

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 (99) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/index.html +17 -4
  3. package/lint/engine-sides.json +7 -0
  4. package/package.json +29 -3
  5. package/scripts/app-build/titlePreloads.mjs +8 -5
  6. package/scripts/bake-road-surfaces.entry.ts +18 -0
  7. package/scripts/bake-road-surfaces.mjs +44 -0
  8. package/scripts/changelog.mjs +2 -1
  9. package/scripts/goldens/capture.mjs +18 -6
  10. package/scripts/goldens/native-residency.d.mts +1 -0
  11. package/scripts/goldens/native-residency.mjs +14 -1
  12. package/scripts/grid-road-lag.mjs +209 -0
  13. package/scripts/keep-copy.mjs +64 -12
  14. package/scripts/land.d.mts +4 -1
  15. package/scripts/land.mjs +85 -3
  16. package/scripts/loading-flow/benchmax.mjs +2 -0
  17. package/scripts/map-hash.mjs +1 -1
  18. package/scripts/nightly-tag.mjs +2 -4
  19. package/scripts/page-release/content.mjs +19 -10
  20. package/scripts/page-release/flow.d.mts +3 -2
  21. package/scripts/page-release/flow.mjs +31 -21
  22. package/scripts/page-release/packs.d.mts +5 -0
  23. package/scripts/page-release/packs.mjs +13 -3
  24. package/scripts/page-release/preview.d.mts +2 -0
  25. package/scripts/page-release/preview.mjs +74 -0
  26. package/scripts/page-release.mjs +13 -5
  27. package/scripts/road-drive-proof.mjs +269 -0
  28. package/scripts/road-memory-probe.mjs +129 -0
  29. package/scripts/scratch-dir.mjs +4 -4
  30. package/scripts/server-release/github.mjs +59 -26
  31. package/scripts/server-release/publish.mjs +15 -1
  32. package/scripts/server-release/sign.mjs +8 -4
  33. package/scripts/test_prebuilt_output.py +3 -1
  34. package/scripts/turn-in-shots.mjs +83 -0
  35. package/scripts/vitest-bench-observe-proof.py +168 -0
  36. package/scripts/vitest-bench.py +122 -77
  37. package/scripts/vps/rebuild.sh +3 -1
  38. package/scripts/worktree-reap.mjs +21 -9
  39. package/scripts/worktree.mjs +1 -1
  40. package/scripts/zone-gate-proof.mjs +93 -0
  41. package/src/client/engine/boot/sw.ts +3 -1
  42. package/src/client/engine/core/ktx2.ts +30 -9
  43. package/src/client/engine/models/place.ts +7 -5
  44. package/src/client/engine/pwa/sw.js +57 -2
  45. package/src/client/engine/render/precompile.ts +6 -0
  46. package/src/client/engine/render/tiers.ts +9 -0
  47. package/src/client/engine/ui/playerReload.ts +5 -5
  48. package/src/client/game/boot/bytes.generated.ts +4 -1
  49. package/src/client/game/boot/versions.generated.ts +8 -5
  50. package/src/client/game/grid/cellClip.ts +70 -6
  51. package/src/client/game/grid/gateCard.css +9 -0
  52. package/src/client/game/grid/gateCard.ts +67 -0
  53. package/src/client/game/grid/live.ts +17 -3
  54. package/src/client/game/grid/liveSession.ts +15 -5
  55. package/src/client/game/grid/neighbourLife.ts +10 -1
  56. package/src/client/game/grid/neighbourPanels.ts +29 -2
  57. package/src/client/game/grid/pageEntry.ts +21 -0
  58. package/src/client/game/grid/regionalWorld.ts +5 -0
  59. package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
  60. package/src/client/game/grid/roadLook.ts +5 -73
  61. package/src/client/game/grid/roadLookPlatform.ts +11 -6
  62. package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
  63. package/src/client/game/grid/roadTilePool.ts +4 -0
  64. package/src/client/game/grid/session.ts +52 -12
  65. package/src/client/game/grid/softWallLook.ts +6 -1
  66. package/src/client/game/plugin/ui.ts +3 -0
  67. package/src/client/game/session/play.ts +3 -0
  68. package/src/client/game/shardfile/clientSource.ts +5 -2
  69. package/src/client/game/shardfile/clientWorker.ts +3 -2
  70. package/src/client/game/shardfile/slabLibrary.ts +37 -0
  71. package/src/client/game/shardfile/slabRanges.ts +145 -0
  72. package/src/client/host/online/shell.ts +2 -2
  73. package/src/client/host/standalone/shell.ts +4 -1
  74. package/src/server/game/grid/simulation.ts +27 -4
  75. package/src/server/game/plugin/simulation.ts +2 -0
  76. package/src/server/game/shardfile/dataRespawn.ts +47 -0
  77. package/src/server/host/standalone/cellWorld.ts +1 -1
  78. package/src/server/host/standalone/gridServer.ts +18 -6
  79. package/src/server/host/standalone/roadWorld.ts +30 -0
  80. package/src/server/host/standalone/serverHost.ts +2 -2
  81. package/src/shared/engine/entities/AnimalSim.ts +10 -0
  82. package/src/shared/engine/physics/transferWalls.ts +9 -4
  83. package/src/shared/game/grid/allocator.ts +8 -1
  84. package/src/shared/game/grid/gateCount.ts +27 -0
  85. package/src/shared/game/grid/zoneWalls.ts +64 -0
  86. package/src/shared/game/strings.ts +2 -0
  87. package/src/shared/host/standalone/harnessPlace.ts +4 -0
  88. package/src/test/engine/simState.ts +134 -0
  89. package/src/test/game/builtProduct.ts +6 -0
  90. package/src/test/game/headless/admittedProductCache.ts +61 -0
  91. package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
  92. package/src/test/game/headless/nativeBounds.ts +27 -0
  93. package/src/test/game/headless/processUsage.ts +22 -0
  94. package/src/test/game/headless/productSession.ts +39 -0
  95. package/src/test/game/headless/ropeBodies.ts +60 -0
  96. package/src/test/game/headless/worker.ts +34 -0
  97. package/src/test/game/headlessNative.ts +114 -0
  98. package/src/test/game/headlessWorker.ts +43 -0
  99. package/src/test/tsconfig.game.json +3 -0
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env node
2
+ // ZONE-ENTRY ZE3 (Jake, 2026-11-15: "drive around on the road absolutely everywhere, pass all kinds of cells, and then come
3
+ // back. Come back to the one"): from a home cell entered by Shard Select, step out of its east entryway by real input and drive
4
+ // the whole road with the run key held: every segment of the grid's junction lattice (every row, then every column, the outer
5
+ // ring included), past every other cell, then back to the home's east entryway and into the home. Per segment it reads the road
6
+ // bar (meta docs/plans/ZONE-ENTRY-PLAN.md): every frame's time, the longest stretch under 90 % of the segment's own speed with
7
+ // the key held, any loading card on screen, `playingMB`, and whether the home stayed resident; then the walk back in.
8
+ // scripts/browser-lane.sh node scripts/road-drive-proof.mjs --base=<preview or loopback url> --out=<dir> [--home=driftwood]
9
+ // [--engine=chromium|webkit] [--device='iPhone 15 Pro'] [--viewport=2992x1434@2] [--segments=n] (the first n only, a short check)
10
+ // [--ride=board|boost|run] (default board: the hoverboard, 30 m/s on the road, J354; boost 120 m/s; run: on foot with the run key)
11
+ // [--from=k] (start measuring at segment k: the board drives the shortest junction path there first, unmeasured; a repro of one
12
+ // segment's frame, not the proof)
13
+ // The steering runs in the page (a 50 ms yaw toward the next waypoint); the keys are real. The walker is placed 20 m inside the
14
+ // home's east entryway by the in-page harness pose, so it runs on preview or a loopback page only. Never production (J205).
15
+ import { mkdirSync, writeFileSync } from 'node:fs';
16
+ import { join, resolve as absolute } from 'node:path';
17
+ import { chromium, devices, webkit } from 'playwright';
18
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
19
+ import { saveFixture } from './debug-settings.mjs';
20
+
21
+ /** @param {string} name @param {string} fallback */
22
+ const flag = (name, fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
23
+ const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', '')), engineName = flag('engine', 'chromium'), device = flag('device', '');
24
+ const limit = Number(flag('segments', '0')) || Infinity, ride = flag('ride', 'board'), from = Number(flag('from', '0'));
25
+ if (!['board', 'boost', 'run'].includes(ride)) throw new Error(`No ride ${ride}: board, boost or run`);
26
+ if (!/^https:\/\/preview\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: road-drive-proof.mjs --base=<preview or loopback url> --out=<dir> [--home=driftwood] [--segments=n]');
27
+ const HOMES = /** @type {Record<string, { slug: string, card: string }>} */ ({ driftwood: { slug: 'driftwood-isle', card: 'Driftwood Isle' }, sunscar: { slug: 'sunscar-dunes', card: 'Signal Dunes' }, pine: { slug: 'pine-hollow', card: 'Pine Hollow' } });
28
+ const homeName = flag('home', 'driftwood'), home = HOMES[homeName];
29
+ if (home === undefined) throw new Error(`No home ${homeName}: ${Object.keys(HOMES).join(', ')}`);
30
+ const desk = (/^(\d+)x(\d+)@([\d.]+)$/u.exec(flag('viewport', '2992x1434@2')) ?? [0, '2992', '1434', '2']).slice(1).map(Number);
31
+ const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
32
+ /** The cell's half size, the gap's half (road and both strips) and the junction offsets a drive keeps off the roundabout's island (6 m). */
33
+ const HALF = 250, GAP_HALF = 31.25, LANE = 4, AROUND = 10, CLEAR = 20, MEASURE_CLEAR = 30;
34
+ /** ZE3a: the page keeps its home resident while the feet are within this many metres of its edge (`liveSession.ts`
35
+ * HOME_KEEP_METRES 300), less a 20 m margin for the 50 ms sample's stride. */
36
+ const KEEP_M = 280;
37
+ /** The longest ramp back to cruise out of a corner the bar accepts: the board's own 90° turn takes about 0.8 s, a longer one is a stop. */
38
+ const RAMP_MS = 1500;
39
+ mkdirSync(out, { recursive: true });
40
+
41
+ /** The junction path: from the home's south-east junction to the lattice's corner, every row (a snake), every column (a snake),
42
+ * then back to the home's south-east junction. Each step is one segment. @param {number} n junction lines @param {number} si @param {number} sj */
43
+ function junctionPath(n, si, sj) {
44
+ /** @type {[number, number][]} */
45
+ const path = [[si, sj]];
46
+ const go = (/** @type {number} */ i, /** @type {number} */ j) => {
47
+ let [ci, cj] = /** @type {[number, number]} */ (path.at(-1));
48
+ while (ci !== i) { ci += Math.sign(i - ci); path.push([ci, cj]); }
49
+ while (cj !== j) { cj += Math.sign(j - cj); path.push([ci, cj]); }
50
+ };
51
+ const goJ = (/** @type {number} */ i, /** @type {number} */ j) => { let [ci, cj] = /** @type {[number, number]} */ (path.at(-1)); while (cj !== j) { cj += Math.sign(j - cj); path.push([ci, cj]); } while (ci !== i) { ci += Math.sign(i - ci); path.push([ci, cj]); } };
52
+ goJ(0, 0);
53
+ for (let j = 0; j < n; j++) { go(j % 2 === 0 ? n - 1 : 0, j); if (j < n - 1) go(/** @type {[number, number]} */ (path.at(-1))[0], j + 1); }
54
+ for (let i = 0; i < n; i++) { const [ci] = /** @type {[number, number]} */ (path.at(-1)); if (ci !== i) go(i, /** @type {[number, number]} */ (path.at(-1))[1]); goJ(i, i % 2 === 0 ? 0 : n - 1); }
55
+ go(si, /** @type {[number, number]} */ (path.at(-1))[1]); goJ(si, sj);
56
+ return path;
57
+ }
58
+
59
+ const result = { base, home: home.slug, engine: engineName, ride, viewport: `${String(desk[0])}x${String(desk[1])}@${String(desk[2])}`, at: new Date().toISOString(), build: '',
60
+ segments: /** @type {Record<string, unknown>[]} */ ([]), back: /** @type {Record<string, unknown> | null} */ (null), summary: /** @type {Record<string, unknown> | null} */ (null), errors: /** @type {string[]} */ ([]), note: '' };
61
+ const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
62
+ const tag = `${engineName}${device === '' ? '' : '-phone'}-${homeName}`;
63
+ let code = 1;
64
+ try {
65
+ result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
66
+ const phone = device === '' ? undefined : devices[device];
67
+ if (device !== '' && phone === undefined) throw new Error(`No Playwright device ${device}`);
68
+ if (phone !== undefined) result.viewport = `${device} ${String(phone.viewport.width)}x${String(phone.viewport.height)}@${String(phone.deviceScaleFactor)}`;
69
+ const context = await browser.newContext(phone ?? { viewport: { width: desk[0] ?? 2992, height: desk[1] ?? 1434 }, deviceScaleFactor: desk[2] ?? 2 }), page = await context.newPage();
70
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
71
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
72
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
73
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { volume: 0 } });
74
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
75
+ await page.locator('.ws-main-select').click({ timeout: 120_000 });
76
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('roaddrive'); await page.locator('#ws-name-box button[type=submit]').click(); }
77
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
78
+ const index = await page.evaluate(card => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes(card)), home.card);
79
+ if (index < 0) throw new Error(`No ${home.card} card`);
80
+ await page.locator('.ws-menu-dots i').nth(index).click();
81
+ await page.locator('.ws-menu-play').click();
82
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
83
+ await sleep(2000);
84
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
85
+ // the lattice: junction lines halfway between cells, from the cells the page knows
86
+ const grid = await page.evaluate(slug => {
87
+ const W = /** @type {any} */ (window), st = W.__wildshard.shard.grid.state(), wf = st.live.live.worldFeet, p = W.__wildshard.world.player.position;
88
+ const cells = /** @type {{ slug: string, cell: [number, number] }[]} */ (st.cells), own = cells.find(row => row.slug === slug);
89
+ return { origin: { x: wf.x - p.x, z: wf.z - p.z }, cell: own?.cell ?? null, is: cells.map(row => row.cell[0]), js: cells.map(row => row.cell[1]) };
90
+ }, home.slug);
91
+ if (grid.cell === null) throw new Error(`${home.slug} is not on the grid`);
92
+ const pitch = grid.cell[0] === 0 ? (grid.cell[1] === 0 ? 562.5 : grid.origin.z / grid.cell[1]) : grid.origin.x / grid.cell[0];
93
+ const lo = Math.min(...grid.is, ...grid.js), hi = Math.max(...grid.is, ...grid.js), lines = Array.from({ length: hi - lo + 2 }, (_, k) => (lo + k - 0.5) * pitch);
94
+ const at = (/** @type {number} */ v) => lines.findIndex(line => Math.abs(line - v) < 1);
95
+ const si = at(grid.origin.x + HALF + GAP_HALF), sj = at(grid.origin.z - HALF - GAP_HALF);
96
+ if (si < 0 || sj < 0) throw new Error('The home has no south-east junction on the lattice');
97
+ const path = junctionPath(lines.length, si, sj), centre = (lines[0] + /** @type {number} */ (lines.at(-1))) / 2;
98
+ // each segment's straight: LANE m to the grid-centre side of its line, CLEAR m off each junction; at a junction, one point AROUND
99
+ // m off its centre toward the way out (or toward the lane on a straight pass), clear of the island
100
+ /** @type {{ x: number, z: number, seg: number }[]} */
101
+ const waypoints = [];
102
+ const legs = Math.min(path.length - 1, from + limit);
103
+ // --from: a lead-in, the junction path from the home's south-east junction to segment `from`'s start, driven unmeasured (seg -5)
104
+ /** @type {[number, number][]} */
105
+ const lead = [];
106
+ if (from > 0) {
107
+ let [ci, cj] = [si, sj];
108
+ const [ti, tj] = path[from];
109
+ while (ci !== ti || cj !== tj) { lead.push([ci, cj]); if (ci !== ti) ci += Math.sign(ti - ci); else cj += Math.sign(tj - cj); }
110
+ }
111
+ const run = [...lead, ...path.slice(from, legs + 1)], segOf = (/** @type {number} */ r) => r < lead.length ? -5 : from + r - lead.length;
112
+ for (let r = 0; r < run.length - 1; r++) {
113
+ const [ai, aj] = run[r], [bi, bj] = run[r + 1];
114
+ const a = { x: lines[ai] ?? 0, z: lines[aj] ?? 0 }, b = { x: lines[bi] ?? 0, z: lines[bj] ?? 0 }, d = { x: Math.sign(b.x - a.x), z: Math.sign(b.z - a.z) };
115
+ const n = d.x !== 0 ? { x: 0, z: Math.sign(centre - a.z) || 1 } : { x: Math.sign(centre - a.x) || 1, z: 0 };
116
+ waypoints.push({ x: a.x + d.x * CLEAR + n.x * LANE, z: a.z + d.z * CLEAR + n.z * LANE, seg: segOf(r) }, { x: b.x - d.x * CLEAR + n.x * LANE, z: b.z - d.z * CLEAR + n.z * LANE, seg: segOf(r) });
117
+ const next = run[r + 2];
118
+ if (next !== undefined) {
119
+ const e = { x: Math.sign((lines[next[0]] ?? 0) - b.x), z: Math.sign((lines[next[1]] ?? 0) - b.z) }, straight = e.x === d.x && e.z === d.z;
120
+ waypoints.push({ x: b.x + (straight ? n.x : e.x) * AROUND, z: b.z + (straight ? n.z : e.z) * AROUND, seg: -1 });
121
+ }
122
+ }
123
+ // out of the home's east entryway onto its east road, then down to the first segment's start
124
+ const exitAt = { x: grid.origin.x + HALF + GAP_HALF - LANE, z: grid.origin.z };
125
+ await page.evaluate(([px, pz]) => { const p = /** @type {any} */ (window).__wildshard.world.player; p.spawn(px, pz, p.yaw, 1.5); p.link?.place?.(p.position.x, p.position.y, p.position.z, p.yaw); }, [HALF - 20, 0]);
126
+ await sleep(4000);
127
+ const route = [{ ...exitAt, seg: -2 }, ...waypoints];
128
+ // the board and its boost through the player's own toggles (what H and a double tap of H call)
129
+ if (ride !== 'run') {
130
+ await page.evaluate(boost => { const p = /** @type {any} */ (window).__wildshard.world.player; if (!p.hover) p.setHover(true); p.setBoost?.(boost); }, ride === 'boost');
131
+ await sleep(800);
132
+ if (!(await page.evaluate(() => /** @type {any} */ (window).__wildshard.world.player.hover === true))) throw new Error('The board did not take');
133
+ }
134
+ await page.evaluate(({ wps, homeSlug }) => {
135
+ const W = /** @type {any} */ (window), q = W.__drive = { frames: /** @type {number[][]} */ ([]), samples: /** @type {any[]} */ ([]), at: 0, done: false, wps,
136
+ programs: /** @type {any[]} */ ([]), slowLinks: /** @type {any[]} */ ([]), loafs: /** @type {any[]} */ ([]) };
137
+ // what a long frame did: the programs it linked, a link the driver finished only when asked, and (Chromium) the long
138
+ // animation frame's own scripts
139
+ const renderer = W.__wildshard?.world?.game?.renderer, gl = renderer?.getContext?.(), known = new Set(renderer?.info?.programs);
140
+ if (gl !== undefined) {
141
+ const ask = gl.getProgramParameter.bind(gl);
142
+ gl.getProgramParameter = (/** @type {WebGLProgram} */ handle, /** @type {number} */ name) => {
143
+ const t0 = performance.now(), value = ask(handle, name), ms = performance.now() - t0;
144
+ if (ms > 8) {
145
+ const found = (renderer.info.programs ?? []).find((/** @type {any} */ row) => row.program === handle), row = { t: Math.round(t0), ms: Math.round(ms), name: String(found?.name ?? ''), key: String(found?.cacheKey ?? '').slice(-40), owners: /** @type {string[]} */ ([]) };
146
+ q.slowLinks.push(row);
147
+ // who drew it: the first few objects whose material now holds this program, by their ancestors' names
148
+ setTimeout(() => { try {
149
+ const seen = new Set();
150
+ W.__wildshard.world.game.scene.traverse((/** @type {any} */ o) => {
151
+ if (row.owners.length >= 4 || o.material === undefined) return;
152
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
153
+ if (renderer.properties.get(m)?.currentProgram?.program !== handle) continue;
154
+ const names = []; for (let node = o; node !== null && node !== undefined && names.length < 6; node = node.parent) names.push(String(node.name === '' ? node.type : node.name));
155
+ const label = `${names.join('<')} [${String(m.name === '' ? m.type : m.name)}]`;
156
+ if (!seen.has(label)) { seen.add(label); row.owners.push(label.slice(0, 220)); }
157
+ }
158
+ });
159
+ } catch (error) { row.owners.push(String(error).slice(0, 120)); } }, 0);
160
+ }
161
+ return value;
162
+ };
163
+ }
164
+ try { new PerformanceObserver(list => { for (const e of /** @type {any[]} */ (list.getEntries())) if (e.duration > 50) q.loafs.push({ t: Math.round(e.startTime), ms: Math.round(e.duration), block: Math.round(e.blockingDuration ?? 0), render: Math.round((e.startTime + e.duration) - (e.renderStart > 0 ? e.renderStart : e.startTime + e.duration)),
165
+ scripts: (e.scripts ?? []).filter((/** @type {any} */ x) => x.duration > 5).map((/** @type {any} */ x) => ({ ms: Math.round(x.duration), fn: String(x.sourceFunctionName ?? ''), src: `${String(x.sourceURL ?? '').split('/').at(-1) ?? ''}:${String(x.sourceCharPosition ?? '')}`, inv: String(x.invoker ?? '').slice(0, 80) })) }); }).observe({ type: 'long-animation-frame', buffered: false }); } catch { /* WebKit has none */ }
166
+ let last = performance.now();
167
+ const raf = (/** @type {number} */ now) => { q.frames.push([Math.round(now), Number((now - last).toFixed(1))]); last = now; requestAnimationFrame(raf); };
168
+ requestAnimationFrame(raf);
169
+ setInterval(() => { try {
170
+ const st = W.__wildshard.shard.grid.state(), p = W.__wildshard.world.player, wf = st.live?.live?.worldFeet ?? p.position;
171
+ const wp = q.wps[q.at];
172
+ if (wp !== undefined) {
173
+ // a waypoint counts within a stride of a 50 ms look at the speed held (3 m on foot, more on a board)
174
+ const prev = q.samples.at(-1), reach = prev === undefined || prev.err !== undefined ? 3 : Math.max(3, Math.hypot(wf.x - prev.x, wf.z - prev.z) * 2.5);
175
+ if (Math.hypot(wf.x - wp.x, wf.z - wp.z) < reach) q.at++;
176
+ const to = q.wps[q.at];
177
+ if (to === undefined) q.done = true; else p.yaw = Math.atan2(wf.x - to.x, wf.z - to.z);
178
+ }
179
+ q.samples.push({ t: Math.round(performance.now()), x: Number(wf.x.toFixed(2)), z: Number(wf.z.toFixed(2)), seg: q.wps[q.at]?.seg ?? -3, inside: st.inside, card: st.cellLoading ?? null, stage: st.cellStage ?? null,
180
+ res: st.live?.live?.residents ?? null, home: (st.live?.live?.residents ?? []).includes(homeSlug), mb: st.playingMB ?? null });
181
+ for (const program of renderer?.info?.programs ?? []) if (!known.has(program)) { known.add(program); q.programs.push({ t: Math.round(performance.now()), name: String(program.name ?? ''), key: String(program.cacheKey ?? '').slice(0, 300) }); }
182
+ } catch (error) { q.samples.push({ err: String(error).slice(0, 160) }); } }, 50);
183
+ }, { wps: route, homeSlug: home.slug });
184
+ // --profile (Chromium): the page thread's CPU profile over the measured drive, for a long frame's cause
185
+ const cdp = process.argv.includes('--profile') && engineName === 'chromium' ? await context.newCDPSession(page) : undefined;
186
+ if (cdp !== undefined) { await cdp.send('Profiler.enable'); await cdp.send('Profiler.setSamplingInterval', { interval: 500 }); await cdp.send('Profiler.start'); }
187
+ const profileAt = await page.evaluate(() => performance.now());
188
+ const t0 = Date.now();
189
+ if (ride === 'run') await page.keyboard.down('ShiftLeft');
190
+ await page.keyboard.down('KeyW');
191
+ for (let seen = -1, since = Date.now(); ;) {
192
+ const { reached, done, last } = await page.evaluate(() => { const q = /** @type {any} */ (window).__drive; return { reached: q.at, done: q.done, last: q.samples.at(-1) }; });
193
+ if (done) break;
194
+ if (reached !== seen) { seen = reached; since = Date.now(); if (reached % 12 === 0) console.log(`waypoint ${String(reached)}/${String(route.length)} after ${String(Math.round((Date.now() - t0) / 1000))} s`); }
195
+ // a waypoint not reached in 90 s is a drive stuck on something: say where, and stop
196
+ if (Date.now() - since > 90_000) throw new Error(`stuck before waypoint ${String(reached)} ${JSON.stringify(route[reached])}: last sample ${JSON.stringify(last)}`);
197
+ await sleep(1000);
198
+ }
199
+ await page.keyboard.up('KeyW'); if (ride === 'run') await page.keyboard.up('ShiftLeft');
200
+ if (cdp !== undefined) { const { profile } = await cdp.send('Profiler.stop'); writeFileSync(join(out, `${tag}-drive.cpuprofile.json`), JSON.stringify({ at: profileAt, profile })); }
201
+ const driveMs = Date.now() - t0;
202
+ // per segment: its straight, MEASURE_CLEAR m off each end, read from the samples and the frames between its first and last sample
203
+ const { frames, samples, programs, slowLinks, loafs } = await page.evaluate(() => { const q = /** @type {any} */ (window).__drive; return { frames: q.frames, programs: q.programs, slowLinks: q.slowLinks, loafs: q.loafs, samples: q.samples.filter((/** @type {any} */ r) => r.err === undefined) }; });
204
+ const edgeM = (/** @type {any} */ r) => Math.hypot(Math.max(0, Math.abs(r.x - grid.origin.x) - HALF), Math.max(0, Math.abs(r.z - grid.origin.z) - HALF));
205
+ const firstOut = samples.findIndex((/** @type {any} */ r) => edgeM(r) > KEEP_M);
206
+ // ZE3a: the home stays resident until the feet first pass KEEP_M from its edge (the page's 300 m keep), then may retire
207
+ const allCards = samples.filter((/** @type {any} */ r) => r.card !== null), allHome = samples.slice(0, firstOut === -1 ? samples.length : firstOut).every((/** @type {any} */ r) => r.home === true);
208
+ /** every frame over 50 ms, with what the page did around it (a ±400 ms window) */
209
+ const longFrames = frames.filter((/** @type {number[]} */ r) => (r[1] ?? 0) > 50).map((/** @type {number[]} */ [t, ms]) => {
210
+ const near = (/** @type {any} */ r) => r.t >= t - (ms ?? 0) - 400 && r.t <= t + 400, hit = samples.find(near);
211
+ return { t, ms, seg: hit?.seg ?? null, at: hit === undefined ? null : { x: hit.x, z: hit.z }, res: hit?.res ?? null, mb: hit?.mb ?? null,
212
+ programs: programs.filter(near).map((/** @type {any} */ r) => r.name), slowLinks: slowLinks.filter(near), loafs: loafs.filter(near) };
213
+ });
214
+ for (let k = from; k < legs; k++) {
215
+ const rows = samples.filter((/** @type {any} */ r) => r.seg === k);
216
+ if (rows.length < 3) { result.segments.push({ seg: k, driven: false }); continue; }
217
+ const [ai, aj] = path[k], [bi, bj] = path[k + 1];
218
+ const a = { x: lines[ai] ?? 0, z: lines[aj] ?? 0 }, b = { x: lines[bi] ?? 0, z: lines[bj] ?? 0 }, len = Math.hypot(b.x - a.x, b.z - a.z);
219
+ const along = (/** @type {any} */ r) => ((r.x - a.x) * (b.x - a.x) + (r.z - a.z) * (b.z - a.z)) / len;
220
+ const mid = rows.filter((/** @type {any} */ r) => along(r) >= MEASURE_CLEAR && along(r) <= len - MEASURE_CLEAR);
221
+ const span = mid.length < 2 ? [] : frames.filter((/** @type {number[]} */ r) => (r[0] ?? 0) >= mid[0].t && (r[0] ?? 0) <= mid.at(-1).t).map((/** @type {number[]} */ r) => r[1] ?? 0);
222
+ const speed = (/** @type {number} */ i) => Math.hypot(mid[i].x - mid[i - 1].x, mid[i].z - mid[i - 1].z) / Math.max(1, mid[i].t - mid[i - 1].t);
223
+ const speeds = mid.map((/** @type {unknown} */ _, /** @type {number} */ i) => i > 0 ? speed(i) : Number.NaN).filter((/** @type {number} */ v) => Number.isFinite(v)).sort((/** @type {number} */ x, /** @type {number} */ y) => x - y), cruise = speeds[Math.floor(speeds.length / 2)] ?? 0;
224
+ // out of a turn the board is still gaining speed: a stop counts only once the segment first reaches 90 % of its cruise (the
225
+ // 2026-11-15 laptop drive: every stop over 105 ms was this ramp out of a 90° corner, each frame 16.8 ms)
226
+ let stop = 0, worstStop = 0, stopAt = null, ramp = 1;
227
+ while (ramp < mid.length && speed(ramp) < cruise * 0.9) ramp++;
228
+ const rampMs = ramp < mid.length ? mid[ramp - 1].t - mid[0].t : 0;
229
+ for (let i = ramp + 1; i < mid.length; i++) { stop = speed(i) < cruise * 0.9 ? stop + (mid[i].t - mid[i - 1].t) : 0; if (stop > worstStop) { worstStop = stop; stopAt = { x: mid[i].x, z: mid[i].z }; } }
230
+ const cards = rows.filter((/** @type {any} */ r) => r.card !== null), mbs = rows.map((/** @type {any} */ r) => r.mb).filter((/** @type {unknown} */ v) => typeof v === 'number');
231
+ result.segments.push({ seg: k, driven: true, from: [ai, aj], to: [bi, bj], ms: rows.at(-1).t - rows[0].t, cruiseMps: Number((cruise * 1000).toFixed(2)), worstFrameMs: Math.max(0, ...span),
232
+ over50: span.filter((/** @type {number} */ ms) => ms > 50).length, over100: span.filter((/** @type {number} */ ms) => ms > 100).length, worstStopMs: worstStop, stopAt, rampMs,
233
+ cardMs: cards.length * 50, cards: [...new Set(cards.map((/** @type {any} */ r) => `${String(r.card)}:${String(r.stage)}`))], homeResident: rows.every((/** @type {any} */ r) => r.home === true),
234
+ residents: [...new Set(rows.flatMap((/** @type {any} */ r) => r.res ?? []))], mb: mbs.length === 0 ? null : { min: Math.min(...mbs), max: Math.max(...mbs) },
235
+ programs: programs.filter((/** @type {any} */ r) => r.t >= rows[0].t && r.t <= rows.at(-1).t).length });
236
+ }
237
+ // back to the home's east entryway and in, by input: control with no card (a short --segments check ends away from home)
238
+ const whole = from === 0 && legs === path.length - 1;
239
+ const backFrom = await page.evaluate(() => Math.round(performance.now()));
240
+ await page.evaluate(([wps]) => { const q = /** @type {any} */ (window).__drive; q.wps = wps; q.at = 0; q.done = false; }, [[{ x: grid.origin.x + HALF + GAP_HALF - LANE, z: grid.origin.z, seg: -4 }, { x: grid.origin.x + HALF - 12, z: grid.origin.z, seg: -4 }]]);
241
+ if (whole) {
242
+ await page.keyboard.down('KeyW');
243
+ for (const ends = Date.now() + 120_000; Date.now() < ends;) { if (await page.evaluate(() => /** @type {any} */ (window).__drive.done)) break; await sleep(250); }
244
+ await page.keyboard.up('KeyW');
245
+ await sleep(2500);
246
+ }
247
+ result.back = await page.evaluate(({ after, slug }) => {
248
+ const W = /** @type {any} */ (window), q = W.__drive, rows = q.samples.filter((/** @type {any} */ r) => r.err === undefined && r.t >= after), st = W.__wildshard.shard.grid.state();
249
+ const span = q.frames.filter((/** @type {number[]} */ r) => (r[0] ?? 0) >= after).map((/** @type {number[]} */ r) => r[1] ?? 0);
250
+ return { reached: q.done === true, inside: st.inside === slug, control: st.live?.live?.gameplayReady === true, cardMs: rows.filter((/** @type {any} */ r) => r.card !== null).length * 50,
251
+ cards: [...new Set(rows.filter((/** @type {any} */ r) => r.card !== null).map((/** @type {any} */ r) => `${String(r.card)}:${String(r.stage)}`))], worstFrameMs: Math.max(0, ...span), over50: span.filter((/** @type {number} */ ms) => ms > 50).length };
252
+ }, { after: backFrom, slug: home.slug });
253
+ await page.screenshot({ path: join(out, `${tag}-road-drive.png`) });
254
+ const driven = result.segments.filter(row => row.driven === true), mbAll = driven.flatMap(row => { const mb = /** @type {any} */ (row.mb); return mb === null ? [] : [mb.min, mb.max]; });
255
+ const phoneBar = device !== '' ? 1 : 0, over50 = driven.reduce((sum, row) => sum + Number(row.over50), 0);
256
+ result.summary = { driveMs, from, segments: legs - from, driven: driven.length, over50, worstFrameMs: Math.max(0, ...driven.map(row => Number(row.worstFrameMs))), worstStopMs: Math.max(0, ...driven.map(row => Number(row.worstStopMs))),
257
+ worstRampMs: Math.max(0, ...driven.map(row => Number(row.rampMs ?? 0))),
258
+ cardMs: allCards.length * 50, cards: [...new Set(allCards.map((/** @type {any} */ r) => `${String(r.card)}:${String(r.stage)}`))], homeResident: allHome, homeKeptToM: KEEP_M, longFrames, mbGrowth: mbAll.length === 0 ? null : Math.max(...mbAll) - (/** @type {any} */ (driven[0]?.mb)?.min ?? 0),
259
+ bar: driven.length === legs - from && over50 <= phoneBar && driven.every(row => Number(row.worstStopMs) <= 250 && Number(row.rampMs ?? 0) <= RAMP_MS) && allCards.length === 0 && allHome && result.errors.length === 0 };
260
+ console.log(`${result.summary.bar === true ? 'ok ' : 'FAIL'} ${homeName} drive ${JSON.stringify(result.summary)}`);
261
+ console.log(`${result.back.inside === true && result.back.cardMs === 0 ? 'ok ' : 'FAIL'} ${homeName} back in ${JSON.stringify(result.back)}`);
262
+ await context.close();
263
+ code = result.summary.bar === true && (!whole || result.back.inside === true && result.back.cardMs === 0) ? 0 : 1;
264
+ } catch (error) { result.note = String(error).slice(0, 400); console.log(`FAIL ${result.note}`); }
265
+ finally {
266
+ writeFileSync(join(out, `${tag}-road-drive.json`), `${JSON.stringify(result, null, 2)}\n`);
267
+ await browser.close();
268
+ }
269
+ process.exit(code);
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ // ZONE-ENTRY ZE21 (Jake, 2026-11-15 ~16:50 Cancún, on the 300 m home unload: "why would having the home cell on the road cause a
3
+ // memory issue, the road should be very cheap ... Having the home cell in memory when your 10m away 100m or 300m away shouldnt
4
+ // matter"): what fills the page on the road, item by item. From Driftwood by Shard Select, on the board out of its east entryway
5
+ // and north up the road, it reads at each stop: the allocator's cost model by owner and category (what `playingMB` and the
6
+ // envelope count), the owner ledger (`__wildshard.memory()`, GPU and RAM bytes by owner and kind), three.js's counts, the JS heap
7
+ // after a full GC, and the renderer and GPU process footprints (real bytes, macOS `phys_footprint`). Desktop Chromium, 60 fps.
8
+ // scripts/browser-lane.sh node scripts/road-memory-probe.mjs --base=<loopback url> --out=<dir> [--label=<name>] [--stops=0,100,250,850]
9
+ // Stops are metres from the home's edge along the road (0: inside the home at control).
10
+ import { spawnSync } from 'node:child_process';
11
+ import { mkdirSync, writeFileSync } from 'node:fs';
12
+ import { join, resolve as absolute } from 'node:path';
13
+ import { launchMemoryBrowser } from './chromium-memory-browser.mjs';
14
+ import { saveFixture } from './debug-settings.mjs';
15
+ import { pageMemoryAttributionExpression } from './memory-report-snapshot.mjs';
16
+
17
+ const flag = (/** @type {string} */ name, /** @type {string} */ fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
18
+ const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', '')), label = flag('label', 'probe');
19
+ const stops = flag('stops', '0,100,250,850').split(',').map(Number);
20
+ if (!/^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: road-memory-probe.mjs --base=<loopback url> --out=<dir>');
21
+ mkdirSync(out, { recursive: true });
22
+ const MB = 1048576, HALF = 250, LANE_X = 281.25 - 10;
23
+ const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
24
+ const FOOTPRINT = String.raw`
25
+ import ctypes, json, sys
26
+ class R(ctypes.Structure):
27
+ _fields_ = [('uuid', ctypes.c_ubyte * 16)] + [(n, ctypes.c_uint64) for n in ('user_time','system_time','pkg_idle_wkups','interrupt_wkups','pageins','wired_size','resident_size','phys_footprint','proc_start_abstime','proc_exit_abstime')]
28
+ lib = ctypes.CDLL('/usr/lib/libproc.dylib'); out = {}
29
+ for p in sys.argv[1:]:
30
+ u = R()
31
+ out[p] = u.phys_footprint if lib.proc_pid_rusage(int(p), 0, ctypes.byref(u)) == 0 else None
32
+ print(json.dumps(out))
33
+ `;
34
+ const PAGE_READ = `(() => {
35
+ const api = window.__wildshard, mem = (() => { try { return ${pageMemoryAttributionExpression}; } catch (e) { return { error: String(e) }; } })();
36
+ const group = (rows, key) => { const m = new Map(); for (const r of rows) { const k = key(r); const v = m.get(k) ?? { bytes: 0, n: 0 }; v.bytes += r.bytes; v.n++; m.set(k, v); }
37
+ return [...m.entries()].map(([k, v]) => ({ k, mb: Math.round(v.bytes / 1048576 * 10) / 10, n: v.n })).sort((a, b) => b.mb - a.mb).slice(0, 30); };
38
+ const rows = Array.isArray(mem?.allocations) ? mem.allocations : [];
39
+ const st = api.shard.grid.state();
40
+ let three = null; try { const r = api.requireWorld().game.renderer; three = { textures: r.info.memory.textures, geometries: r.info.memory.geometries, programs: r.info.programs?.length ?? null, calls: r.info.render.calls, triangles: r.info.render.triangles }; } catch {}
41
+ // the cost model (what playingMB and the envelope count): every claim's accounted bytes by owner and by category, and the inputs
42
+ let cost = null; try { const res = api.shard.grid.residency(), m = (b) => Math.round(b / 1048576 * 10) / 10, by = (key) => { const g = new Map(); for (const c of res.claims) { const k = key(c); g.set(k, (g.get(k) ?? 0) + (c.accountedBytes ?? 0)); } return [...g].map(([k, b]) => [k, m(b)]).sort((x, y) => y[1] - x[1]); };
43
+ cost = { playingMB: m(res.cost.playing), accountedMB: m(res.cost.accounted), engineBaseMB: m(res.cost.input?.engineBase ?? 0), pageMB: m(res.cost.input?.page ?? 0), overlapMB: m(res.cost.input?.overlap ?? 0),
44
+ byOwner: by(c => c.owner).slice(0, 20), byCategory: by(c => c.category), byOwnerCategory: by(c => c.owner + ' ' + c.category).slice(0, 30) }; } catch (e) { cost = { error: String(e).slice(0, 160) }; }
45
+ const lv = st.live?.live;
46
+ const why = { home: st.home, gate: st.gate, current: lv?.current ?? null, pending: lv?.pending ?? null, crossings: lv?.crossings ?? null, transitions: (lv?.transitions ?? []).slice(-6), retirements: (lv?.retirements ?? []).slice(-6), hybrid: st.hybrid ?? null };
47
+ return { why, cost, feet: st.feet, inside: st.inside, residents: st.live?.live?.residents ?? null, playingMB: st.playingMB, residentMB: st.residentMB, envelopeMB: st.envelopeMB,
48
+ shows: Object.entries(st.cells.reduce((m, c) => { m[c.shows] = (m[c.shows] ?? 0) + 1; return m; }, {})), rings: { far: st.rings.far, l1: st.rings.l1, l0: st.rings.l0 },
49
+ ledgerMB: mem?.totals ? { gpu: Math.round(mem.totals.gpu / 1048576), ram: Math.round(mem.totals.ram / 1048576) } : null,
50
+ byOwner: group(rows, r => r.domain + ' ' + r.owner), byKind: group(rows, r => r.domain + ' ' + r.kind), three };
51
+ })()`;
52
+
53
+ const { browser, close } = await launchMemoryBrowser(['--use-angle=metal', '--ignore-gpu-blocklist', '--enable-precise-memory-info', '--mute-audio']);
54
+ const result = { base, label, at: new Date().toISOString(), build: '', stops: /** @type {any[]} */ ([]), errors: /** @type {string[]} */ ([]), note: '' };
55
+ let code = 1;
56
+ /** @type {import('playwright').Page | undefined} */
57
+ let shown;
58
+ try {
59
+ result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
60
+ const context = await browser.newContext({ viewport: { width: 2992, height: 1434 }, deviceScaleFactor: 2 }), page = await context.newPage(); shown = page;
61
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
62
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
63
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
64
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { volume: 0 } });
65
+ const cdp = await browser.newBrowserCDPSession(), pageCdp = await context.newCDPSession(page);
66
+ const footprint = async () => {
67
+ const info = await cdp.send('SystemInfo.getProcessInfo'), pids = info.processInfo.filter(row => row.type === 'renderer' || row.type === 'GPU');
68
+ const sizes = JSON.parse(spawnSync('python3', ['-c', FOOTPRINT, ...pids.map(row => String(row.id))], { encoding: 'utf8' }).stdout || '{}');
69
+ const mb = (/** @type {string} */ type) => Math.round(pids.filter(row => row.type === type).reduce((sum, row) => sum + (sizes[String(row.id)] ?? 0), 0) / MB);
70
+ return { rendererMB: mb('renderer'), gpuMB: mb('GPU') };
71
+ };
72
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
73
+ await page.locator('.ws-main-select').click({ timeout: 120_000 });
74
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('roadmem'); await page.locator('#ws-name-box button[type=submit]').click(); }
75
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
76
+ const index = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes('Driftwood Isle')));
77
+ await page.locator('.ws-menu-dots i').nth(index).click();
78
+ await page.locator('.ws-menu-play').click();
79
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
80
+ await sleep(2000);
81
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
82
+ const origin = await page.evaluate(() => { const W = /** @type {any} */ (window), wf = W.__wildshard.shard.grid.state().live.live.worldFeet, p = W.__wildshard.world.player.position; return { x: wf.x - p.x, z: wf.z - p.z }; });
83
+ const read = async (/** @type {string} */ name) => {
84
+ await sleep(8000); // settle: rings, far views and lazy work reach a steady state at this spot
85
+ const before = await footprint();
86
+ await pageCdp.send('HeapProfiler.collectGarbage');
87
+ const heapAfterGcMB = Math.round((await pageCdp.send('Runtime.getHeapUsage')).usedSize / MB);
88
+ const row = { stop: name, ...await page.evaluate(PAGE_READ), process: before, processAfterGc: await footprint(), heapAfterGcMB };
89
+ result.stops.push(row);
90
+ console.log(`${name}: feet ${JSON.stringify(row.feet)} residents ${JSON.stringify(row.residents)} playingMB ${String(row.playingMB)} ledger ${JSON.stringify(row.ledgerMB)} heap ${String(heapAfterGcMB)} process ${JSON.stringify(row.processAfterGc)}`);
91
+ };
92
+ // drive by waypoints with W held; the page steers (a 50 ms yaw toward the next point)
93
+ const drive = async (/** @type {{ x: number, z: number }[]} */ wps) => {
94
+ await page.evaluate(points => {
95
+ const W = /** @type {any} */ (window), q = W.__mem = { wps: points, at: 0 };
96
+ if (W.__memTimer !== undefined) clearInterval(W.__memTimer);
97
+ W.__memTimer = setInterval(() => { const wf = W.__wildshard.shard.grid.state().live?.live?.worldFeet, p = W.__wildshard.world.player, to = q.wps[q.at];
98
+ if (wf === undefined || to === undefined) return; if (Math.hypot(wf.x - to.x, wf.z - to.z) < 4) { q.at++; return; } p.yaw = Math.atan2(wf.x - to.x, wf.z - to.z); }, 50);
99
+ }, wps);
100
+ await page.keyboard.down('KeyW');
101
+ for (const ends = Date.now() + 180_000; Date.now() < ends;) { if (await page.evaluate(() => /** @type {any} */ (window).__mem.at >= /** @type {any} */ (window).__mem.wps.length)) break; await sleep(250); }
102
+ await page.keyboard.up('KeyW');
103
+ };
104
+ for (const stop of stops) {
105
+ if (stop === 0) { await read('home'); continue; }
106
+ if (result.stops.every(row => row.stop === 'home')) {
107
+ await page.evaluate(([px, pz]) => { const p = /** @type {any} */ (window).__wildshard.world.player; p.spawn(px, pz, p.yaw, 1.5); p.link?.place?.(p.position.x, p.position.y, p.position.z, p.yaw); }, [HALF - 20, 0]);
108
+ await sleep(3000);
109
+ await page.evaluate(() => { const p = /** @type {any} */ (window).__wildshard.world.player; if (!p.hover) p.setHover(true); });
110
+ await sleep(800);
111
+ await drive([{ x: origin.x + LANE_X, z: origin.z }]);
112
+ }
113
+ // north along the road: the edge distance on the lane is hypot(lane offset, z past the corner); junctions are passed 10 m off
114
+ // their centres (the lane already is)
115
+ const z = HALF + Math.sqrt(Math.max(0, stop * stop - (LANE_X - HALF) ** 2));
116
+ await drive([{ x: origin.x + LANE_X, z: origin.z + z }]);
117
+ await read(`road+${String(stop)}m`);
118
+ }
119
+ await context.close();
120
+ code = 0;
121
+ } catch (error) {
122
+ result.note = String(error).slice(0, 400); console.log(`FAIL ${result.note}`);
123
+ await shown?.screenshot({ path: join(out, `${label}-fail.png`) }).catch(() => undefined);
124
+ }
125
+ finally {
126
+ writeFileSync(join(out, `${label}-road-memory.json`), `${JSON.stringify(result, null, 2)}\n`);
127
+ await close();
128
+ }
129
+ process.exit(code);
@@ -5,9 +5,9 @@
5
5
  // node scripts/scratch-dir.mjs <task> "<purpose>" [--row <plan-row>]
6
6
  //
7
7
  // creates <repo>/tmp/<task>/ and tmp/<task>/.owner, then prints the folder's absolute path. .owner is JSON: the session
8
- // id ($CLAUDE_SESSION_ID, else $CLAUDE_CODE_SESSION_ID, else the Codex lane name in $WS_LANE_NAME), the lane name, the
8
+ // id ($CODEX_THREAD_ID, else $CLAUDE_SESSION_ID, else $CLAUDE_CODE_SESSION_ID, else $WS_LANE_NAME), the lane name, the
9
9
  // herdr pane ($HERDR_PANE_ID), the start time and the purpose. DK4's SessionEnd hook removes the folders whose .owner
10
- // names the ending session; a .keep file in the folder (one line: why to keep it) stops that and DK6's 3-day sweep.
10
+ // names the ending session. J358 makes cleanup report-only; a human audits and copies before removal.
11
11
  //
12
12
  // <task> is one plain folder name: letters, digits, '.', '_' and '-', not starting with '.', never containing '/' or
13
13
  // '..'. The helper deletes nothing. It refuses a folder that already exists unless that folder's .owner names this
@@ -41,10 +41,10 @@ export function ownerRecord(task, purpose, env, now, row = null) {
41
41
  catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') receiptOffset = 0; }
42
42
  return {
43
43
  task,
44
- session: env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || env.CODEX_THREAD_ID || lane,
44
+ session: env.CODEX_THREAD_ID || env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
45
45
  lane,
46
46
  pane: env.HERDR_PANE_ID || null,
47
- agent: env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID ? 'claude' : env.CODEX_THREAD_ID || lane ? 'codex' : 'unknown',
47
+ agent: env.CODEX_THREAD_ID ? 'codex' : env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID ? 'claude' : lane ? 'codex' : 'unknown',
48
48
  row,
49
49
  receiptOffset,
50
50
  started: now.toISOString(),
@@ -1,4 +1,4 @@
1
- // Privileged workflow entry: only trusted main-push CI and main-history version tags.
1
+ // Privileged workflow entry: release-branch CI and reachable version tags only.
2
2
  import { createHash } from 'node:crypto';
3
3
  import { execFileSync } from 'node:child_process';
4
4
  import { appendFileSync, readFileSync } from 'node:fs';
@@ -8,7 +8,7 @@ import { setTimeout as sleep } from 'node:timers/promises';
8
8
  import * as v from 'valibot';
9
9
  import { COMMIT } from './sign.mjs';
10
10
 
11
- const REPOSITORY = 'project-wildshard/engine', VERSION = /^v\d+\.\d+\.\d+$/u;
11
+ const REPOSITORY = 'project-wildshard/engine', VERSION = /^v\d+\.\d+\.\d+$/u, RELEASE_BRANCH = /^release\/v\d+\.\d+\.\d+$/u;
12
12
  const Run = v.object({ id: v.number(), head_sha: v.string(), head_branch: v.nullable(v.string()), event: v.string(), status: v.string(), conclusion: v.nullable(v.string()) });
13
13
  const Release = v.object({ id: v.number(), upload_url: v.string(), assets: v.array(v.object({ name: v.string(), browser_download_url: v.string() })) });
14
14
  class GitHubError extends Error {
@@ -27,7 +27,7 @@ async function api(path, options = {}) {
27
27
  /** @param {string[]} args @returns {string} */
28
28
  const git = args => execFileSync('git', args, { encoding: 'utf8' }).trim();
29
29
 
30
- /** No fork or PR event is allowed to reach a signing job. @returns {{sha: string, channel: string, tag: string, align?: true} | null} */
30
+ /** No fork or PR event is allowed to reach a signing job. @returns {{sha: string, channel: string, tag: string, branches: string[], align?: true, legacy?: true} | null} */
31
31
  function candidate() {
32
32
  if (process.env.GITHUB_REPOSITORY !== REPOSITORY) return null;
33
33
  const eventName = process.env.GITHUB_EVENT_NAME;
@@ -36,53 +36,83 @@ function candidate() {
36
36
  const sha = process.env.ALIGN_BUILD ?? '';
37
37
  if (process.env.GITHUB_REF !== 'refs/heads/main') throw new Error('Staging alignment runs from main only');
38
38
  if (!COMMIT.test(sha)) throw new Error('Staging alignment needs a full 40-character build SHA');
39
- return { sha, channel: 'staging', tag: `server-staging-${sha}`, align: true };
39
+ const branches = git(['for-each-ref', '--format=%(refname:short)', '--contains', sha, 'refs/remotes/origin/release/']).split('\n')
40
+ .map(ref => ref.replace(/^origin\//u, '')).filter(ref => RELEASE_BRANCH.test(ref) && git(['rev-parse', `refs/remotes/origin/${ref}^{commit}`]) === sha);
41
+ if (branches.length === 0) {
42
+ const prepared = publishedMainRelease(sha);
43
+ if (prepared === null) throw new Error('Staging alignment needs a published release-branch build');
44
+ return { sha, channel: 'staging', tag: `server-staging-${sha}`, branches: [`release/${prepared}`, 'main'], align: true, legacy: true };
45
+ }
46
+ return { sha, channel: 'staging', tag: `server-staging-${sha}`, branches, align: true };
40
47
  }
41
48
  if (eventName === 'workflow_run') {
42
49
  const event = v.parse(v.object({ workflow_run: v.object({ ...Run.entries, head_repository: v.object({ full_name: v.string() }) }) }), JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH ?? '', 'utf8'))).workflow_run;
43
- if (event.event !== 'push' || event.head_branch !== 'main' || event.head_repository.full_name !== REPOSITORY || event.conclusion !== 'success') return null;
50
+ if (event.event !== 'push' || !RELEASE_BRANCH.test(event.head_branch ?? '') || event.head_repository.full_name !== REPOSITORY || event.conclusion !== 'success') return null;
44
51
  if (!COMMIT.test(event.head_sha)) throw new Error('Invalid green source SHA');
45
- return { sha: event.head_sha, channel: 'staging', tag: `server-staging-${event.head_sha}` };
52
+ return { sha: event.head_sha, channel: 'staging', tag: `server-staging-${event.head_sha}`, branches: [event.head_branch ?? ''] };
46
53
  }
47
54
  if (eventName === 'push') {
48
55
  const tag = process.env.GITHUB_REF_NAME ?? '';
49
56
  if (process.env.GITHUB_REF_TYPE !== 'tag' || !VERSION.test(tag)) return null;
50
57
  const sha = git(['rev-parse', '--verify', `refs/tags/${tag}^{commit}`]);
51
58
  if (!COMMIT.test(sha)) throw new Error('Invalid tagged source SHA');
52
- return { sha, channel: 'production', tag };
59
+ return { sha, channel: 'production', tag, branches: [`release/${tag}`, 'main'] };
53
60
  }
54
61
  return null;
55
62
  }
56
63
 
57
- /** Exact-SHA success of both normal push workflows; a PR result cannot stand in.
58
- * @param {string} sha @returns {Promise<'green' | 'pending' | 'red'>} */
59
- async function checks(sha) {
60
- let pending = false;
61
- for (const workflow of ['ci.yml']) {
62
- const value = await api(`actions/workflows/${workflow}/runs?head_sha=${sha}&event=push&branch=main&per_page=100`);
63
- const rows = v.parse(v.object({ workflow_runs: v.array(Run) }), value).workflow_runs
64
- .filter(run => run.head_sha === sha && run.head_branch === 'main' && run.event === 'push').sort((a, b) => b.id - a.id);
65
- const run = rows[0];
66
- if (run === undefined || run.status !== 'completed') pending = true;
67
- else if (run.conclusion !== 'success') return 'red';
68
- }
69
- return pending ? 'pending' : 'green';
64
+ /** Whether this published ref contains the source. Missing release refs are expected after merge-back.
65
+ * @param {string} sha @param {string} branch */
66
+ function reachable(sha, branch) {
67
+ try { git(['merge-base', '--is-ancestor', sha, `refs/remotes/origin/${branch}`]); return true; }
68
+ catch { return false; }
69
+ }
70
+
71
+ /** Let a release already prepared on main finish through explicit alignment.
72
+ * Ordinary main CI events never enter this path. @param {string} sha @returns {string | null} */
73
+ function publishedMainRelease(sha) {
74
+ if (!reachable(sha, 'main')) return null;
75
+ try {
76
+ const tag = /^chore\(release\): (v\d+\.\d+\.\d+)$/u.exec(git(['log', '-1', '--format=%s', sha]))?.[1];
77
+ return tag !== undefined && JSON.parse(git(['show', `${sha}:package.json`])).version === tag.slice(1) ? tag : null;
78
+ } catch { return null; }
79
+ }
80
+
81
+ /** Exact-SHA push CI on an admitted branch; PRs and plan branches cannot authorize a release.
82
+ * @param {string} sha @param {string[]} branches @returns {Promise<'green' | 'pending' | 'red'>} */
83
+ async function checks(sha, branches) {
84
+ const value = await api(`actions/workflows/ci.yml/runs?head_sha=${sha}&event=push&per_page=100`);
85
+ const rows = v.parse(v.object({ workflow_runs: v.array(Run) }), value).workflow_runs
86
+ .filter(run => run.head_sha === sha && branches.includes(run.head_branch ?? '') && run.event === 'push').sort((a, b) => b.id - a.id);
87
+ const latest = branches.flatMap(branch => { const row = rows.find(run => run.head_branch === branch); return row === undefined ? [] : [row]; });
88
+ if (latest.some(run => run.status === 'completed' && run.conclusion === 'success')) return 'green';
89
+ if (latest.length === 0 || latest.some(run => run.status !== 'completed')) return 'pending';
90
+ return 'red';
70
91
  }
71
92
 
72
93
  /** @returns {Promise<void>} */
73
94
  async function select() {
74
95
  const source = candidate(); if (source === null) return;
75
- git(['merge-base', '--is-ancestor', source.sha, 'origin/main']);
96
+ if (source.channel === 'staging' && source.legacy !== true && !source.branches.some(branch => {
97
+ try { return git(['rev-parse', '--verify', `refs/remotes/origin/${branch}^{commit}`]) === source.sha; } catch { return false; }
98
+ })) {
99
+ if (source.align === true) throw new Error('Staging alignment needs the current release-branch head');
100
+ return; // A delayed CI event must not publish an older release-branch head.
101
+ }
102
+ const published = source.branches.some(branch => reachable(source.sha, branch));
103
+ if (!published) throw new Error('Release source is unreachable from its published release branch or main');
104
+ // A completed release keeps its exact-SHA branch proof after merge-back deletes the branch.
105
+ const proofBranches = source.channel === 'production' || source.legacy === true ? source.branches : source.branches.filter(branch => reachable(source.sha, branch));
76
106
  // A late workflow_run from before this producer existed is not a release candidate.
77
107
  if (execFileSync('git', ['ls-tree', '--name-only', source.sha, 'scripts/server-release/publish.mjs'], { encoding: 'utf8' }).trim() === '') return;
78
108
  const deadline = Date.now() + 40 * 60_000;
79
109
  for (;;) {
80
- const state = await checks(source.sha);
110
+ const state = await checks(source.sha, proofBranches);
81
111
  if (state === 'green') break;
82
- if (source.align === true) throw new Error(`Build ${source.sha} is not green on main CI and Ring 1`);
83
- if (state === 'red') { if (source.channel === 'staging') return; throw new Error('Tagged commit has a failed main CI workflow'); }
112
+ if (source.align === true) throw new Error(`Build ${source.sha} is not green on release-branch CI and Ring 1`);
113
+ if (state === 'red') { if (source.channel === 'staging') return; throw new Error('Tagged commit has a failed release CI workflow'); }
84
114
  if (source.channel === 'staging') return; // The other workflow's completion will trigger again.
85
- if (Date.now() >= deadline) throw new Error('Timed out waiting for tagged main CI');
115
+ if (Date.now() >= deadline) throw new Error('Timed out waiting for tagged release CI');
86
116
  await sleep(20_000);
87
117
  }
88
118
  const output = process.env.GITHUB_OUTPUT; if (output === undefined) throw new Error('Missing GITHUB_OUTPUT');
@@ -102,7 +132,10 @@ async function verifyReleaseTag(tag, sha) {
102
132
  async function asset(tag, sha, archive, channel) {
103
133
  if (!COMMIT.test(sha) || !(VERSION.test(tag) && channel === 'production' || tag === `server-staging-${sha}` && channel === 'staging')) throw new Error('Invalid server release tag');
104
134
  if (git(['rev-parse', 'HEAD']) !== sha) throw new Error('Bundle checkout differs from release source');
105
- git(['merge-base', '--is-ancestor', sha, 'origin/main']);
135
+ const releaseBranches = channel === 'production' ? [`release/${tag}`] : git(['for-each-ref', '--format=%(refname:short)', '--contains', sha, 'refs/remotes/origin/release/']).split('\n').map(ref => ref.replace(/^origin\//u, '')).filter(ref => RELEASE_BRANCH.test(ref));
136
+ const legacy = channel === 'staging' && publishedMainRelease(sha) !== null;
137
+ if ((channel === 'production' || legacy ? [...releaseBranches, 'main'] : releaseBranches).every(branch => !reachable(sha, branch))) throw new Error('Server asset source is unreachable from release history');
138
+ if (channel === 'staging' && !legacy && !releaseBranches.some(branch => git(['rev-parse', `refs/remotes/origin/${branch}^{commit}`]) === sha)) throw new Error('Staging asset must name the current release-branch head');
106
139
  /** @type {v.InferOutput<typeof Release>} */
107
140
  let release;
108
141
  try { release = v.parse(Release, await api(`releases/tags/${encodeURIComponent(tag)}`)); }