@wildshard/engine 0.1.17 → 0.1.18

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 (83) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +7 -0
  3. package/lint/host-callback-syntax.mjs +2 -1
  4. package/lint/host-callbacks.mjs +3 -3
  5. package/lint/host-files.mjs +5 -4
  6. package/lint/no-base64.mjs +3 -1
  7. package/lint/shard-imports.mjs +6 -7
  8. package/lint/shard-source.d.mts +9 -0
  9. package/lint/shard-source.mjs +91 -0
  10. package/lint/shardfile-boundaries.mjs +10 -8
  11. package/lint/sim-closure.mjs +6 -3
  12. package/lint/wildshard-plugin.d.ts +4 -0
  13. package/lint/wildshard-plugin.js +22 -23
  14. package/package.json +9 -2
  15. package/scripts/app-build/outputProducts.d.mts +3 -0
  16. package/scripts/app-build/outputProducts.mjs +31 -0
  17. package/scripts/app-build-pipeline.mjs +3 -0
  18. package/scripts/check-devserver.mjs +1 -1
  19. package/scripts/chromium-keychain-check.mjs +4 -2
  20. package/scripts/chromium-keychain.mjs +3 -1
  21. package/scripts/cook.mjs +7 -3
  22. package/scripts/devices.d.mts +4 -0
  23. package/scripts/devices.mjs +39 -0
  24. package/scripts/devserver-client.d.mts +4 -2
  25. package/scripts/devserver-client.mjs +25 -8
  26. package/scripts/doctor-proof.mjs +1 -1
  27. package/scripts/e2e-faults.mjs +159 -0
  28. package/scripts/grid-crossing-walk-proof.mjs +14 -3
  29. package/scripts/memory-proof.mjs +158 -0
  30. package/scripts/offline-proof-rules.d.mts +4 -2
  31. package/scripts/offline-proof-rules.mjs +21 -5
  32. package/scripts/offline-proof.mjs +15 -6
  33. package/scripts/tier-textures-proof.mjs +101 -0
  34. package/scripts/tier-textures.mjs +60 -0
  35. package/scripts/tsconfig.json +1 -0
  36. package/scripts/vps/wildshard-config +79 -23
  37. package/scripts/worker-client-play.mjs +1 -0
  38. package/scripts/worker-client-proof.mjs +1 -1
  39. package/scripts/worker-client-slug.mjs +44 -0
  40. package/src/client/app/entry.ts +37 -10
  41. package/src/client/engine/boot/parsedPages.ts +127 -58
  42. package/src/client/engine/build.d.ts +2 -0
  43. package/src/client/engine/core/Game.ts +18 -0
  44. package/src/client/engine/core/bootstrap.ts +4 -1
  45. package/src/client/engine/debug/probe.ts +18 -1
  46. package/src/client/engine/fx/LightPool.ts +41 -1
  47. package/src/client/engine/pwa/sw.js +12 -3
  48. package/src/client/engine/render/precompile.ts +20 -14
  49. package/src/client/engine/telemetry/browserErrors.ts +4 -1
  50. package/src/client/engine/telemetry/deviceSnapshot.ts +155 -0
  51. package/src/client/game/boot/audio.generated.ts +0 -102
  52. package/src/client/game/boot/bytes.generated.ts +42 -60
  53. package/src/client/game/boot/versions.generated.ts +0 -2
  54. package/src/client/game/grid/area.ts +38 -0
  55. package/src/client/game/grid/live.ts +28 -2
  56. package/src/client/game/grid/liveSession.ts +14 -3
  57. package/src/client/game/grid/menu.ts +4 -0
  58. package/src/client/game/grid/neighbourPanels.ts +10 -1
  59. package/src/client/game/grid/placedCards.ts +55 -0
  60. package/src/client/game/grid/placedCells.ts +131 -0
  61. package/src/client/game/grid/regionalRuntime.ts +6 -0
  62. package/src/client/game/grid/regionalWorld.ts +15 -2
  63. package/src/client/game/grid/roadCull.ts +44 -14
  64. package/src/client/game/grid/roadTileBacking.ts +13 -3
  65. package/src/client/game/grid/session.ts +9 -0
  66. package/src/client/game/grid/shardfileFar.ts +9 -3
  67. package/src/client/game/session/finish.ts +5 -1
  68. package/src/client/game/shard/titleList.ts +6 -2
  69. package/src/client/game/shardfile/clientWorker.ts +2 -1
  70. package/src/client/game/titleDeck.ts +4 -3
  71. package/src/client/host/online/shell.ts +14 -0
  72. package/src/cook/game/shardCook.ts +38 -8
  73. package/src/cook/game/tierTextures.ts +276 -0
  74. package/src/e2e/smoke/game.ts +19 -14
  75. package/src/e2e/smoke/page-globals.d.ts +9 -8
  76. package/src/e2e/smoke/template2.spec.ts +8 -7
  77. package/src/server/host/dedicated/placementFile.ts +1 -17
  78. package/src/server/host/dedicated/socketTransport.ts +2 -1
  79. package/src/server/host/dedicated/world.ts +30 -1
  80. package/src/shared/engine/net/deviceWord.ts +138 -0
  81. package/src/shared/engine/net/socketFrames.ts +7 -4
  82. package/src/shared/game/grid/catalogueSlot.ts +7 -0
  83. package/src/shared/game/grid/placementRows.ts +33 -0
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
2
3
  import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
4
 
@@ -24,6 +25,36 @@ export function copyOutputProducts(root, outDir) {
24
25
  }
25
26
  }
26
27
 
28
+ /** A product's mounts serve from `public/` (`pins.ts install` publishes them), so a product dropped into `out/` by hand keeps
29
+ * whatever an older head left there. AUDIO AU7 re-encodes a recording under its old URL, so a new revision and its
30
+ * predecessor share URLs with different bytes: a preparation preview then serves the old head's audio, its manifests
31
+ * name the old hashes, and `wildshard prepare` records no audio in the new head's fence (meta QA 2026-11-13 row 34).
32
+ * Refuse a build whose `public/` copy of a product's mount differs from the product's own bytes; a missing copy is the
33
+ * cook's to refuse. Under 0.5 s over every pinned product.
34
+ * @param {string} root @returns {number} the mounts checked */
35
+ export function checkPublishedMounts(root) {
36
+ const products = resolve(root, 'out'), stale = [];
37
+ if (!existsSync(products)) return 0;
38
+ let checked = 0;
39
+ for (const entry of readdirSync(products, { withFileTypes: true })) {
40
+ const cook = resolve(products, entry.name, 'cook.json');
41
+ if (!entry.isDirectory() || entry.name.startsWith('.') || !existsSync(cook)) continue;
42
+ let parsed;
43
+ try { parsed = JSON.parse(readFileSync(cook, 'utf8')); } catch (error) { throw new Error(`out/${entry.name}/cook.json does not parse`, { cause: error }); }
44
+ const { mounts } = /** @type {{mounts?: {url: string, hash: string}[]}} */ (parsed);
45
+ for (const row of mounts ?? []) {
46
+ const copy = resolve(root, `public${row.url}`);
47
+ if (!/^\/(?:assets|programs)\/(?!.*(?:^|\/)\.\.(?:\/|$))/u.test(row.url) || !existsSync(copy)) continue;
48
+ checked++;
49
+ if (createHash('sha256').update(readFileSync(copy)).digest('hex') !== row.hash) stale.push(`${entry.name} ${row.url}`);
50
+ }
51
+ }
52
+ if (stale.length > 0) throw new Error(`public/ holds ${stale.length} ${stale.length === 1 ? 'mount' : 'mounts'} with other bytes than their product in out/ `
53
+ + `(${stale.slice(0, 3).join(', ')}): publish that product's mounts (node scripts/pins.ts install for a pin, or copy a candidate's `
54
+ + 'mounts/ into public/), or remove its out/ folder if nothing pins it any more, and build again');
55
+ return checked;
56
+ }
57
+
27
58
  /** DL20: a level file leaves the deploy when a part holds it and nothing reads its URL directly. Every default manifest's file
28
59
  * stays: a neighbour's rings and a road crossing read those by URL (G828, G1011; through parts each would cost a whole part),
29
60
  * a title's `<img>` reads its art, and the harness's shardfile arm reads the same set. What goes is the rest of a whole-level
@@ -15,6 +15,7 @@ import { nameChunksByFinalBytes } from "./app-build/finalChunkNames.mjs";
15
15
  import { writeTitleAssets } from "./title-assets.mjs";
16
16
  import {
17
17
  copyOutputProducts,
18
+ checkPublishedMounts,
18
19
  copyDeferredPublic,
19
20
  pruneLooseCopies,
20
21
  } from "./app-build/outputProducts.mjs";
@@ -55,6 +56,8 @@ export function prepareAppBuild() {
55
56
  // C3: a tree with no shard source (the lifted engine) has no list or bake to run; it builds from a catalogue and its packs.
56
57
  const shardSource = existsSync("src/shards");
57
58
  checkBakedTextures(process.cwd(), resolve("public"));
59
+ // A shard-source tree rebuilds out/ from public/ below; only a tree that builds from placed products can hold a stale copy.
60
+ if (!shardSource) checkPublishedMounts(process.cwd());
58
61
  if (shardSource) {
59
62
  step(["scripts/gen-shards.mjs"]);
60
63
  for (const baker of ["bake-chunk", "bake-sky"]) {
@@ -16,7 +16,7 @@ export function assertProductionBuild(directory) {
16
16
  if (file.isDirectory()) walk(full);
17
17
  else if (file.name.endsWith('.js')) {
18
18
  const code = readFileSync(full, 'utf8');
19
- if (code.includes('__DEVSERVER__')) throw new Error('Production bundle contains an unsubstituted DEVSERVER define');
19
+ if (code.includes('__DEVSERVER__') || code.includes('__PREPARATION_ONLY__')) throw new Error('Production bundle contains an unsubstituted DEVSERVER or PREPARATION_ONLY define');
20
20
  }
21
21
  }
22
22
  };
@@ -1,4 +1,6 @@
1
1
  // Conservative source guard for Chromium launchers, without a parser dependency.
2
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
3
+
2
4
  const childMethods = ['spawn', 'spawnSync', 'execFile', 'execFileSync', 'exec', 'execSync'];
3
5
  const browserBinary = /chrom(?:e|ium)|executablePath\s*\(/iu;
4
6
 
@@ -11,7 +13,7 @@ function shellProblems(/** @type {string} */ text) {
11
13
  if (!command || command[1].startsWith('#') || command[1].includes('=')) return [];
12
14
  const program = command[1].replaceAll(/\$\{?(\w+)\}?/gu, (_all, name) => variables.get(name) ?? name);
13
15
  if (!browserBinary.test(program)) return [];
14
- return ['--use-mock-keychain', '--password-store=basic'].every(flag => command[2].includes(flag)) ? [] : ['bare Chromium shell executable'];
16
+ return KEYCHAIN_ARGS.every(flag => command[2].includes(flag)) ? [] : ['bare Chromium shell executable'];
15
17
  });
16
18
  }
17
19
 
@@ -96,7 +98,7 @@ export function keychainProblems(/** @type {string} */ text) {
96
98
  return expanded;
97
99
  };
98
100
  const safe = (/** @type {string} */ value) => /\.\.\.\s*KEYCHAIN_ARGS\b/u.test(expand(value))
99
- || ['--use-mock-keychain', '--password-store=basic'].every(flag => expand(value).includes(flag));
101
+ || KEYCHAIN_ARGS.every(flag => expand(value).includes(flag));
100
102
  const names = [...childMethods];
101
103
  const namespaces = new Set([...text.matchAll(/import\s+\*\s+as\s+(\w+)\s+from\s+['"](?:node:)?child_process['"]/gu)].map(match => match[1]));
102
104
  for (const match of text.matchAll(/import\s+(\w+)\s+from\s+['"](?:node:)?child_process['"]/gu)) namespaces.add(match[1]);
@@ -2,4 +2,6 @@
2
2
  // keychain for "Chrome for Testing Safe Storage" and a dialog lands on the desktop at each launch. Playwright adds them
3
3
  // by default, but a raw `spawn` of the executable skips its defaults, so every launch site spreads them explicitly and
4
4
  // test/tooling/chrome-keychain.test.mjs refuses a launch file that does not.
5
- export const KEYCHAIN_ARGS = Object.freeze(['--use-mock-keychain', '--password-store=basic']);
5
+ // `--mute-audio` rides along (Jake, 2026-11-13: "headless chromium with volume off"), so a launch that forgets it
6
+ // still cannot play a game's sound out of Jake's speakers.
7
+ export const KEYCHAIN_ARGS = Object.freeze(['--use-mock-keychain', '--password-store=basic', '--mute-audio']);
package/scripts/cook.mjs CHANGED
@@ -1,19 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  // C1 (J28): `cook <shardfile.tar> <out>`, a shard's packs from its tarball alone: no bundle, no src/shards, no public/.
3
- // node --import ./scripts/bake-loader.mjs scripts/cook.mjs <shardfile.tar> <out>
3
+ // node --import ./scripts/bake-loader.mjs scripts/cook.mjs <shardfile.tar> <out> [--phone-textures]
4
4
  // `out` receives `assets/spawn/parts/<hash>.pack.br`, one manifest per tier and set, and what no part may hold at its URL.
5
+ // --phone-textures (S12b): the phone manifests list each KTX2 table row trimmed to its phone size (`phoneTier`).
5
6
  import { readFileSync } from 'node:fs';
6
7
  import { homedir } from 'node:os';
7
8
  import { resolve } from 'node:path';
8
9
  import { BrotliSizeCache } from '../src/cook/game/brotliSizeCache.mjs';
9
10
 
10
11
  const { cookShard, servedAsIs } = await import('../src/cook/game/shardCook.ts');
11
- const [tarball, out] = process.argv.slice(2);
12
- if (tarball === undefined || out === undefined) throw new Error('usage: cook <shardfile.tar> <out>');
12
+ const flags = process.argv.slice(2).filter(arg => arg.startsWith('--')), unknown = flags.find(flag => flag !== '--phone-textures');
13
+ if (unknown !== undefined) throw new Error(`cook: unknown flag ${unknown}`);
14
+ const [tarball, out] = process.argv.slice(2).filter(arg => !arg.startsWith('--'));
15
+ if (tarball === undefined || out === undefined) throw new Error('usage: cook <shardfile.tar> <out> [--phone-textures]');
13
16
  const served = new BrotliSizeCache(process.env.WILDSHARD_WIRE_SIZE_CACHE ?? resolve(homedir(), '.cache/wildshard/gen/served-bytes/1'));
14
17
  const report = await cookShard(readFileSync(tarball), resolve(out), {
15
18
  now: () => performance.now(),
16
19
  wireBytes: (url, bytes) => servedAsIs(url, bytes) ? bytes.length : served.bytes(bytes),
17
20
  warn: line => { console.warn(`warning: ${line}`); },
21
+ ...(process.argv.includes('--phone-textures') ? { tiers: { phone: true } } : {}),
18
22
  });
19
23
  console.log(JSON.stringify(report));
@@ -0,0 +1,4 @@
1
+ /** The `client.device` lines in a journal's text, oldest first. */
2
+ export function deviceLines(text: string): Record<string, unknown>[];
3
+ /** The lines as a fixed-width table. */
4
+ export function deviceTable(lines: readonly Record<string, unknown>[]): string;
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // DEVICE-TELEMETRY DT5 (meta docs/plans/DEVICE-TELEMETRY-PLAN.md): the last N connects' devices from a door's journal, as a table.
3
+ // The door writes one `client.device` JSON line per connect (src/server/host/dedicated/world.ts, src/shared/engine/net/deviceWord.ts).
4
+ // ssh wildshard-agent journalctl -u wildshard-server@staging --since today -o cat | node scripts/devices.mjs --last 20
5
+ // node scripts/devices.mjs --last 20 journal.txt (a saved journal)
6
+ // node scripts/devices.mjs --json < journal.txt (the lines themselves)
7
+ // Read-only: it reads text and prints. Lines carry device characteristics, the Name and the secret-keyed body id, never an address.
8
+ import { readFileSync } from 'node:fs';
9
+
10
+ const COLUMNS = [['name', 14], ['body', 12], ['model', 16], ['platform', 10], ['platformVersion', 8], ['browser', 24], ['gpu', 36], ['screen', 10], ['dpr', 5], ['memory', 4], ['cores', 4], ['clientBuild', 12]];
11
+
12
+ /** The `client.device` lines in a journal's text, oldest first; anything else on a line (a journal prefix) is skipped. */
13
+ export function deviceLines(text) {
14
+ const out = [];
15
+ for (const raw of text.split('\n')) {
16
+ const at = raw.indexOf('{"at":"client.device"');
17
+ if (at === -1) continue;
18
+ try { out.push(JSON.parse(raw.slice(at))); } catch { /* a cut line */ }
19
+ }
20
+ return out;
21
+ }
22
+
23
+ /** The lines as a fixed-width table. */
24
+ export function deviceTable(lines) {
25
+ const cell = (value, width) => { const said = value === undefined ? '-' : String(value); return (said.length > width ? `${said.slice(0, width - 1)}~` : said).padEnd(width); };
26
+ const head = COLUMNS.map(([name, width]) => cell(name, width)).join(' ');
27
+ return [head, ...lines.map(line => COLUMNS.map(([name, width]) => cell(line[name], width)).join(' '))].join('\n');
28
+ }
29
+
30
+ function main(argv) {
31
+ const lastAt = argv.indexOf('--last'), last = lastAt === -1 ? 20 : Number(argv[lastAt + 1] ?? 20);
32
+ const files = argv.filter((arg, index) => !arg.startsWith('--') && index !== lastAt + 1);
33
+ const text = files.length === 0 ? readFileSync(0, 'utf8') : files.map(file => readFileSync(file, 'utf8')).join('\n');
34
+ const lines = deviceLines(text).slice(-Math.max(1, last));
35
+ if (argv.includes('--json')) { for (const line of lines) console.log(JSON.stringify(line)); return; }
36
+ console.log(lines.length === 0 ? 'no client.device lines (a door from before DEVICE-TELEMETRY writes none)' : deviceTable(lines));
37
+ }
38
+
39
+ if (import.meta.url === `file://${process.argv[1]}`) main(process.argv.slice(2));
@@ -1,5 +1,7 @@
1
1
  // HOW-WE-BUILD ENG-16: types for scripts/devserver-client.mjs.
2
2
  /** The release asset's name; sharddev's `DEV_CLIENT_ASSET` reads the same. */
3
3
  export declare const DEV_CLIENT_ASSET: string;
4
- /** Prune a devserver build in place to the client an author's page reads. */
5
- export declare function pruneDevserverClient(client: string): void;
4
+ /** SA43: the preparation client's asset; sharddev's `PREPARATION_CLIENT_ASSET` reads the same. */
5
+ export declare const PREPARATION_CLIENT_ASSET: string;
6
+ /** Prune a devserver build (or a preparation-only production build) in place to the client an author's page reads. */
7
+ export declare function pruneDevserverClient(client: string, kind?: 'devserver' | 'preparation'): void;
@@ -9,6 +9,11 @@
9
9
  // programs, drafts, trailers and source maps. The author's own shard comes from `wildshard dev`'s build.
10
10
  //
11
11
  // python3 scripts/heavy-lane.py build -- node scripts/devserver-client.mjs --out <devserver-client.tar.gz> [--keep <folder>]
12
+ //
13
+ // SHARD-AUTHORING SA43: `--kind preparation` packs the client `wildshard prepare` records in, `preparation-client.tar.gz`:
14
+ // the production build (DEVSERVER off, the production renderer and its revision) made with `WILDSHARD_PREPARATION_ONLY=1`,
15
+ // so it owns the author's inline draft as `wildshard dev`'s page does, pruned the same way. check-devserver refuses to
16
+ // release it; it is only ever a release asset beside the devserver client.
12
17
  import { execFileSync, spawnSync } from 'node:child_process';
13
18
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
14
19
  import { join, relative, resolve } from 'node:path';
@@ -17,16 +22,25 @@ import { pathToFileURL } from 'node:url';
17
22
  const ROOT = resolve(import.meta.dirname, '..');
18
23
  /** The release asset's name; sharddev's `DEV_CLIENT_ASSET` reads the same. */
19
24
  export const DEV_CLIENT_ASSET = 'devserver-client.tar.gz';
25
+ /** SA43: the preparation client's asset; sharddev's `PREPARATION_CLIENT_ASSET` reads the same. */
26
+ export const PREPARATION_CLIENT_ASSET = 'preparation-client.tar.gz';
27
+ /** @typedef {'devserver' | 'preparation'} ClientKind */
20
28
  /** Top-level paths (and `assets/` folders) a devserver page never reads. */
21
29
  const DROP_TOP = ['programs', 'drafts', 'trailer-15.mp4', 'trailer-30.mp4'];
22
30
  const DROP_ASSETS = ['driftwood-isle', 'far-reach', 'nalati', 'nine-dragon', 'pine-hollow', 'sunscar-dunes', 'practice'];
23
31
  /** `assets/gpu/` (KTX2 stand-ins): the shards' own folders go; the engine's `tex`, `models` and `horizon` stay. */
24
32
  const DROP_GPU = ['baked', 'far-reach', 'nalati', 'nine-dragon', 'pine-hollow'];
25
33
 
26
- /** Prune a devserver build in place to the client an author's page reads. @param {string} client */
27
- export function pruneDevserverClient(client) {
34
+ /** Prune a devserver build (or, SA43, a preparation-only production build) in place to the client an author's page reads.
35
+ * @param {string} client @param {ClientKind} [kind] */
36
+ export function pruneDevserverClient(client, kind = 'devserver') {
28
37
  const flags = JSON.parse(readFileSync(join(client, 'build-flags.json'), 'utf8'));
29
- if (flags?.devserver !== true) throw new Error('devserver-client: the build is not in devserver mode');
38
+ if (kind === 'devserver' && flags?.devserver !== true) throw new Error('devserver-client: the build is not in devserver mode');
39
+ if (kind === 'preparation') {
40
+ const versionFile = join(client, 'version.json');
41
+ const version = existsSync(versionFile) ? JSON.parse(readFileSync(versionFile, 'utf8')) : undefined;
42
+ if (flags?.devserver !== false || version?.preparationOnly !== true) throw new Error('devserver-client: the build is not a preparation-only production build');
43
+ }
30
44
  for (const name of DROP_TOP) rmSync(join(client, name), { recursive: true, force: true });
31
45
  for (const name of DROP_ASSETS) rmSync(join(client, 'assets', name), { recursive: true, force: true });
32
46
  for (const name of DROP_GPU) rmSync(join(client, 'assets', 'gpu', name), { recursive: true, force: true });
@@ -47,15 +61,18 @@ const bytesOf = folder => readdirSync(folder, { recursive: true, withFileTypes:
47
61
 
48
62
  if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
49
63
  const args = process.argv.slice(2), option = (/** @type {string} */ name) => { const at = args.indexOf(`--${name}`); return at === -1 ? undefined : args[at + 1]; };
50
- const out = resolve(option('out') ?? join('tmp', 'devserver-client', DEV_CLIENT_ASSET));
64
+ const kind = /** @type {ClientKind} */ (option('kind') ?? 'devserver');
65
+ if (kind !== 'devserver' && kind !== 'preparation') throw new Error(`devserver-client: --kind is devserver or preparation, not ${String(kind)}`);
66
+ const out = resolve(option('out') ?? join('tmp', 'devserver-client', kind === 'devserver' ? DEV_CLIENT_ASSET : PREPARATION_CLIENT_ASSET));
51
67
  const client = resolve(option('keep') ?? join(ROOT, 'tmp', 'devserver-client', 'client'));
52
68
  if (relative(ROOT, client).startsWith('..')) throw new Error('devserver-client: the build folder must be inside this checkout (build-app defers its public copy there)');
53
69
  rmSync(client, { recursive: true, force: true });
54
- const built = spawnSync(process.execPath, ['scripts/build-app.mjs', '--mode', 'devserver', '--outDir', client], {
55
- cwd: ROOT, stdio: 'inherit', env: { ...process.env, WILDSHARD_CATALOGUE: process.env.WILDSHARD_CATALOGUE ?? 'test/pins/catalogue.json' } });
70
+ const built = spawnSync(process.execPath, ['scripts/build-app.mjs', '--mode', kind === 'devserver' ? 'devserver' : 'production', '--outDir', client], {
71
+ cwd: ROOT, stdio: 'inherit', env: { ...process.env, WILDSHARD_CATALOGUE: process.env.WILDSHARD_CATALOGUE ?? 'test/pins/catalogue.json',
72
+ ...(kind === 'preparation' ? { WILDSHARD_PREPARATION_ONLY: '1' } : {}) } });
56
73
  if (built.status !== 0) throw new Error(`devserver-client: build-app exited ${String(built.status)}`);
57
74
  const before = bytesOf(client);
58
- pruneDevserverClient(client);
75
+ pruneDevserverClient(client, kind);
59
76
  mkdirSync(resolve(out, '..'), { recursive: true });
60
77
  // the same bytes for the same tree: sorted names, no owners or times (as the dedicated bundle is packed in server-release.yml)
61
78
  const tar = spawnSync('tar', ['--version'], { encoding: 'utf8' }).stdout.includes('GNU') ? 'tar' : 'gtar';
@@ -63,6 +80,6 @@ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(p
63
80
  execFileSync('bash', ['-c', gnu
64
81
  ? `set -euo pipefail; ${tar} --sort=name --mtime='@0' --owner=0 --group=0 --numeric-owner -cf - -C "$1" . | gzip -n > "$2"`
65
82
  : 'set -euo pipefail; tar -cf - -C "$1" . | gzip -n > "$2"', 'pack', client, out], { stdio: 'inherit' });
66
- console.log(`devserver-client: ${(before / 1e6).toFixed(0)} MB built, ${(bytesOf(client) / 1e6).toFixed(0)} MB kept, ${(statSync(out).size / 1e6).toFixed(1)} MB packed: ${out}`);
83
+ console.log(`devserver-client (${kind}): ${(before / 1e6).toFixed(0)} MB built, ${(bytesOf(client) / 1e6).toFixed(0)} MB kept, ${(statSync(out).size / 1e6).toFixed(1)} MB packed: ${out}`);
67
84
  if (option('keep') === undefined) rmSync(client, { recursive: true, force: true });
68
85
  }
@@ -62,7 +62,7 @@ const pages = spawn(process.execPath, ['scripts/preview-server.mjs', '--outDir',
62
62
  for (let tries = 0; tries < 100 && !(await fetch(`http://127.0.0.1:${String(PAGE_PORT)}/version.json`).then(found => found.ok).catch(() => false)); tries++) await sleep(100);
63
63
  const base = `http://127.0.0.1:${String(PAGE_PORT)}`;
64
64
 
65
- const browser = await (engine === 'webkit' ? webkit : chromium).launch(engine === 'webkit' ? {} : { args: ['--use-mock-keychain', '--password-store=basic'] });
65
+ const browser = await (engine === 'webkit' ? webkit : chromium).launch(engine === 'webkit' ? {} : { args: ['--use-mock-keychain', '--password-store=basic', '--mute-audio'] });
66
66
  const device = engine === 'webkit' ? devices['iPhone 13'] : devices['Pixel 7'];
67
67
  const failures = /** @type {string[]} */ ([]), results = /** @type {Record<string, unknown>} */ ({});
68
68
  /** @param {boolean} ok @param {string} what */
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env node
2
+ // T2E-2 (TEMPLATE-E2E-PLAN): the Template 2 smoke's fault drill. Each step of the smoke has a fault planted in the real
3
+ // source that should turn that step, and no earlier one, red. The drill plants one fault at a time, runs the smoke
4
+ // (`--project template-2`), puts the source back, and checks which step failed first.
5
+ //
6
+ // node scripts/e2e-faults.mjs every fault, one smoke run each (about 1.5 min each)
7
+ // node scripts/e2e-faults.mjs <id>... only these
8
+ //
9
+ // Run it in a worktree you own: it rewrites tracked source for the length of a run and restores the bytes it read,
10
+ // also on Ctrl-C. Each run builds the client cold and checks the served build holds this plant and no other. Steps 4
11
+ // (the bag key unbound) and 5 (the attack dropped) join once Template 2 carries a pickup and a weapon (shard-format
12
+ // S2-1, S2-2).
13
+ import { spawnSync } from 'node:child_process';
14
+ import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { join, resolve as resolvePath } from 'node:path';
16
+ import { stripVTControlCharacters } from 'node:util';
17
+ import { CLIENT_DIR, E2E_DIR, STATE_FILE } from './e2e-paths.mjs';
18
+
19
+ const root = resolvePath(import.meta.dirname, '..');
20
+ const REPORT = `${E2E_DIR}/faults-report.json`;
21
+ /** The planted file's path and both texts, while a plant stands. */
22
+ const PLANTED = `${E2E_DIR}/faults-planted.json`;
23
+
24
+ /** @typedef {{ id: string, step: string, why: string, file: string, find: string, plant: string }} Fault */
25
+ /** @type {readonly Fault[]} */
26
+ const FAULTS = [
27
+ { id: 'use-unbound', step: '3.', why: 'E is bound to nothing in play',
28
+ file: 'src/client/game/inputContexts.ts', find: "dodge: ['KeyV', 'AltLeft'], use: ['KeyE'],", plant: "dodge: ['KeyV', 'AltLeft'], use: ['e2e-fault-use-unbound'],"
29
+ },
30
+ { id: 'door-hook-stubbed', step: '3.', why: "the door's scene (blender.door.toggle) runs nothing",
31
+ file: 'src/server/game/plugin/simulation.ts', find: 'seats.step(); createQuestScriptPorts(lane, hooks, actors).scene(row.scene, player); return true;', plant: "seats.step(); Reflect.set(globalThis, 'e2eFault', 'e2e-fault-door-hook-stubbed'); return true;"
32
+ },
33
+ // The door's state is its shared field, `blender.door.open` (id 101). Leaving only the quest's `blender.door` flag out of
34
+ // the snapshot stays green: the quest earns it again from that field as the world restores.
35
+ { id: 'save-skips-door', step: '7.', why: "the save keeps the door's field (blender.door.open, 101) at its default",
36
+ file: 'src/shared/engine/script/state.ts', find: 'shared: [...this.shared], players:',
37
+ plant: "shared: (Reflect.set(globalThis, 'e2eFault', 'e2e-fault-save-skips-door'), this.shared.map((value, index) => this.declaration.shared[index]?.id === 101 ? 0 : value)), players:"
38
+ },
39
+ ];
40
+
41
+ /** @param {string} text @param {string} part */
42
+ const count = (text, part) => text.split(part).length - 1;
43
+
44
+ /** Every fault's marker: a string its plant carries that survives the bundle. @param {Fault} fault */
45
+ const marker = fault => `e2e-fault-${fault.id}`;
46
+
47
+ /** The markers the served client holds: the smoke's JavaScript under CLIENT_DIR. @returns {Set<string>} */
48
+ function served() {
49
+ const found = new Set();
50
+ /** @param {string} dir */
51
+ const walk = dir => {
52
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
53
+ const path = join(dir, entry.name);
54
+ if (entry.isDirectory()) walk(path);
55
+ else if (entry.name.endsWith('.js')) { const text = readFileSync(path, 'utf8'); for (const fault of FAULTS) if (text.includes(marker(fault))) found.add(fault.id); }
56
+ }
57
+ };
58
+ walk(join(root, CLIENT_DIR));
59
+ return found;
60
+ }
61
+
62
+ /** This worktree's watcher, as the smoke drives it. @param {'ready'|'stop'} command */
63
+ function client(command) {
64
+ const run = spawnSync(process.execPath, ['--import', './scripts/format-hook.mjs', 'scripts/e2e-client.mjs', command], { cwd: root, encoding: 'utf8' });
65
+ interrupted(run);
66
+ if (run.status !== 0) throw new Error(`e2e-faults: e2e-client ${command} failed\n${run.stdout}\n${run.stderr}`);
67
+ }
68
+
69
+ /** @param {number} ms */
70
+ const pause = ms => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); };
71
+ /** @param {number} pid */
72
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
73
+
74
+ /** Wait until this worktree's watcher has exited: the next ready builds the source as it now stands. */
75
+ function stopClient() {
76
+ const state = join(root, STATE_FILE), pid = existsSync(state) ? Number(JSON.parse(readFileSync(state, 'utf8')).pid) : undefined;
77
+ client('stop');
78
+ const running = () => pid !== undefined && alive(pid);
79
+ for (let wait = 0; wait < 300 && running(); wait += 1) pause(100);
80
+ if (running()) throw new Error(`e2e-faults: the watcher (pid ${String(pid)}) did not stop in 30 s`);
81
+ }
82
+
83
+ /** Puts a planted file back from its recovery record, if one is left, and only while it still holds the plant: an edit
84
+ * made since is kept, and named. @returns {string|undefined} a warning */
85
+ function recover() {
86
+ const record = join(root, PLANTED);
87
+ if (!existsSync(record)) return undefined;
88
+ const { file, before, planted } = JSON.parse(readFileSync(record, 'utf8')), path = join(root, file);
89
+ const now = readFileSync(path, 'utf8');
90
+ rmSync(record, { force: true });
91
+ if (now === before) return undefined;
92
+ if (now === planted) { writeFileSync(path, before); return undefined; }
93
+ return `e2e-faults: ${file} changed during the drill, so its plant was left for you to take out`;
94
+ }
95
+
96
+ /** A Ctrl-C reaches the child, not this process (spawnSync blocks its handlers): stop on the child's signal. @param {import('node:child_process').SpawnSyncReturns<string>} run */
97
+ function interrupted(run) {
98
+ if (run.signal === null && run.status !== 130) return;
99
+ const warning = recover();
100
+ if (warning !== undefined) console.error(warning);
101
+ try { client('stop'); } catch { /* the stop is best effort here */ }
102
+ process.exit(130);
103
+ }
104
+
105
+ /** Every test.step at the top level of a result; the first red one is the step the fault reddened. @param {any} suite @returns {any[]} */
106
+ const resultsOf = suite => [...(suite.specs ?? []).flatMap((/** @type {any} */ spec) => spec.tests).flatMap((/** @type {any} */ test) => test.results), ...(suite.suites ?? []).flatMap(resultsOf)];
107
+
108
+ /** @param {Fault} fault */
109
+ function drill(fault) {
110
+ const path = join(root, fault.file), before = readFileSync(path, 'utf8');
111
+ if (count(before, fault.find) !== 1) return { ok: false, detail: `${fault.file} no longer holds the line to plant in once` };
112
+ if (!fault.plant.includes(marker(fault))) return { ok: false, detail: `its plant carries no ${marker(fault)}` };
113
+ const planted = before.replace(fault.find, fault.plant);
114
+ // A warm watcher can miss a write and restore made seconds apart (its file events are not reliable), so each drill
115
+ // builds cold, about 25 s: a fresh watcher before the plant and another after the restore.
116
+ stopClient();
117
+ // Written first, so a drill killed mid-run is put right by the next one.
118
+ writeFileSync(join(root, PLANTED), JSON.stringify({ file: fault.file, before, planted }));
119
+ writeFileSync(path, planted);
120
+ rmSync(join(root, REPORT), { force: true });
121
+ const started = performance.now();
122
+ let run, warning;
123
+ try {
124
+ // A drill is only as good as the build it ran: the served client must hold this plant and no other.
125
+ client('ready');
126
+ const held = [...served()];
127
+ if (held.length !== 1 || held[0] !== fault.id) return { ok: false, detail: `the served client holds [${held.join(', ')}], not just this plant` };
128
+ run = spawnSync('pnpm', ['exec', 'playwright', 'test', '--config', 'src/e2e/playwright.config.ts', '--project', 'template-2', '--reporter', 'json'],
129
+ { cwd: root, encoding: 'utf8', env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_NAME: join(root, REPORT) }, maxBuffer: 64 * 1024 * 1024 });
130
+ interrupted(run);
131
+ } finally {
132
+ warning = recover();
133
+ stopClient();
134
+ }
135
+ if (warning !== undefined) throw new Error(warning);
136
+ const seconds = ((performance.now() - started) / 1000).toFixed(1);
137
+ if (run.status === 0) return { ok: false, detail: `the smoke stayed green (${seconds} s)` };
138
+ if (!existsSync(join(root, REPORT))) return { ok: false, detail: `no report (exit ${String(run.status)})\n${(run.stderr ?? run.error?.message ?? '').slice(-2000)}` };
139
+ const results = resultsOf(JSON.parse(readFileSync(join(root, REPORT), 'utf8')));
140
+ const red = results.flatMap((/** @type {any} */ result) => result.steps ?? []).find((/** @type {any} */ step) => step.error !== undefined);
141
+ if (red === undefined) return { ok: false, detail: `red outside any step (${seconds} s): ${String(results[0]?.error?.message ?? '').split('\n')[0]}` };
142
+ const message = stripVTControlCharacters(String(red.error?.message ?? '')).split('\n').find(line => line.trim() !== '') ?? '';
143
+ return { ok: String(red.title).startsWith(fault.step), detail: `red at "${String(red.title)}" (want step ${fault.step}) in ${seconds} s: ${message.trim()}` };
144
+ }
145
+
146
+ const asked = process.argv.slice(2);
147
+ const unknown = asked.filter(id => !FAULTS.some(fault => fault.id === id));
148
+ if (unknown.length > 0) throw new Error(`e2e-faults: no fault ${unknown.join(', ')}; known: ${FAULTS.map(fault => fault.id).join(', ')}`);
149
+ const leftover = recover();
150
+ if (leftover !== undefined) throw new Error(leftover);
151
+ let failed = 0;
152
+ for (const fault of FAULTS.filter(row => asked.length === 0 || asked.includes(row.id))) {
153
+ /** @type {{ ok: boolean, detail: string }} */
154
+ let result;
155
+ try { result = drill(fault); } catch (error) { result = { ok: false, detail: error instanceof Error ? error.message : String(error) }; }
156
+ if (!result.ok) failed += 1;
157
+ console.log(`${result.ok ? 'RED AS PLANTED' : 'DRILL FAILED'} ${fault.id} (${fault.why}): ${result.detail}`);
158
+ }
159
+ process.exit(failed === 0 ? 0 : 1);
@@ -54,6 +54,16 @@ try {
54
54
  if (open === null) throw new Error(`The world did not start: see ${join(work, 'server.log')}`);
55
55
  browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
56
56
  const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }), page = await context.newPage(), errors = /** @type {string[]} */ ([]);
57
+ // RP4: every program's first use (three's uniform read after its link, where a link not yet finished blocks the frame),
58
+ // counted so a leg's receipt says how many programs linked on the way (a cell's whole set relinking at its edge was 2.5 s)
59
+ await context.addInitScript(() => {
60
+ const W = /** @type {any} */ (window); W.__programLinks = 0;
61
+ for (const C of [W.WebGL2RenderingContext, W.WebGLRenderingContext]) {
62
+ if (C === undefined) continue;
63
+ const read = C.prototype.getProgramParameter;
64
+ C.prototype.getProgramParameter = function getProgramParameter(/** @type {WebGLProgram} */ program, /** @type {number} */ name) { if (name === this.ACTIVE_UNIFORMS) W.__programLinks++; return read.call(this, program, name); };
65
+ }
66
+ });
57
67
  page.on('pageerror', error => { errors.push(error.message.slice(0, 240)); });
58
68
  let navigations = 0;
59
69
  page.on('framenavigated', frame => { if (frame === page.mainFrame()) navigations++; });
@@ -128,7 +138,7 @@ try {
128
138
  /** @type {Record<string, unknown>[]} */
129
139
  const events = [];
130
140
  let stuckSince = 0, stuckMs = 0, worstStuck = 0, last = start, enteredAt = 0, controlAt = 0, roadAt = 0, jumps = 0;
131
- const t1 = Date.now(), framesFrom = await page.evaluate(() => /** @type {any} */ (window).__gc15c.frames.length);
141
+ const t1 = Date.now(), framesFrom = await page.evaluate(() => /** @type {any} */ (window).__gc15c.frames.length), linksFrom = await page.evaluate(() => /** @type {any} */ (window).__programLinks);
132
142
  await face(yaw);
133
143
  await page.keyboard.down('KeyW'); if (leg.boost) await page.keyboard.down('ShiftLeft');
134
144
  while (Date.now() - t1 < LEG_MS) {
@@ -153,9 +163,10 @@ try {
153
163
  await page.keyboard.up('KeyW'); if (leg.boost) await page.keyboard.up('ShiftLeft');
154
164
  const end = await sample(), frames = /** @type {number[][]} */ (await page.evaluate(n => /** @type {any} */ (window).__gc15c.frames.slice(n), framesFrom));
155
165
  await page.screenshot({ path: join(out, `${engineName}-${leg.name}-after.png`) });
156
- const deltas = frames.map(row => row[1] ?? 0), row = { name: leg.name, from, target: leg.target, boost: leg.boost, roadAtMs: roadAt, enteredAtMs: enteredAt, controlAtMs: controlAt,
166
+ const programLinks = await page.evaluate(() => /** @type {any} */ (window).__programLinks) - linksFrom;
167
+ const deltas = frames.map(row => row[1] ?? 0), row = { name: leg.name, programLinks, from, target: leg.target, boost: leg.boost, roadAtMs: roadAt, enteredAtMs: enteredAt, controlAtMs: controlAt,
157
168
  borderToControlMs: enteredAt === 0 || controlAt === 0 ? null : controlAt - enteredAt, worstStopMs: worstStuck, stoppedMs: stuckMs, jumps, frames: deltas.length,
158
- over50: deltas.filter(ms => ms > 50).length, worstFrameMs: Math.max(0, ...deltas), events, end };
169
+ over50: deltas.filter(ms => ms > 50).length, over100: deltas.filter(ms => ms > 100).length, worstFrameMs: Math.max(0, ...deltas), events, end };
159
170
  legs.push(row);
160
171
  note(`${leg.name}: arrives in ${leg.target} with control`, controlAt !== 0, { enteredAt, controlAt, end: { inside: end.inside, z: end.z, ready: end.ready } });
161
172
  note(`${leg.name}: no stop or wall on the way`, worstStuck <= STUCK_MS && jumps === 0, { worstStuck, jumps });