@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,209 @@
1
+ #!/usr/bin/env node
2
+ // Road lag (Jake, 2026-11-15: "Last time I tried going to the road, there was a lot of lag"): from a home cell, step out of its
3
+ // entryway onto the road and back in, by real input, a few times, and measure what the player feels at each line: every frame's
4
+ // time (requestAnimationFrame) in the window from 1 s before to 3 s after the feet cross, any loading card on screen in it, and the
5
+ // longest stretch under 90 % of the approach speed with the key held (the road bar's stop). One JSON per run, plus a printed line per crossing.
6
+ // scripts/browser-lane.sh node scripts/grid-road-lag.mjs --base=<staging, preview or loopback> --out=<dir> [--home=driftwood|nalati]
7
+ // [--viewport=2992x1434@2] [--reps=3] [--engine=chromium|webkit] [--run] (sprint) [--device='iPhone 15 Pro'] (a phone: its viewport, touch and agent)
8
+ // [--profile] (Chromium: the page thread's CPU profile over the first lap, with `at`, its start on the page's clock)
9
+ // On preview or a loopback page the walker is set 20 m inside the home cell's road-facing entryway by the in-page harness pose; on
10
+ // staging (an online seat can't be placed) only Driftwood is walked to its east entryway from the spawn. Never production (J205).
11
+ import { mkdirSync, writeFileSync } from 'node:fs';
12
+ import { join, resolve as absolute } from 'node:path';
13
+ import { chromium, devices, webkit } from 'playwright';
14
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
15
+ import { saveFixture } from './debug-settings.mjs';
16
+
17
+ /** @param {string} name @param {string} fallback */
18
+ const flag = (name, fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
19
+ /** A program row on a crossing's clock (`at`, its line), its `again` and `released` marks only when set. @param {any} r @param {number} at */
20
+ const programRow = (r, at) => ({ t: r.t - at, name: r.name, key: r.key, ...(r.again === true ? { again: true } : {}), ...(r.released === true ? { released: true } : {}) });
21
+ /** A row on a crossing's clock. @param {any} r @param {number} at */
22
+ const shifted = (r, at) => ({ ...r, t: r.t - at });
23
+ const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', '')), engineName = flag('engine', 'chromium'), device = flag('device', ''), run = process.argv.includes('--run'), profile = process.argv.includes('--profile'), reps = Number(flag('reps', '3'));
24
+ if (!/^https:\/\/(preview|staging)\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: grid-road-lag.mjs --base=<staging, preview or loopback url> --out=<dir> [--home=driftwood|nalati] [--viewport=WxH@dpr] [--reps=n]');
25
+ const online = base.includes('staging');
26
+ /** Each home's road-facing entryway (the middle of an edge, in the cell's own metres) and the yaw that walks out through it (the
27
+ * page's motor faces atan2(own - target): +x is -π/2, -x is π/2, +z is π, -z is 0). Driftwood's east faces Nalati, Nalati's west faces Driftwood. */
28
+ const HOMES = /** @type {Record<string, { slug: string, card: string, axis: 'x' | 'z', sign: number, approach: [number, number][] }>} */ ({
29
+ driftwood: { slug: 'driftwood-isle', card: 'Driftwood Isle', axis: 'x', sign: 1, approach: [[235, -194], [235, 0]] },
30
+ nalati: { slug: 'nalati-grasslands', card: 'Nalati Grasslands', axis: 'x', sign: -1, approach: [] },
31
+ sunscar: { slug: 'sunscar-dunes', card: 'Signal Dunes', axis: 'x', sign: 1, approach: [] },
32
+ pine: { slug: 'pine-hollow', card: 'Pine Hollow', axis: 'x', sign: 1, approach: [] } });
33
+ const homeName = flag('home', 'driftwood'), home = HOMES[homeName];
34
+ if (home === undefined) throw new Error(`No home ${homeName}: ${Object.keys(HOMES).join(', ')}`);
35
+ if (online && home.approach.length === 0) throw new Error(`${homeName} has no walked approach for an online seat: use preview or a loopback page`);
36
+ const desk = (/^(\d+)x(\d+)@([\d.]+)$/u.exec(flag('viewport', '2992x1434@2')) ?? [0, '2992', '1434', '2']).slice(1).map(Number);
37
+ const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
38
+ mkdirSync(out, { recursive: true });
39
+
40
+ const result = { base, home: home.slug, engine: engineName, viewport: `${String(desk[0])}x${String(desk[1])}@${String(desk[2])}`, at: new Date().toISOString(), build: '', crossings: /** @type {Record<string, unknown>[]} */ ([]), errors: /** @type {string[]} */ ([]), note: '', crossingTiming: /** @type {unknown} */ (null) };
41
+ const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
42
+ let code = 1;
43
+ try {
44
+ result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
45
+ const phone = device === '' ? undefined : devices[device];
46
+ if (device !== '' && phone === undefined) throw new Error(`No Playwright device ${device}`);
47
+ if (phone !== undefined) result.viewport = `${device} ${String(phone.viewport.width)}x${String(phone.viewport.height)}@${String(phone.deviceScaleFactor)}`;
48
+ const context = await browser.newContext(phone ?? { viewport: { width: desk[0] ?? 2992, height: desk[1] ?? 1434 }, deviceScaleFactor: desk[2] ?? 2 }), page = await context.newPage();
49
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
50
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
51
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
52
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { volume: 0 } });
53
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
54
+ await page.locator('.ws-main-select').click({ timeout: 120_000 });
55
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('roadlag'); await page.locator('#ws-name-box button[type=submit]').click(); }
56
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
57
+ const index = await page.evaluate(card => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes(card)), home.card);
58
+ if (index < 0) throw new Error(`No ${home.card} card`);
59
+ await page.locator('.ws-menu-dots i').nth(index).click();
60
+ await page.locator('.ws-menu-play').click();
61
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
62
+ await sleep(2000);
63
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
64
+ // every drawn frame [t, ms] and a 50 ms sample of where the feet are and what the screen shows
65
+ await page.evaluate(() => {
66
+ const W = /** @type {any} */ (window), q = W.__road = { frames: /** @type {number[][]} */ ([]), samples: /** @type {any[]} */ ([]), programs: /** @type {any[]} */ ([]), slowLinks: /** @type {any[]} */ ([]) };
67
+ // every shader program the renderer links, with when it was first seen: a crossing that compiles one stalls its frame
68
+ const known = new Set(W.__wildshard?.world?.game?.renderer?.info?.programs);
69
+ // a key linked once before and released since links again: `again` tells a re-link from a first link
70
+ const seenKeys = new Set([...known].map((/** @type {any} */ program) => String(program.cacheKey)));
71
+ let held = new Set(known);
72
+ // and every program whose first use blocked the page (a link the driver finished only when asked): which, and how long
73
+
74
+ const renderer = W.__wildshard?.world?.game?.renderer, gl = renderer?.getContext?.();
75
+ if (gl !== undefined) {
76
+ const ask = gl.getProgramParameter.bind(gl);
77
+ gl.getProgramParameter = (/** @type {WebGLProgram} */ handle, /** @type {number} */ name) => {
78
+ const t0 = performance.now(), value = ask(handle, name), ms = performance.now() - t0;
79
+ if (ms > 8) {
80
+ const all = renderer.info.programs ?? [], found = all.find((/** @type {any} */ row) => row.program === handle), key = String(found?.cacheKey ?? '');
81
+ // ZE2d: what this link differs in from the same material's programs already linked: the key's comma fields that differ
82
+ const custom = (/** @type {string} */ k) => k.slice(Math.max(0, k.lastIndexOf(',srgb,'))), head = (/** @type {string} */ k) => k.slice(0, Math.max(0, k.lastIndexOf(',srgb,')));
83
+ const fields = head(key).split(','), siblings = all.filter((/** @type {any} */ row) => row !== found && row.name === found?.name && custom(String(row.cacheKey)) === custom(key)).map((/** @type {any} */ row) => head(String(row.cacheKey)).split(','));
84
+ const diffs = siblings.slice(0, 4).map((/** @type {string[]} */ other) => other.length !== fields.length ? `len ${String(other.length)}/${String(fields.length)}` : fields.map((f, i) => f === other[i] ? null : `${String(i)}:${other[i] ?? ''}->${f}`).filter(x => x !== null).join(' '));
85
+ // who drew it
86
+ const owners = /** @type {string[]} */ ([]);
87
+ try { W.__wildshard.world.game.scene.traverse((/** @type {any} */ o) => { if (owners.length >= 3 || o.material === undefined) return; for (const m of Array.isArray(o.material) ? o.material : [o.material]) if (renderer.properties.get(m)?.currentProgram?.program === handle) { const n = []; for (let at = o; at !== null && at !== undefined && n.length < 5; at = at.parent) n.push(String(at.name === '' ? at.type : at.name)); owners.push(n.join('<')); } }); } catch { /* best effort */ }
88
+ q.slowLinks.push({ t: Math.round(t0), ms: Math.round(ms), name: String(found?.name ?? ''), fields: fields.length, tail: fields.slice(-24).join(','), diffs, owners, env: String(W.__wildshard.world.game.scene.environment?.image?.height ?? null) });
89
+ }
90
+ return value;
91
+ };
92
+ }
93
+ let last = performance.now();
94
+ const raf = (/** @type {number} */ now) => { q.frames.push([Math.round(now), Number((now - last).toFixed(1))]); last = now; requestAnimationFrame(raf); };
95
+ requestAnimationFrame(raf);
96
+ setInterval(() => { try {
97
+ const st = W.__wildshard.shard.grid.state(), p = W.__wildshard.world.player;
98
+ const wf = st.live?.live?.worldFeet ?? p.position;
99
+ const now = W.__wildshard.world.game?.renderer?.info?.programs ?? [];
100
+ for (const program of now) if (!known.has(program)) { known.add(program); const key = String(program.cacheKey ?? ''); q.programs.push({ t: Math.round(performance.now()), name: String(program.name ?? ''), key: key.length > 700 && !/creature|wildlife/u.test(String(program.name)) ? `${key.slice(0, 300)} … ${key.slice(-300)}` : key, again: seenKeys.has(key) }); seenKeys.add(key); }
101
+ const live = new Set(now);
102
+ for (const program of held) if (!live.has(program)) q.programs.push({ t: Math.round(performance.now()), name: String(program.name ?? ''), key: ((k) => k.length > 700 ? `${k.slice(0, 300)} … ${k.slice(-300)}` : k)(String(program.cacheKey ?? '')), released: true });
103
+ held = live;
104
+ q.samples.push({ t: Math.round(performance.now()), x: Number(wf.x.toFixed(2)), z: Number(wf.z.toFixed(2)), inside: st.inside, phase: st.live?.crossing?.phase ?? null, card: st.cellLoading ?? null, stage: st.cellStage ?? null, ready: st.live?.live?.gameplayReady, res: st.live?.live?.residents ?? null, cx: st.live?.live?.crossings ?? null, cur: st.live?.live?.current ?? null, hy: st.hybrid?.instance ?? null, hook: st.hybrid?.hook ?? null });
105
+ } catch (error) { q.samples.push({ err: String(error).slice(0, 700) }); } }, 50);
106
+ });
107
+ const sample = () => page.evaluate(() => { const rows = /** @type {any[]} */ (/** @type {any} */ (window).__road.samples); for (let at = rows.length - 1; at >= 0; at--) if (rows[at].err === undefined) return rows[at]; return undefined; });
108
+ const face = (/** @type {number} */ yaw) => page.evaluate(wanted => { /** @type {any} */ (window).__wildshard.world.player.yaw = wanted; }, yaw);
109
+ const edge = 250, along = home.axis;
110
+ if (online) {
111
+ await page.keyboard.down('ShiftLeft');
112
+ for (const [x, z] of home.approach) {
113
+ await page.keyboard.down('KeyW');
114
+ for (let ends = Date.now() + 90_000, near = Infinity; Date.now() < ends && near > 3; await sleep(250)) {
115
+ const at = await sample(); near = Math.hypot(at.x - x, at.z - z); await face(Math.atan2(at.x - x, at.z - z));
116
+ }
117
+ await page.keyboard.up('KeyW');
118
+ }
119
+ await page.keyboard.up('ShiftLeft');
120
+ } else {
121
+ const [x, z] = along === 'x' ? [home.sign * (edge - 20), 0] : [0, home.sign * (edge - 20)];
122
+ 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); }, [x, z]);
123
+ }
124
+ await sleep(4000);
125
+ // ZE2d: what the boot prelinked for the road before the first walk out: each road program's environment height and light
126
+ // fields (the key's 3, 4, 51, 52), and the environments the page and the root scene hold now
127
+ /** @type {any} */ (result).bootRoad = await page.evaluate(() => {
128
+ const W = /** @type {any} */ (window), game = W.__wildshard.world.game, height = (/** @type {any} */ t) => t?.image?.height ?? null;
129
+ const programs = (game.renderer.info.programs ?? []).filter((/** @type {any} */ p) => String(p.name).startsWith('grid-')).map((/** @type {any} */ p) => { const f = String(p.cacheKey).split(','); return `${String(p.name)} ${f[3] ?? ''} ${f[4] ?? ''} ${f[51] ?? ''} ${f[52] ?? ''}`; });
130
+ // and the home's creatures: each graph body's linked programs (key fields 3, 4, 51, 52) and the hidden warm rigs (DL24)
131
+ // parked anywhere in the page, by material
132
+ const creatures = (game.renderer.info.programs ?? []).filter((/** @type {any} */ p) => /creature|wildlife/u.test(String(p.name))).map((/** @type {any} */ p) => `${String(p.name)} ${String(p.cacheKey)}`);
133
+ const warm = /** @type {string[]} */ ([]);
134
+ for (const root of [game.scene, game.rootScene]) root?.traverse((/** @type {any} */ o) => { if (o.name !== 'creature-warm') return; o.traverse((/** @type {any} */ m) => { for (const mat of m.material === undefined ? [] : Array.isArray(m.material) ? m.material : [m.material]) warm.push(`${String(mat.name === '' ? mat.type : mat.name)}${(o.parent?.name ?? '') === '' ? '' : ` in ${String(o.parent.name)}`}`); }); });
135
+ return { programs, creatures, warm: [...new Set(warm)], scene: height(game.scene.environment), root: height(game.rootScene?.environment), exterior: W.__wildshard.shard.grid.exterior?.() ?? 'none', sameScene: game.scene === game.rootScene };
136
+ });
137
+ if (process.argv.includes('--reprelink')) {
138
+ await page.evaluate(() => { /** @type {any} */ (window).__wildshard.shard.grid.prelink(); });
139
+ await sleep(5000);
140
+ /** @type {any} */ (result).bootRoadAgain = await page.evaluate(() => (/** @type {any} */ (window).__wildshard.world.game.renderer.info.programs ?? []).filter((/** @type {any} */ p) => String(p.name).startsWith('grid-')).map((/** @type {any} */ p) => { const f = String(p.cacheKey).split(','); return `${String(p.name)} ${f[3] ?? ''} ${f[4] ?? ''} ${f[51] ?? ''} ${f[52] ?? ''}`; }));
141
+ }
142
+ // the walk's lines are in the home's own coordinates: world feet less the home cell's origin
143
+ const originAt = 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 }; });
144
+ const local = (/** @type {any} */ s) => s[along] - originAt[along];
145
+ const outward = along === 'x' ? (home.sign > 0 ? -Math.PI / 2 : Math.PI / 2) : (home.sign > 0 ? Math.PI : 0);
146
+ let heldUntil = Infinity;
147
+ const t = () => page.evaluate(() => Math.round(performance.now()));
148
+ /** Walk with W held until `done(sample)` or 40 s; returns the wall time it took. */
149
+ const walk = async (/** @type {number} */ yaw, /** @type {(s: any) => boolean} */ done) => {
150
+ await face(yaw); if (run) await page.keyboard.down('ShiftLeft'); await page.keyboard.down('KeyW');
151
+ const t0 = Date.now();
152
+ for (let s = await sample(); Date.now() - t0 < 40_000 && !done(s); s = await sample()) await sleep(100);
153
+ heldUntil = await t(); await page.keyboard.up('KeyW'); if (run) await page.keyboard.up('ShiftLeft'); return Date.now() - t0;
154
+ };
155
+ /** One crossing's numbers from the page's frames and samples around the first sample past the line */
156
+ const measure = async (/** @type {string} */ name, /** @type {number} */ fromT) => {
157
+ const { frames, samples, programs, slowLinks } = await page.evaluate(after => { const q = /** @type {any} */ (window).__road; return { slowLinks: /** @type {any[]} */ (q.slowLinks.filter((/** @type {any} */ r) => r.t >= after)), programs: /** @type {any[]} */ (q.programs.filter((/** @type {any} */ r) => r.t >= after)), frames: /** @type {number[][]} */ (q.frames.filter((/** @type {number[]} */ r) => (r[0] ?? 0) >= after)), samples: /** @type {any[]} */ (q.samples.filter((/** @type {any} */ r) => r.err === undefined && r.t >= after)) }; }, fromT);
158
+ const leaving = name.startsWith('out'), line = samples.find((s, i) => i > 0 && (leaving ? s.inside === null && samples[i - 1].inside !== null : s.inside === home.slug && samples[i - 1].inside !== home.slug));
159
+ if (line === undefined) return { name, crossed: false };
160
+ const span = frames.filter(r => (r[0] ?? 0) >= line.t - 1000 && (r[0] ?? 0) <= line.t + 3000).map(r => r[1] ?? 0), sorted = [...span].sort((a, b) => a - b);
161
+ const cards = samples.filter(s => s.t >= line.t - 1000 && s.t <= line.t + 3000 && s.card !== null);
162
+ // the road bar's stop: ground speed under 90 % of the approach's median, counted only while the key is held
163
+ let stop = 0, worstStop = 0;
164
+ const near = samples.filter(s => s.t >= line.t - 1000 && s.t <= line.t + 3000), held = near.filter(s => s.t <= heldUntil);
165
+ const speed = (/** @type {number} */ i) => Math.hypot(held[i].x - held[i - 1].x, held[i].z - held[i - 1].z) / Math.max(1, held[i].t - held[i - 1].t);
166
+ const approach = held.map((_, i) => i > 0 && held[i].t < line.t - 200 ? speed(i) : Number.NaN).filter(v => Number.isFinite(v)).sort((a, b) => a - b), cruise = approach[Math.floor(approach.length / 2)] ?? 0;
167
+ let stopAt = null;
168
+ // a walk that starts within the window starts from rest: count only once the feet first reach the approach's speed
169
+ for (let i = 1, moving = false; i < held.length; i++) { const slow = speed(i) < cruise * 0.9; moving ||= !slow; if (!moving) continue; stop = slow ? stop + (held[i].t - held[i - 1].t) : 0; if (stop > worstStop) { worstStop = stop; stopAt = { endsMs: held[i].t - line.t, x: held[i].x, z: held[i].z }; } }
170
+ return { name, crossed: true, lineAt: line.t, frames: span.length, worstFrameMs: sorted.at(-1) ?? 0, p95Ms: sorted[Math.floor(sorted.length * 0.95)] ?? 0, medianMs: sorted[Math.floor(sorted.length / 2)] ?? 0,
171
+ over33: span.filter(ms => ms > 33.4).length, over50: span.filter(ms => ms > 50).length, over100: span.filter(ms => ms > 100).length,
172
+ trace: near.filter((_, i) => i % 2 === 0).map(s => [s.t - line.t, s.x, s.z, s.inside, s.cur, s.cx, s.phase, s.card, s.stage, s.res, s.hy, s.hook]), cardMs: cards.length * 50, cards: [...new Set(cards.map(s => `${String(s.card)}:${String(s.stage)}`))], worstStopMs: worstStop, stopAt, cruiseMps: Number((cruise * 1000).toFixed(2)), phases: [...new Set(near.map(s => s.phase))],
173
+ programs: programs.filter(r => r.t >= line.t - 1000 && r.t <= line.t + 3000).map(r => programRow(r, line.t)),
174
+ releasedBefore: programs.filter(r => r.released === true && r.t < line.t - 1000).map(r => ({ t: r.t - line.t, name: r.name, key: r.key })),
175
+ slowLinks: slowLinks.filter(r => r.t >= line.t - 1000 && r.t <= line.t + 3000).map(r => shifted(r, line.t)) };
176
+ };
177
+ const cdp = profile && engineName === 'chromium' ? await context.newCDPSession(page) : undefined;
178
+ let profileAt = 0;
179
+ // --profile-lap=<n>: the profile covers that lap (default the first; a later lap shows what a warm page still pays)
180
+ const profileLap = Number(flag('profile-lap', '1'));
181
+ if (cdp !== undefined) await cdp.send('Profiler.enable');
182
+ for (let rep = 1; rep <= reps; rep++) {
183
+ if (cdp !== undefined && rep === profileLap) { await cdp.send('Profiler.setSamplingInterval', { interval: 250 }); await cdp.send('Profiler.start'); profileAt = await t(); }
184
+ let from = await t();
185
+ await walk(outward, s => s.inside === null && Math.abs(local(s)) >= edge + 12);
186
+ await sleep(2500);
187
+ result.crossings.push({ rep, ...await measure('out (cell to road)', from) });
188
+ from = await t();
189
+ await walk(outward + Math.PI, s => s.inside === home.slug && Math.abs(local(s)) <= edge - 12);
190
+ await sleep(2500);
191
+ result.crossings.push({ rep, ...await measure('back (road to cell)', from) });
192
+ if (cdp !== undefined && rep === profileLap) {
193
+ const { profile: taken } = await cdp.send('Profiler.stop');
194
+ writeFileSync(join(out, `${engineName}${device === '' ? '' : '-phone'}${run ? '-run' : ''}-${homeName}-lap${String(profileLap)}.cpuprofile.json`), JSON.stringify({ at: profileAt, base, profile: taken }));
195
+ }
196
+ for (const row of result.crossings.slice(-2)) console.log(`${row.crossed === true ? 'ok ' : 'FAIL'} ${homeName} rep ${String(rep)} ${String(row.name)} ${JSON.stringify({ worst: row.worstFrameMs, p95: row.p95Ms, over50: row.over50, over100: row.over100, card: row.cardMs, stop: row.worstStopMs })}`);
197
+ }
198
+ await page.screenshot({ path: join(out, `${engineName}${device === '' ? '' : '-phone'}${run ? '-run' : ''}-${homeName}-road-lag.png`) });
199
+ // ZE2d: every road program the run linked or released, by page time (the crossings' `lineAt` place them)
200
+ /** @type {any} */ (result).roadPrograms = await page.evaluate(() => /** @type {any[]} */ (/** @type {any} */ (window).__road.programs).filter(p => String(p.name).startsWith('grid-') || p.name === '').map(p => { const f = String(p.key).split(','); return `${String(p.t)} ${String(p.name)} ${f[3] ?? ''} ${f[4] ?? ''} ${f[51] ?? ''} ${f[52] ?? ''}${p.released === undefined ? '' : ' released'}`; }));
201
+ result.crossingTiming = await page.evaluate(() => /** @type {any} */ (window).__wildshard.shard.grid.state().live?.crossingTiming ?? null);
202
+ await context.close();
203
+ code = result.crossings.every(row => row.crossed === true) && result.errors.length === 0 ? 0 : 1;
204
+ } catch (error) { result.note = String(error).slice(0, 400); console.log(`FAIL ${result.note}`); }
205
+ finally {
206
+ writeFileSync(join(out, `${engineName}${device === '' ? '' : '-phone'}${run ? '-run' : ''}-${homeName}-road-lag.json`), `${JSON.stringify(result, null, 2)}\n`);
207
+ await browser.close();
208
+ }
209
+ process.exit(code);
@@ -3,14 +3,18 @@
3
3
  // helper only writes a copy; it has no delete operation.
4
4
  import { spawnSync } from 'node:child_process';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, writeFileSync } from 'node:fs';
6
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, writeFileSync } from 'node:fs';
7
7
  import { homedir } from 'node:os';
8
- import { basename, join, resolve } from 'node:path';
8
+ import { basename, dirname, join, resolve, sep } from 'node:path';
9
9
  import { pathToFileURL } from 'node:url';
10
10
 
11
11
  const MAX_UNTRACKED_BYTES = 50 * 1024 * 1024;
12
12
  const DEFAULT_KEEP_ROOT = join(homedir(), '.cache/wildshard/session-keep');
13
13
  const RETENTION_DAYS = 14;
14
+ const RAW_PATCH = ['--binary', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
15
+ // Declared build/install outputs are regenerable. Other ignored files, including
16
+ // tmp captures and owner metadata, must be copied or make removal fail closed.
17
+ const REGENERABLE = /^(?:(?:node_modules|dist(?:-[^/]+)?|out|build|coverage|\.bin-deps|\.tsc-layers|\.cache|\.vite|test-results|playwright-report|blob-report)\/|public\/(?:assets\/(?:packs|physics|gpu)|basis|shardfiles)\/)|(?:^|\/)[^/]+\.(?:tsbuildinfo|generated\.ts)$/u;
14
18
 
15
19
  /** @param {string} cwd @param {string[]} args */
16
20
  const run = (cwd, args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
@@ -21,6 +25,15 @@ const text = (cwd, args) => {
21
25
  return result.stdout;
22
26
  };
23
27
 
28
+ /** A patch is a byte stream: text diffs may contain non-UTF-8 source bytes.
29
+ * @param {string} root @param {boolean} [cached] */
30
+ function rawPatch(root, cached = false) {
31
+ const args = ['-C', root, 'diff', ...(cached ? ['--cached'] : []), ...RAW_PATCH, 'HEAD'];
32
+ const result = spawnSync('git', args, { maxBuffer: 64 * 1024 * 1024 });
33
+ if (result.status !== 0) throw new Error(`keep-copy: raw patch failed: ${result.stderr?.toString('utf8')}`);
34
+ return result.stdout;
35
+ }
36
+
24
37
  /** @param {string} path @param {string} root @param {Date} now */
25
38
  function destination(path, root, now) {
26
39
  const day = now.toISOString().slice(0, 10);
@@ -28,17 +41,53 @@ function destination(path, root, now) {
28
41
  return join(root, day, `${basename(path)}__${process.pid}-${stamp}-${randomUUID()}`);
29
42
  }
30
43
 
44
+ /** Resolve existing symlink ancestors before any destination directory is made.
45
+ * @param {string} path */
46
+ function physicalPath(path) {
47
+ let ancestor = resolve(path);
48
+ const tail = [];
49
+ while (!existsSync(ancestor)) {
50
+ tail.unshift(basename(ancestor));
51
+ ancestor = dirname(ancestor);
52
+ }
53
+ return resolve(realpathSync(ancestor), ...tail);
54
+ }
55
+
56
+ /** @param {string} source @param {string} target */
57
+ function requireExternalCopy(source, target) {
58
+ if (target === source || target.startsWith(source + sep))
59
+ throw new Error('keep-copy: destination must stay outside the source removal tree');
60
+ }
61
+
31
62
  /** @param {string} path @param {string[]} files */
32
63
  function bytes(path, files) {
33
64
  return files.reduce((total, file) => total + lstatSync(join(path, file)).size, 0);
34
65
  }
35
66
 
67
+ /** Include ignored evidence without walking known generated outputs or symlinks.
68
+ * @param {string} root */
69
+ function recoverableFiles(root) {
70
+ const files = new Set(text(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean));
71
+ const visit = (/** @type {string} */ file) => {
72
+ const info = lstatSync(join(root, file));
73
+ if (info.isDirectory()) {
74
+ for (const name of readdirSync(join(root, file))) visit(join(file, name));
75
+ } else if (info.isFile() || info.isSymbolicLink()) files.add(file);
76
+ else throw new Error(`keep-copy: cannot preserve ${file}; source must be kept`);
77
+ };
78
+ for (const file of text(root, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '--no-empty-directory', '-z']).split('\0').filter(Boolean))
79
+ if (!REGENERABLE.test(file)) visit(file.replace(/\/$/u, ''));
80
+ const list = [...files].sort();
81
+ if (bytes(root, list) > MAX_UNTRACKED_BYTES) throw new Error('keep-copy: recoverable files exceed 50 MiB; source must be kept');
82
+ return list;
83
+ }
84
+
36
85
  /** Snapshot every recoverable byte before copying and again after stopping
37
86
  * writers. Status alone misses edits within an existing untracked folder.
38
87
  * @param {string} root */
39
88
  export function worktreeState(root) {
40
89
  const hash = createHash('sha256');
41
- for (const file of text(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean)) {
90
+ for (const file of recoverableFiles(root)) {
42
91
  const path = join(root, file), info = lstatSync(path);
43
92
  if (!info.isFile() && !info.isSymbolicLink()) throw new Error(`cannot snapshot ${file}`);
44
93
  hash.update(JSON.stringify([file, info.mode, info.size]));
@@ -47,7 +96,7 @@ export function worktreeState(root) {
47
96
  return JSON.stringify([
48
97
  text(root, ['rev-parse', 'HEAD']), text(root, ['symbolic-ref', '--quiet', 'HEAD']),
49
98
  text(root, ['status', '--porcelain', '--untracked-files=all']),
50
- text(root, ['diff', '--binary', 'HEAD']), text(root, ['diff', '--cached', '--binary', 'HEAD']),
99
+ createHash('sha256').update(rawPatch(root)).digest('hex'), createHash('sha256').update(rawPatch(root, true)).digest('hex'),
51
100
  hash.digest('hex'),
52
101
  ]);
53
102
  }
@@ -58,28 +107,31 @@ export function keepCopy(path, { keepRoot = DEFAULT_KEEP_ROOT, now = new Date()
58
107
  const root = resolve(path);
59
108
  if (!existsSync(root)) throw new Error(`keep-copy: ${root} does not exist`);
60
109
  const repo = text(root, ['rev-parse', '--show-toplevel']).trim();
61
- const files = text(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean);
110
+ const source = realpathSync(root);
111
+ requireExternalCopy(source, physicalPath(keepRoot));
112
+ const files = recoverableFiles(root);
62
113
  const dir = destination(root, resolve(keepRoot), now);
63
114
  mkdirSync(dir, { recursive: true });
115
+ requireExternalCopy(source, realpathSync(dir));
64
116
  /** @type {{source:string,repository:string,created:string,bundle:boolean,patch:boolean,untracked:string|{files:number,bytes:number}}} */
65
117
  const manifest = { source: root, repository: repo, created: now.toISOString(), bundle: false, patch: false, untracked: 'none' };
66
- const unpublished = run(root, ['log', '--branches', '--tags', '--not', '--remotes', '--format=%H']);
118
+ const unpublished = run(root, ['log', 'HEAD', '--branches', '--tags', '--not', '--remotes', '--format=%H']);
67
119
  if (unpublished.status !== 0) throw new Error(`keep-copy: cannot inspect unpublished commits: ${unpublished.stderr.trim()}`);
68
120
  if (unpublished.stdout.trim() !== '') {
69
- text(root, ['bundle', 'create', join(dir, 'unpublished.bundle'), '--branches', '--tags', '--not', '--remotes']);
121
+ text(root, ['bundle', 'create', join(dir, 'unpublished.bundle'), 'HEAD', '--branches', '--tags', '--not', '--remotes']);
70
122
  manifest.bundle = true;
71
123
  }
72
- const patch = text(root, ['diff', '--binary', 'HEAD']);
73
- const indexPatch = text(root, ['diff', '--cached', '--binary', 'HEAD']);
74
- if (indexPatch !== '') writeFileSync(join(dir, 'index.patch'), indexPatch);
75
- if (patch !== '') {
124
+ const patch = rawPatch(root);
125
+ const indexPatch = rawPatch(root, true);
126
+ if (indexPatch.length > 0) writeFileSync(join(dir, 'index.patch'), indexPatch);
127
+ if (patch.length > 0) {
76
128
  writeFileSync(join(dir, 'tracked.patch'), patch);
77
129
  manifest.patch = true;
78
130
  }
79
131
  if (files.length > 0) {
80
132
  const total = bytes(root, files);
81
133
  if (total <= MAX_UNTRACKED_BYTES) {
82
- const archive = spawnSync('tar', ['-czf', join(dir, 'untracked.tgz'), '--', ...files], { cwd: root, encoding: 'utf8' });
134
+ const archive = spawnSync('tar', ['-czf', join(dir, 'untracked.tgz'), '--null', '-T', '-'], { cwd: root, input: `${files.join('\0')}\0`, encoding: 'utf8' });
83
135
  if (archive.status !== 0) throw new Error(`keep-copy: tar failed: ${archive.stderr.trim()}`);
84
136
  manifest.untracked = { files: files.length, bytes: total };
85
137
  } else throw new Error('keep-copy: untracked files exceed 50 MiB; source must be kept');
@@ -2,7 +2,10 @@ import type { SpawnSyncReturns } from 'node:child_process';
2
2
 
3
3
  export const LAND_WORKFLOWS: readonly string[];
4
4
  export function githubSlug(remote: string): string | null;
5
- export function parseArgs(argv: string[]): { pollSeconds: number; timeoutMinutes: number; appearMinutes: number; rounds: number; watchMain: boolean };
5
+ export function parseArgs(argv: string[]): { pollSeconds: number; timeoutMinutes: number; appearMinutes: number; rounds: number; keep: boolean; preflight: boolean };
6
+ export function preflightSteps(files: string[]): [string, string[]][];
7
+ export const CHECK_CSS: string;
8
+ export const PINS_LEDGER: string;
6
9
  export function classifyRebase(cwd: string, range: { tested: string; base: string; head: string; main: string }): { rule: 'carried' | 'rerun'; reason: string; stamp?: boolean };
7
10
  export function shaVerdict(data: unknown, sha: string): { state: 'pending' | 'green' | 'red'; runs: Record<string, { id: number; status: string; conclusion: string | null; branch: string; url: string; attempt: number }>; summary: string };
8
11
  export function failedJobs(data: unknown): { blocking: string[]; nonblocking: string[] };
package/scripts/land.mjs CHANGED
@@ -13,6 +13,10 @@
13
13
  // 6. Fast-forward the canonical checkout when it is on main and clean (J247, WL7).
14
14
  // 7. A `landed` receipt; main-watch follows main's own `ci` and reports it (LS5).
15
15
  // 8. Delete origin's plan branch and remove this worktree (--keep skips it).
16
+ // Before gen:inputs, a worktree that never ran `pnpm pins` runs it. Before step 2's push, a preflight runs lint:game,
17
+ // check-css, typecheck and the Vitest files related to the branch's changed code,
18
+ // here, and stops on the first red with its log (BUILD-MAX 2026-11-15: 14 of 22 stopped lands failed a check that runs
19
+ // locally, each after a push and a wait). --no-preflight skips it.
16
20
  // Main's CI runs after every landing; if it goes red, the lane that landed last fixes it forward or reverts it.
17
21
  import {execFileSync,spawn,spawnSync} from 'node:child_process';
18
22
  import {keepCopy,worktreeState} from './keep-copy.mjs';
@@ -88,6 +92,24 @@ function gitTee(cwd,args,env){
88
92
  const git=(cwd,args,env=process.env)=>execFileSync('git',args,{cwd,env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:64<<20}).trim();
89
93
  /** @param {string} cwd @param {string[]} args @param {NodeJS.ProcessEnv} [env] */
90
94
  const tryGit=(cwd,args,env=process.env)=>spawnSync('git',args,{cwd,env,encoding:'utf8',maxBuffer:64<<20});
95
+
96
+ /** WL12: a recent small branch merits a mode reminder, never a refusal.
97
+ * Reflog selectors carry branch-event time; commit time can predate branch creation.
98
+ * Missing/expired local reflogs cannot establish age and produce no warning.
99
+ * @param {string} root @param {string} branch @param {number} [now] @returns {string|null} */
100
+ export function smallPlanWarning(root,branch,now=Date.now()){
101
+ if(!PLAN_BRANCH.test(branch))return null;
102
+ const count=tryGit(root,['rev-list','--count',`origin/main..${branch}`]);
103
+ if(count.status!==0)return null;
104
+ const commits=Number(count.stdout.trim());
105
+ if(!Number.isSafeInteger(commits)||commits<1||commits>3)return null;
106
+ const history=tryGit(root,['reflog','show','--date=unix','--format=%gD%x09%gs',`refs/heads/${branch}`]);
107
+ if(history.status!==0)return null;
108
+ const first=history.stdout.trim().split('\n').at(-1)??'';
109
+ const created=Number(/@\{(\d+)\}\tbranch: Created from .+$/u.exec(first)?.[1])*1000,age=now-created;
110
+ if(!Number.isFinite(created)||!Number.isFinite(age)||age<0||age>=3*60*60*1000)return null;
111
+ return `WARNING one-row land (J290): commit on main next time (${commits} commit${commits===1?'':'s'}, ${Math.floor(age/60_000)} min old; J336: land a whole plan once)`;
112
+ }
91
113
  /** A ref lock another git process holds or just moved: worktrees share refs, so two lands fetching main at once race
92
114
  * for refs/remotes/origin/main ("cannot lock ref ...: is at X but expected Y", engine run 43332891983), and any git
93
115
  * may hold packed-refs.lock for a moment. Only these are retried; every other git failure stops as before. */
@@ -109,6 +131,22 @@ const isAncestor=(cwd,ancestor,descendant)=>tryGit(cwd,['merge-base','--is-ances
109
131
  /** @param {string} cwd @param {string} from @param {string} to */
110
132
  const short=(/** @type {string} */ sha)=>sha.slice(0,10);
111
133
 
134
+ /** CI's `check css` (scripts/ci-static.sh). A tree without it (a fixture, another repo's land) skips the step. */
135
+ export const CHECK_CSS='scripts/check-css.mjs';
136
+ /** What `pnpm pins` leaves (scripts/pins.ts LEDGER). Without it gen.mjs --inputs-only fails, so land runs pins first. */
137
+ export const PINS_LEDGER='out/.pins.json';
138
+
139
+ /** The preflight's checks, in order, as [name, argv], for a branch whose diff from main is `files` (BUILD-MAX 2026-11-15).
140
+ * check-css is a check CI's static job runs and the pre-push does not (it cost opus-gcm11 a 27-minute re-run). Vitest
141
+ * runs only when code changed, on the tests related to that code (`vitest related`, which includes a changed test itself).
142
+ * @param {string[]} files @returns {[string,string[]][]} */
143
+ export function preflightSteps(files){
144
+ const code=files.filter(file=>/^(?:src|test|scripts)\/.+\.[cm]?[jt]sx?$/u.test(file));
145
+ /** @type {[string,string[]][]} */const steps=[['lint:game',['pnpm','lint:game']],['check-css',['node',CHECK_CSS]],['typecheck',['pnpm','typecheck']]];
146
+ if(code.length>0)steps.push(['vitest',['pnpm','exec','vitest','related','--run','--passWithNoTests',...code]]);
147
+ return steps;
148
+ }
149
+
112
150
  /** `owner/name` of a GitHub remote URL, or null.
113
151
  * @param {string} remote */
114
152
  export function githubSlug(remote){
@@ -119,7 +157,7 @@ export function githubSlug(remote){
119
157
  /** Refuse anything but the known options. Any spelling of force is refused by name.
120
158
  * @param {string[]} argv */
121
159
  export function parseArgs(argv){
122
- const options={pollSeconds:30,timeoutMinutes:60,appearMinutes:5,rounds:5,keep:false};
160
+ const options={pollSeconds:30,timeoutMinutes:60,appearMinutes:5,rounds:5,keep:false,preflight:true};
123
161
  for(const arg of argv){
124
162
  if(/^-f$|force/iu.test(arg))throw new StopError(`refused ${arg}: land never force-pushes main (J240: fast-forward only). If main moved, land rebases and retries by itself`);
125
163
  const [name,value]=arg.split('=',2);
@@ -127,11 +165,12 @@ export function parseArgs(argv){
127
165
  // --no-watch-main is accepted for old callers: land never watches main now (LS8).
128
166
  if(name==='--no-watch-main'&&value===undefined)continue;
129
167
  if(name==='--keep'&&value===undefined)options.keep=true;
168
+ else if(name==='--no-preflight'&&value===undefined)options.preflight=false;
130
169
  else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--poll')options.pollSeconds=number;
131
170
  else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--timeout')options.timeoutMinutes=number;
132
171
  else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--appear')options.appearMinutes=number;
133
172
  else if(value!==undefined&&Number.isSafeInteger(number)&&number>0&&name==='--rounds')options.rounds=number;
134
- else throw new StopError(`unknown option ${arg}; usage: node scripts/land.mjs [--poll=SECONDS] [--timeout=MINUTES] [--appear=MINUTES] [--rounds=N] [--keep]`);
173
+ else throw new StopError(`unknown option ${arg}; usage: node scripts/land.mjs [--poll=SECONDS] [--timeout=MINUTES] [--appear=MINUTES] [--rounds=N] [--keep] [--no-preflight]`);
135
174
  }
136
175
  return options;
137
176
  }
@@ -310,6 +349,7 @@ class Landing{
310
349
  /** @type {string|null} */this.planTip=null;
311
350
  this.expected='';
312
351
  /** @type {string|null} */this.landedSha=null;
352
+ /** @type {string|null} */this.sizeWarning=null;
313
353
  }
314
354
 
315
355
  /** @type {(why:string)=>void} */
@@ -715,12 +755,52 @@ class Landing{
715
755
  throw new StopError(`main push of ${short(head)} failed and main did not move: ${result.stdout.trim()}\nA red pre-push names its failing check above; fix forward and run land again.`);
716
756
  }
717
757
 
758
+ /** lint:game, typecheck and the related Vitest files, here, before anything is pushed; the first red stops land with
759
+ * its log. The logs live in this worktree's git dir, so they never dirty the tree and go when the worktree does.
760
+ * @param {string} main */
761
+ localChecks(main){
762
+ if(!this.options.preflight){this.say('preflight','skipped (--no-preflight)');return;}
763
+ const head=this.head(),files=git(this.root,['diff','--name-only','--no-renames',`${main}...${head}`]).split('\n').filter(Boolean);
764
+ const dir=resolve(this.root,git(this.root,['rev-parse','--git-path','land-preflight']));
765
+ mkdirSync(dir,{recursive:true});
766
+ for(const [name,[command,...args]] of preflightSteps(files)){
767
+ if(command==='node'&&!existsSync(join(this.root,args[0]??''))){this.say('preflight',`${name} skipped: no ${args[0]} here`);continue;}
768
+ const log=join(dir,`${short(head)}-${name.replace(':','-')}.log`),began=Date.now();
769
+ this.say('preflight',`${name} on ${short(head)}`);
770
+ const ran=spawnSync(command==='node'?process.execPath:command??'pnpm',args,{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:256<<20});
771
+ writeFileSync(log,`$ ${command} ${args.join(' ')}\n${ran.stdout??''}${ran.stderr??''}${ran.error===undefined?'':`\n${String(ran.error)}\n`}`);
772
+ if(ran.status!==0){
773
+ this.receipt(`STOP preflight ${name} red on ${short(head)}, nothing pushed: ${log}`);
774
+ throw new StopError(`preflight ${name} is red on ${short(head)}; nothing was pushed. Log: ${log}\nFix it on ${this.branch} and run land again (--no-preflight skips the preflight).`);
775
+ }
776
+ this.say('preflight',`${name} green in ${String(Math.round((Date.now()-began)/1000))} s`);
777
+ }
778
+ }
779
+
780
+ /** A worktree that never ran `pnpm pins` has no PINS_LEDGER, and gen:inputs fails on it (opus-gcm11, 2026-11-15). Run it
781
+ * once, before gen:inputs; with or without --no-preflight, since gen:inputs needs it either way. */
782
+ pinsOnce(){
783
+ /** @type {{pins?:string}} */let scripts={};
784
+ try{scripts=JSON.parse(readFileSync(join(this.root,'package.json'),'utf8')).scripts??{};}catch{return;}
785
+ if(scripts.pins===undefined||existsSync(join(this.root,PINS_LEDGER)))return;
786
+ this.say('pins',`no ${PINS_LEDGER}: this worktree never ran pnpm pins; running it before gen:inputs`);
787
+ const ran=spawnSync('pnpm',['--silent','pins'],{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:256<<20});
788
+ if(ran.status!==0){
789
+ const why=`${ran.stderr??''}${ran.stdout??''}`.trim().split('\n').slice(-3).join(' | ')||String(ran.error??`exit ${String(ran.status)}`);
790
+ this.receipt(`STOP pnpm pins failed before gen:inputs: ${why}`);
791
+ throw new StopError(`pnpm pins failed in ${this.root} (gen:inputs needs its outputs); nothing was pushed: ${why}`);
792
+ }
793
+ this.say('pins',`pnpm pins done; ${PINS_LEDGER} written`);
794
+ }
795
+
718
796
  async run(){
719
797
  const stamps=this.clean();
720
798
  const start=this.head();this.expected=start;
721
799
  let main=this.fetchMain();
722
800
  if(start===main||isAncestor(this.root,start,main)){this.say('nothing',`${this.branch} ${short(start)} has nothing main lacks`);return 0;}
723
801
  this.say('start',`${this.branch} ${short(start)} -> main ${short(main)} (repo ${this.repo})`);
802
+ this.sizeWarning=smallPlanWarning(this.root,this.branch);
803
+ if(this.sizeWarning!==null){this.say('warning',this.sizeWarning);this.receipt(`small-plan warning: ${this.sizeWarning}`);}
724
804
  // An install a stopped land owed (its rebase had already moved HEAD) runs before anything else (J206 review).
725
805
  if(existsSync(this.installMarker()))this.install(['an earlier land\'s rebase']);
726
806
  // DS22: gen:inputs rewrites the stamps from the tree after the rebase, so their stale bytes never block it.
@@ -733,7 +813,9 @@ class Landing{
733
813
  this.rebase(main);
734
814
  if(this.head()===main){this.say('nothing',`every commit on ${this.branch} is already on main`);return 0;}
735
815
  }
816
+ this.pinsOnce();
736
817
  this.regenerate();
818
+ this.localChecks(main);
737
819
  /** @type {{sha:string,base:string}|null} */let tested=null;
738
820
  let needHosted=true,rule='exact',why='main had not moved since the hosted run';
739
821
  for(let round=1;round<=this.options.rounds;round++){
@@ -884,7 +966,7 @@ class Landing{
884
966
  this.startWatcher(head);
885
967
  this.say('rule',`main's own CI runs on ${short(head)} now. If it goes red, the lane that landed last fixes it forward or reverts it, at once (J249)`);
886
968
  const seconds=Math.round((Date.now()-this.started)/1000);
887
- this.receipt(`landed ${short(head)} on main (${short(before)}..${short(head)}); ${rule}; rounds ${round}; branch ci ${this.runs.join(', ')||'none'}; main ci ${rule==='carried'?'followed by main-watch':'reuses the branch run'}; ${seconds} s`);
969
+ this.receipt(`landed ${short(head)} on main (${short(before)}..${short(head)}); ${rule}; rounds ${round}; branch ci ${this.runs.join(', ')||'none'}; main ci ${rule==='carried'?'followed by main-watch':'reuses the branch run'}${this.sizeWarning===null?'':'; one-row'}; ${seconds} s`);
888
970
  return 0;
889
971
  }
890
972
  }
@@ -39,6 +39,8 @@ try {
39
39
  : await browser.newContext({ viewport: { width: Number(desktop[1]), height: Number(desktop[2]) }, deviceScaleFactor: Number(desktop[3]) });
40
40
  await developerSettings(context, { tier: desktop === null ? 'phone' : 'desktop', volume: 0 });
41
41
  await saveFixture(context, { scope: 'global', key: 'gfx', data: { dpr: values.dpr ?? '2', aa: 'auto' } });
42
+ // MOBILE-GRAPHICS MG8: the phone's pixel density is Settings ▸ Graphics' device knob now; the old `gfx` pick alone left --dpr 1 drawing at 2
43
+ await saveFixture(context, { scope: 'device', key: 'gfx.knob.density', data: Number(values.dpr ?? '2') });
42
44
  for (const fixture of levelDownloadFixtures('packs')) await saveFixture(context, fixture);
43
45
  // a phone's first PLAY goes straight to Driftwood's first-play card (MOBILE-GRAPHICS MG5): this device has done it
44
46
  await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
@@ -10,12 +10,12 @@ import { shardSourceDir, shardSourceFolders } from './shard-outputs.mjs';
10
10
 
11
11
  // Sharp resolves from this file: engine's own devDependency here, the consumer's through the optional
12
12
  // `sharp` peer when a shard repo or sharddev runs this script from its install of engine.
13
- const sharp = createRequire(import.meta.url)('sharp');
14
13
 
15
14
  /** Hash decoded sRGB RGBA8 pixels and their dimensions, independent of image encoding and metadata.
16
15
  * This binds a stamp to its raster; world freshness still requires the official map bake.
17
16
  * @param {string} image @returns {Promise<string>} */
18
17
  export async function mapPixelHash(image) {
18
+ const sharp = createRequire(import.meta.url)('sharp');
19
19
  // Decode these exact bytes: libvips' filename cache can retain a previous
20
20
  // raster when an official bake replaces the same path within one clock tick.
21
21
  const { data, info } = await sharp(readFileSync(image), { limitInputPixels: 4096 * 4096, animated: false, failOn: 'warning' })
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Optional promotion helper. The schedule never tags; J184 leaves promotion in charge.
2
+ // Optional promotion helper. A nightly selects a release cut point; release.sh owns branches and tags.
3
3
  // J167: require the downloaded exact-SHA green nightly verdict before any network/write.
4
4
  // A commit that already has a version tag is left alone: an unchanged tree needs no second release.
5
5
  import { execFileSync } from 'node:child_process';
@@ -25,8 +25,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
25
25
  if (git('tag', '--points-at', 'HEAD').split('\n').some((tag) => /^v\d/u.test(tag))) console.log('This commit is already tagged');
26
26
  else {
27
27
  const tag = nextTag(git('tag', '--list', 'v*').split('\n'));
28
- git('tag', tag);
29
- git('push', 'origin', tag);
30
- console.log(`Tagged ${tag}`);
28
+ console.log(`release.sh ${tag} --prepare --from ${git('rev-parse', 'HEAD')}`);
31
29
  }
32
30
  }