@wildshard/engine 0.1.22 → 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 (179) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/index.html +17 -4
  3. package/lint/engine-sides.json +9 -0
  4. package/lint/sim-players.json +2 -13
  5. package/package.json +36 -3
  6. package/scripts/apfs-clone.mjs +5 -2
  7. package/scripts/app-build/catalogue.ts +39 -8
  8. package/scripts/app-build/serviceWorker.ts +4 -1
  9. package/scripts/app-build/splitOutput.mjs +33 -11
  10. package/scripts/app-build/titlePreloads.mjs +8 -5
  11. package/scripts/bake-road-surfaces.entry.ts +18 -0
  12. package/scripts/bake-road-surfaces.mjs +44 -0
  13. package/scripts/changelog.mjs +2 -1
  14. package/scripts/ci-pack.mjs +3 -3
  15. package/scripts/engine-ci-shard.mjs +11 -0
  16. package/scripts/fight-page-census.mjs +131 -0
  17. package/scripts/goldens/board.py +44 -11
  18. package/scripts/goldens/capture.mjs +18 -6
  19. package/scripts/goldens/native-residency.d.mts +2 -0
  20. package/scripts/goldens/native-residency.mjs +31 -4
  21. package/scripts/grid-road-lag.mjs +209 -0
  22. package/scripts/keep-copy.mjs +172 -0
  23. package/scripts/land.d.mts +4 -1
  24. package/scripts/land.mjs +121 -9
  25. package/scripts/lane-live.mjs +136 -0
  26. package/scripts/leftovers-report.mjs +47 -0
  27. package/scripts/loading-card-proof.mjs +42 -9
  28. package/scripts/loading-flow/benchmax.mjs +59 -7
  29. package/scripts/loading-flow/stalls.d.mts +2 -0
  30. package/scripts/loading-flow/stalls.mjs +13 -0
  31. package/scripts/map-hash.mjs +1 -1
  32. package/scripts/mmo-bots.mjs +5 -3
  33. package/scripts/mmo-grid-proof.mjs +74 -0
  34. package/scripts/mmo-seat-proof.mjs +43 -0
  35. package/scripts/nightly-heads.ts +13 -13
  36. package/scripts/nightly-model.ts +26 -12
  37. package/scripts/nightly-tag.mjs +2 -4
  38. package/scripts/nightly.proof.ts +18 -5
  39. package/scripts/nightly.ts +13 -8
  40. package/scripts/no-astc-boot.mjs +77 -0
  41. package/scripts/page-release/content.mjs +19 -10
  42. package/scripts/page-release/flow.d.mts +3 -2
  43. package/scripts/page-release/flow.mjs +31 -21
  44. package/scripts/page-release/packs.d.mts +5 -0
  45. package/scripts/page-release/packs.mjs +13 -3
  46. package/scripts/page-release/preview.d.mts +2 -0
  47. package/scripts/page-release/preview.mjs +74 -0
  48. package/scripts/page-release.mjs +13 -5
  49. package/scripts/physics-route.json +6 -6
  50. package/scripts/pins-reuse.mjs +1 -0
  51. package/scripts/pins-staging.ts +54 -0
  52. package/scripts/pins.ts +5 -0
  53. package/scripts/ring3.proof.ts +71 -0
  54. package/scripts/ring3.ts +100 -0
  55. package/scripts/road-drive-proof.mjs +269 -0
  56. package/scripts/road-memory-probe.mjs +129 -0
  57. package/scripts/scratch-dir.mjs +33 -14
  58. package/scripts/scratch-sweep.mjs +15 -23
  59. package/scripts/server-release/github.mjs +59 -26
  60. package/scripts/server-release/items.d.mts +7 -0
  61. package/scripts/server-release/items.mjs +28 -0
  62. package/scripts/server-release/publish.mjs +24 -2
  63. package/scripts/server-release/sign.mjs +8 -4
  64. package/scripts/side-parity.mjs +1 -1
  65. package/scripts/test-products.json +1 -0
  66. package/scripts/test_prebuilt_output.py +3 -1
  67. package/scripts/tsconfig.json +2 -0
  68. package/scripts/turn-in-shots.mjs +83 -0
  69. package/scripts/vitest-bench-observe-proof.py +168 -0
  70. package/scripts/vitest-bench.py +122 -77
  71. package/scripts/vitest-ci-files.ts +5 -1
  72. package/scripts/vps/rebuild.sh +3 -1
  73. package/scripts/vps/wildshard-config +106 -1
  74. package/scripts/warm-native-chrome.mjs +9 -3
  75. package/scripts/worker-client-fights.mjs +9 -3
  76. package/scripts/worktree-reap.mjs +36 -140
  77. package/scripts/worktree.mjs +92 -12
  78. package/scripts/zone-gate-proof.mjs +93 -0
  79. package/src/client/engine/audio/audioLog.ts +7 -2
  80. package/src/client/engine/boot/diagnostics.ts +69 -1
  81. package/src/client/engine/boot/sw.ts +3 -1
  82. package/src/client/engine/core/ktx2.ts +33 -10
  83. package/src/client/engine/core/ktx2Zstd.ts +2 -1
  84. package/src/client/engine/models/place.ts +7 -5
  85. package/src/client/engine/pwa/sw.js +83 -10
  86. package/src/client/engine/render/dataLook.ts +14 -7
  87. package/src/client/engine/render/lookLight.ts +64 -20
  88. package/src/client/engine/render/precompile.ts +6 -0
  89. package/src/client/engine/render/tiers.ts +9 -0
  90. package/src/client/engine/ui/Loading.ts +6 -8
  91. package/src/client/engine/ui/lookLightOption.ts +1 -1
  92. package/src/client/engine/ui/playerReload.ts +5 -5
  93. package/src/client/game/audio/cueDirector.ts +2 -1
  94. package/src/client/game/boot/bytes.generated.ts +4 -1
  95. package/src/client/game/boot/versions.generated.ts +8 -5
  96. package/src/client/game/boss/arenaRoom.ts +4 -3
  97. package/src/client/game/boss/roamingProjection.ts +1 -1
  98. package/src/client/game/devScene/hook.ts +1 -1
  99. package/src/client/game/devScene/liveLook.ts +1 -1
  100. package/src/client/game/grid/cellClip.ts +70 -6
  101. package/src/client/game/grid/dataCellKit.ts +9 -1
  102. package/src/client/game/grid/gateCard.css +9 -0
  103. package/src/client/game/grid/gateCard.ts +67 -0
  104. package/src/client/game/grid/live.ts +17 -3
  105. package/src/client/game/grid/liveSession.ts +15 -5
  106. package/src/client/game/grid/neighbourLife.ts +10 -1
  107. package/src/client/game/grid/neighbourPanels.ts +29 -2
  108. package/src/client/game/grid/pageEntry.ts +21 -0
  109. package/src/client/game/grid/products.ts +21 -7
  110. package/src/client/game/grid/regionalWorld.ts +5 -0
  111. package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
  112. package/src/client/game/grid/roadLook.ts +5 -73
  113. package/src/client/game/grid/roadLookPlatform.ts +11 -6
  114. package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
  115. package/src/client/game/grid/roadTilePool.ts +4 -0
  116. package/src/client/game/grid/session.ts +58 -16
  117. package/src/client/game/grid/softWallLook.ts +6 -1
  118. package/src/client/game/plugin/ui.ts +3 -0
  119. package/src/client/game/population/signals.ts +1 -1
  120. package/src/client/game/quest/chapterDirector.ts +1 -0
  121. package/src/client/game/session/play.ts +3 -0
  122. package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
  123. package/src/client/game/shardfile/clientSource.ts +5 -2
  124. package/src/client/game/shardfile/clientWorker.ts +25 -8
  125. package/src/client/game/shardfile/look.ts +1 -1
  126. package/src/client/game/shardfile/runtimeProduct.ts +9 -5
  127. package/src/client/game/shardfile/slabLibrary.ts +37 -0
  128. package/src/client/game/shardfile/slabRanges.ts +145 -0
  129. package/src/client/game/shardfile/wirePage.ts +5 -2
  130. package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
  131. package/src/client/host/online/shell.ts +2 -2
  132. package/src/client/host/standalone/shell.ts +4 -1
  133. package/src/cook/game/cookWorker.ts +8 -5
  134. package/src/cook/game/tierTextures.ts +5 -3
  135. package/src/server/engine/net/simWorld.ts +3 -4
  136. package/src/server/game/grid/cellHome.ts +58 -0
  137. package/src/server/game/grid/simulation.ts +32 -8
  138. package/src/server/game/plugin/mover.ts +18 -14
  139. package/src/server/game/plugin/simulation.ts +2 -0
  140. package/src/server/game/shardfile/dataRespawn.ts +47 -0
  141. package/src/server/game/shardfile/declaredKitItems.ts +31 -7
  142. package/src/server/host/bake/headlessWorker.ts +3 -3
  143. package/src/server/host/dedicated/cellWorker.ts +4 -2
  144. package/src/server/host/dedicated/main.ts +7 -4
  145. package/src/server/host/dedicated/packReader.ts +15 -2
  146. package/src/server/host/dedicated/playerStore.ts +1 -1
  147. package/src/server/host/headlessRuntime.ts +11 -6
  148. package/src/server/host/standalone/cellWorld.ts +20 -6
  149. package/src/server/host/standalone/gridServer.ts +20 -6
  150. package/src/server/host/standalone/roadWorld.ts +36 -0
  151. package/src/server/host/standalone/serverHost.ts +2 -2
  152. package/src/shared/engine/entities/AnimalSim.ts +10 -0
  153. package/src/shared/engine/physics/gridBorders.ts +15 -1
  154. package/src/shared/engine/physics/transferWalls.ts +9 -4
  155. package/src/shared/engine/sim/snapshot.ts +5 -5
  156. package/src/shared/game/grid/allocator.ts +8 -1
  157. package/src/shared/game/grid/gateCount.ts +27 -0
  158. package/src/shared/game/grid/zoneWalls.ts +64 -0
  159. package/src/shared/game/ledger.ts +13 -4
  160. package/src/shared/game/loot/platformCatalogue.ts +14 -0
  161. package/src/shared/game/quest/ledger.ts +3 -3
  162. package/src/shared/game/shardfile/items.ts +9 -1
  163. package/src/shared/game/strings.ts +2 -0
  164. package/src/shared/host/headlessJourney.ts +3 -3
  165. package/src/shared/host/headlessTape.ts +7 -6
  166. package/src/shared/host/releaseRows.ts +4 -1
  167. package/src/shared/host/standalone/harnessPlace.ts +4 -0
  168. package/src/test/engine/simState.ts +134 -0
  169. package/src/test/game/builtProduct.ts +6 -0
  170. package/src/test/game/headless/admittedProductCache.ts +61 -0
  171. package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
  172. package/src/test/game/headless/nativeBounds.ts +27 -0
  173. package/src/test/game/headless/processUsage.ts +22 -0
  174. package/src/test/game/headless/productSession.ts +39 -0
  175. package/src/test/game/headless/ropeBodies.ts +60 -0
  176. package/src/test/game/headless/worker.ts +34 -0
  177. package/src/test/game/headlessNative.ts +114 -0
  178. package/src/test/game/headlessWorker.ts +43 -0
  179. 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);
@@ -2,17 +2,18 @@
2
2
  // repo-kit's scratch folder maker (meta docs/plans/REPO-DISK-PLAN.md row DK3). One copy lives in repo-kit; every org
3
3
  // repo and singleplayer carries a byte-identical copy at scripts/scratch-dir.mjs (DK8 checks the copies).
4
4
  //
5
- // node scripts/scratch-dir.mjs <task> "<purpose>"
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
14
14
  // same session (then it prints the path again), so it never takes over another lane's or an ownerless folder.
15
- import { mkdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
15
+ import { mkdirSync, readFileSync, renameSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
16
17
  import { join, resolve } from 'node:path';
17
18
  import { pathToFileURL } from 'node:url';
18
19
 
@@ -31,14 +32,21 @@ export function refuseTask(task) {
31
32
  }
32
33
 
33
34
  /** The .owner record for a new folder.
34
- * @param {string} task @param {string} purpose @param {NodeJS.ProcessEnv} env @param {Date} now */
35
- export function ownerRecord(task, purpose, env, now) {
35
+ * @param {string} task @param {string} purpose @param {NodeJS.ProcessEnv} env @param {Date} now
36
+ * @param {string | null} row */
37
+ export function ownerRecord(task, purpose, env, now, row = null) {
36
38
  const lane = env.WS_LANE_NAME || null;
39
+ let receiptOffset = null;
40
+ try { receiptOffset = statSync(env.WS_LANE_RECEIPTS ?? join(homedir(), '.cache/wildshard/lane-receipts.log')).size; }
41
+ catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') receiptOffset = 0; }
37
42
  return {
38
43
  task,
39
- session: env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
44
+ session: env.CODEX_THREAD_ID || env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
40
45
  lane,
41
46
  pane: env.HERDR_PANE_ID || null,
47
+ agent: env.CODEX_THREAD_ID ? 'codex' : env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID ? 'claude' : lane ? 'codex' : 'unknown',
48
+ row,
49
+ receiptOffset,
42
50
  started: now.toISOString(),
43
51
  purpose,
44
52
  };
@@ -52,21 +60,29 @@ function readOwner(path) {
52
60
  /** Make <root>/tmp/<task>/ and its .owner; returns the folder's absolute path. Throws on a refused name, an empty
53
61
  * purpose, or a folder that exists and is not this session's.
54
62
  * @param {string} task @param {string} purpose
55
- * @param {{root?: string, env?: NodeJS.ProcessEnv, now?: Date}} [options] */
56
- export function scratchDir(task, purpose, { root = ROOT, env = process.env, now = new Date() } = {}) {
63
+ * @param {{root?: string, env?: NodeJS.ProcessEnv, now?: Date, row?: string | null}} [options] */
64
+ export function scratchDir(task, purpose, { root = ROOT, env = process.env, now = new Date(), row = null } = {}) {
57
65
  const refusal = refuseTask(task);
58
66
  if (refusal) throw new Error(refusal);
59
67
  if (typeof purpose !== 'string' || purpose.trim() === '') throw new Error('a purpose is required');
60
68
  const tmp = join(resolve(root), 'tmp');
61
69
  const dir = join(tmp, task);
62
- const owner = ownerRecord(task, purpose.trim(), env, now);
70
+ if (row !== null && !/^[A-Z][A-Z0-9-]*\d+[a-z]?$/u.test(row)) throw new Error(`row "${row}" is not a plan row`);
71
+ const owner = ownerRecord(task, purpose.trim(), env, now, row);
63
72
  mkdirSync(tmp, { recursive: true });
64
73
  try {
65
74
  mkdirSync(dir);
66
75
  } catch (error) {
67
76
  if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;
68
77
  const existing = readOwner(join(dir, '.owner'));
69
- if (existing && owner.session && existing.session === owner.session) return dir;
78
+ if (existing && owner.session && existing.session === owner.session) {
79
+ // A lane name can outlive a task. Advance its cursor when it resumes,
80
+ // without ever exposing a half-written ownership record.
81
+ const next = join(dir, `.owner-${process.pid}`);
82
+ writeFileSync(next, `${JSON.stringify(owner, null, 2)}\n`, { flag: 'wx' });
83
+ renameSync(next, join(dir, '.owner'));
84
+ return dir;
85
+ }
70
86
  throw new Error(existing
71
87
  ? `${dir} already belongs to session ${String(existing.session)}; pick another task name`
72
88
  : `${dir} already exists with no .owner; pick another task name`);
@@ -82,12 +98,15 @@ export function scratchDir(task, purpose, { root = ROOT, env = process.env, now
82
98
 
83
99
  if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
84
100
  const [task = '', purpose = '', ...rest] = process.argv.slice(2);
85
- if (rest.length > 0 || task === '--help' || task === '-h') {
86
- console.error('usage: node scripts/scratch-dir.mjs <task> "<purpose>"');
101
+ const rowAt = rest.indexOf('--row');
102
+ const row = rowAt === -1 ? null : rest[rowAt + 1] ?? null;
103
+ const other = rowAt === -1 ? rest : rest.filter((_, index) => index !== rowAt && index !== rowAt + 1);
104
+ if (other.length > 0 || task === '--help' || task === '-h' || rowAt !== -1 && row === null) {
105
+ console.error('usage: node scripts/scratch-dir.mjs <task> "<purpose>" [--row <plan-row>]');
87
106
  process.exit(2);
88
107
  }
89
108
  try {
90
- console.log(scratchDir(task, purpose));
109
+ console.log(scratchDir(task, purpose, { row }));
91
110
  } catch (error) {
92
111
  console.error(`scratch-dir: ${error instanceof Error ? error.message : String(error)}`);
93
112
  process.exit(1);
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // repo-kit's 3-day scratch sweep (meta REPO-DISK-PLAN DK6, was TEMP-HYGIENE T7). One copy lives in repo-kit; every org
2
+ // repo-kit's report-only scratch sweep (meta REPO-DISK-PLAN J358, was TEMP-HYGIENE T7). One copy lives in repo-kit; every org
3
3
  // repo carries a byte-identical copy at scripts/scratch-sweep.mjs, beside scratch-dir.mjs (DK3) and vite-tmp.mjs.
4
4
  //
5
- // node scripts/scratch-sweep.mjs [--live] [--root <repo>] [--days <n>]
5
+ // node scripts/scratch-sweep.mjs [--root <repo>] [--days <n>]
6
6
  //
7
7
  // It looks at each folder directly under <repo>/tmp/ and would remove one in which nothing (the folder or anything in
8
8
  // it) changed for <n> days (3 by default), with or without a DK3 `.owner`. It keeps:
@@ -11,12 +11,13 @@
11
11
  // - a folder that is, or holds, some process's cwd (lsof -d cwd; /proc on Linux); an unreadable table keeps all;
12
12
  // - a folder holding a Git root with dirty files or commits no remote has (DS14's list: the reason names the root);
13
13
  // - dot folders, symlinks, and `tmp/vitest` (vite-tmp.mjs's own).
14
- // Dry run is the default until Jake's yes (REPO-DISK decision 1) and a week of dry-run log; `--live` removes. Every
15
- // decision is appended to tmp/.sweep.log, one line each, and a summary line goes to stdout.
14
+ // J358 cancelled the 11-20 go-live: this script never removes files. Every decision is appended to
15
+ // tmp/.sweep.log, one line each, and a summary line goes to stdout for a human daily audit.
16
16
  import { spawnSync } from 'node:child_process';
17
- import { appendFileSync, lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync } from 'node:fs';
17
+ import { appendFileSync, lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';
18
18
  import { join, resolve, sep } from 'node:path';
19
19
  import { pathToFileURL } from 'node:url';
20
+ import { laneLive } from './lane-live.mjs';
20
21
 
21
22
  const DEFAULT_DAYS = 3;
22
23
  const MINUTES_A_DAY = 1440;
@@ -138,23 +139,14 @@ export function plan({ root, days = DEFAULT_DAYS, cwds = processCwds() }) {
138
139
  return rows;
139
140
  }
140
141
 
141
- /** Plans, logs every row to tmp/.sweep.log, and removes the planned folders when live.
142
- * @param {{ root: string, live?: boolean, days?: number, cwds?: readonly string[] | null, now?: Date }} options */
143
- export function sweep({ root, live = false, days = DEFAULT_DAYS, cwds, now = new Date() }) {
142
+ /** Plans and logs every row to tmp/.sweep.log. J358: humans, not this script, remove leftovers.
143
+ * @param {{ root: string, days?: number, cwds?: readonly string[] | null, now?: Date }} options */
144
+ export function sweep({ root, days = DEFAULT_DAYS, cwds, now = new Date() }) {
144
145
  const rows = plan({ root, days, ...(cwds === undefined ? {} : { cwds }) });
145
146
  const stamp = now.toISOString(), lines = [];
146
- let removed = 0;
147
147
  for (const row of rows) {
148
- let verb = row.action === 'keep' ? `keep (${row.reason})` : 'would remove';
149
- if (row.action === 'remove' && live) {
150
- try {
151
- rmSync(join(root, 'tmp', row.name), { recursive: true, force: true });
152
- verb = 'removed';
153
- removed += 1;
154
- } catch (error) {
155
- verb = `remove failed (${error instanceof Error ? error.message : String(error)})`;
156
- }
157
- }
148
+ const liveness = laneLive(join(root, 'tmp', row.name));
149
+ const verb = row.action === 'keep' ? `keep (${row.reason}; ${liveness.state}: ${liveness.reason})` : `leftover (manual audit; ${liveness.state}: ${liveness.reason})`;
158
150
  lines.push(`${stamp} ${verb} tmp/${row.name}${row.action === 'remove' ? ` (${row.reason})` : ''}\n`);
159
151
  }
160
152
  if (lines.length > 0) {
@@ -163,7 +155,7 @@ export function sweep({ root, live = false, days = DEFAULT_DAYS, cwds, now = new
163
155
  } catch {}
164
156
  }
165
157
  const planned = rows.filter(row => row.action === 'remove').length;
166
- return { rows, planned, removed };
158
+ return { rows, planned };
167
159
  }
168
160
 
169
161
  if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
@@ -175,8 +167,8 @@ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.a
175
167
  const days = Number(flag('--days') ?? DEFAULT_DAYS);
176
168
  if (!Number.isInteger(days) || days < 1) throw new Error('--days takes a whole number of days, 1 or more');
177
169
  const root = resolve(flag('--root') ?? resolve(import.meta.dirname, '..'));
178
- const live = args.includes('--live');
179
- const { rows, planned, removed } = sweep({ root, live, days });
170
+ if (args.includes('--live')) throw new Error('--live was removed by REPO-DISK J358: this command only reports leftovers');
171
+ const { rows, planned } = sweep({ root, days });
180
172
  const keptRows = rows.filter(row => row.action === 'keep');
181
- process.stdout.write(`scratch-sweep ${live ? 'live' : '(dry run)'} ${root}/tmp: ${live ? `removed ${String(removed)} of ${String(planned)}` : `would remove ${String(planned)}`}, kept ${String(keptRows.length)}; log tmp/.sweep.log\n`);
173
+ process.stdout.write(`scratch-sweep report ${root}/tmp: ${String(planned)} leftover(s) for manual audit, kept ${String(keptRows.length)}; log tmp/.sweep.log\n`);
182
174
  }