@wildshard/engine 0.1.21 → 0.1.23
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.
- package/CHANGELOG.md +16 -0
- package/lint/engine-sides.json +5 -0
- package/lint/shardfile-boundaries.mjs +4 -2
- package/lint/sim-players.json +2 -13
- package/lint/wildshard-plugin.js +1 -1
- package/package.json +10 -2
- package/scripts/apfs-clone.mjs +5 -2
- package/scripts/app-build/catalogue.ts +39 -8
- package/scripts/app-build/serviceWorker.ts +4 -1
- package/scripts/app-build/splitOutput.mjs +33 -11
- package/scripts/audio-download-proof.mjs +1 -1
- package/scripts/check-spelled-paths.mjs +6 -3
- package/scripts/ci-pack.mjs +3 -3
- package/scripts/committed-fast-checks.mjs +2 -2
- package/scripts/engine-ci-shard.mjs +11 -0
- package/scripts/failmode-cases.mjs +1 -1
- package/scripts/failmode-proof.mjs +35 -11
- package/scripts/fight-page-census.mjs +131 -0
- package/scripts/goldens/board.py +44 -11
- package/scripts/goldens/native-residency.d.mts +1 -0
- package/scripts/goldens/native-residency.mjs +18 -4
- package/scripts/grid-crossing-walk-proof.mjs +3 -3
- package/scripts/hover-speed-probe.mjs +2 -2
- package/scripts/keep-copy.mjs +120 -0
- package/scripts/land.mjs +36 -6
- package/scripts/lane-live.mjs +136 -0
- package/scripts/leftovers-report.mjs +47 -0
- package/scripts/loading-card-proof.mjs +42 -9
- package/scripts/loading-flow/benchmax.mjs +57 -7
- package/scripts/loading-flow/stalls.d.mts +2 -0
- package/scripts/loading-flow/stalls.mjs +13 -0
- package/scripts/mmo-bots.mjs +11 -5
- package/scripts/mmo-grid-proof.mjs +74 -0
- package/scripts/mmo-seat-proof.mjs +43 -0
- package/scripts/net-lag-proof.mjs +1 -1
- package/scripts/nightly-heads.ts +13 -13
- package/scripts/nightly-model.ts +26 -12
- package/scripts/nightly.proof.ts +18 -5
- package/scripts/nightly.ts +13 -8
- package/scripts/no-astc-boot.mjs +77 -0
- package/scripts/online-rig.mjs +7 -7
- package/scripts/parity/boot-smoke.mjs +1 -1
- package/scripts/physics-route.json +6 -6
- package/scripts/pins-reuse.mjs +1 -0
- package/scripts/pins-staging.ts +54 -0
- package/scripts/pins.ts +5 -0
- package/scripts/release-cook.mjs +6 -2
- package/scripts/ring3.proof.ts +71 -0
- package/scripts/ring3.ts +100 -0
- package/scripts/scratch-dir.mjs +31 -12
- package/scripts/scratch-sweep.mjs +15 -23
- package/scripts/server-release/items.d.mts +7 -0
- package/scripts/server-release/items.mjs +28 -0
- package/scripts/server-release/publish.mjs +9 -1
- package/scripts/side-parity.mjs +1 -1
- package/scripts/test-products.json +1 -21
- package/scripts/tsconfig.json +2 -0
- package/scripts/vitest-ci-files.ts +5 -1
- package/scripts/vps/cook-follow.d.mts +6 -0
- package/scripts/vps/cook-follow.mjs +45 -0
- package/scripts/vps/harden-apply.sh +10 -1
- package/scripts/vps/rebuild.sh +104 -36
- package/scripts/vps/wildshard-config +106 -3
- package/scripts/warm-native-chrome.mjs +9 -3
- package/scripts/worker-client-fights.mjs +9 -3
- package/scripts/worktree-reap.mjs +15 -131
- package/scripts/worktree.mjs +92 -12
- package/src/client/app/entry.ts +2 -3
- package/src/client/engine/audio/audioLog.ts +7 -2
- package/src/client/engine/boot/contentRead.ts +24 -4
- package/src/client/engine/boot/diagnostics.ts +69 -1
- package/src/client/engine/boot/downloadGiveUp.ts +34 -0
- package/src/client/engine/combat/EquipmentService.ts +2 -0
- package/src/client/engine/core/Game.ts +6 -2
- package/src/client/engine/core/ktx2.ts +5 -3
- package/src/client/engine/core/ktx2Zstd.ts +2 -1
- package/src/client/engine/pwa/sw.js +26 -8
- package/src/client/engine/render/dataLook.ts +14 -7
- package/src/client/engine/render/lookLight.ts +64 -20
- package/src/client/engine/ui/Loading.ts +6 -8
- package/src/client/engine/ui/downloadFailed.ts +54 -0
- package/src/client/engine/ui/lookLightOption.ts +1 -1
- package/src/client/game/audio/cueDirector.ts +2 -1
- package/src/client/game/boot/spawnDownload.ts +12 -1
- package/src/client/game/boss/arenaRoom.ts +4 -3
- package/src/client/game/boss/roamingProjection.ts +1 -1
- package/src/client/game/devScene/hook.ts +1 -1
- package/src/client/game/devScene/liveLook.ts +1 -1
- package/src/client/game/grid/copyPrompts.ts +3 -4
- package/src/client/game/grid/dataCellKit.ts +99 -0
- package/src/client/game/grid/enteredEquipment.ts +11 -2
- package/src/client/game/grid/live.ts +9 -299
- package/src/client/game/grid/liveSession.ts +31 -8
- package/src/client/game/grid/neighbourLife.ts +50 -32
- package/src/client/game/grid/products.ts +21 -7
- package/src/client/game/grid/reveal.ts +7 -2
- package/src/client/game/grid/session.ts +10 -74
- package/src/client/game/plugin/weaponFamily.ts +6 -0
- package/src/client/game/population/signals.ts +1 -1
- package/src/client/game/quest/chapterDirector.ts +1 -0
- package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
- package/src/client/game/shardfile/clientWorker.ts +35 -9
- package/src/client/game/shardfile/look.ts +1 -1
- package/src/client/game/shardfile/runtimeProduct.ts +9 -5
- package/src/client/game/shardfile/wirePage.ts +5 -2
- package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
- package/src/client/host/online/shell.ts +37 -13
- package/src/cook/game/cookWorker.ts +8 -5
- package/src/cook/game/tierTextures.ts +5 -3
- package/src/server/engine/net/simWorld.ts +3 -4
- package/src/server/game/grid/cellHome.ts +58 -0
- package/src/server/game/grid/room.ts +2 -38
- package/src/server/game/grid/simulation.ts +5 -4
- package/src/server/game/plugin/mover.ts +18 -14
- package/src/server/game/shardfile/declaredKitItems.ts +39 -9
- package/src/server/host/bake/headlessWorker.ts +3 -3
- package/src/server/host/dedicated/cellHost.ts +2 -2
- package/src/server/host/dedicated/cellProtocol.ts +1 -1
- package/src/server/host/dedicated/cellWorker.ts +5 -3
- package/src/server/host/dedicated/dedicatedRoom.ts +8 -3
- package/src/server/host/dedicated/gridCells.ts +5 -3
- package/src/server/host/dedicated/main.ts +12 -7
- package/src/server/host/dedicated/packReader.ts +15 -2
- package/src/server/host/dedicated/playerStore.ts +1 -1
- package/src/server/host/dedicated/workerTable.ts +0 -10
- package/src/server/host/dedicated/world.ts +39 -5
- package/src/server/host/headlessRuntime.ts +11 -6
- package/src/server/host/standalone/cellWorld.ts +21 -7
- package/src/server/host/standalone/gridServer.ts +3 -1
- package/src/server/host/standalone/roadWorld.ts +6 -0
- package/src/shared/engine/physics/gridBorders.ts +15 -1
- package/src/shared/engine/saves/shape.ts +17 -2
- package/src/shared/engine/sim/snapshot.ts +5 -5
- package/src/shared/engine/strings.ts +10 -0
- package/src/shared/game/grid/placementRows.ts +4 -3
- package/src/shared/game/ledger.ts +13 -4
- package/src/shared/game/loot/platformCatalogue.ts +14 -0
- package/src/shared/game/quest/ledger.ts +3 -3
- package/src/shared/game/shardfile/items.ts +9 -1
- package/src/shared/host/headlessJourney.ts +3 -3
- package/src/shared/host/headlessTape.ts +7 -6
- package/src/shared/host/releaseRows.ts +4 -1
- package/src/client/game/grid/cellLoading.ts +0 -110
- package/src/client/game/grid/cellScreens.ts +0 -48
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// REPO-DISK DK16/J358: read liveness without changing the lane.
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join, sep } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { activeHoursSince } from '../.agents/hooks/active-hours.mjs';
|
|
9
|
+
|
|
10
|
+
const RECEIPTS = join(homedir(), '.cache/wildshard/lane-receipts.log');
|
|
11
|
+
/** @param {string} path @param {string} root */
|
|
12
|
+
const under = (path, root) => path === root || path.startsWith(root + sep);
|
|
13
|
+
/** @param {string} path */
|
|
14
|
+
const readOwner = path => {
|
|
15
|
+
try {
|
|
16
|
+
const marker = join(path, '.owner'), info = lstatSync(marker);
|
|
17
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) return undefined;
|
|
18
|
+
const value = JSON.parse(readFileSync(marker, 'utf8'));
|
|
19
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
20
|
+
} catch { return undefined; }
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** null means process evidence could not be read; callers protect the folder. */
|
|
24
|
+
export function processCwds() {
|
|
25
|
+
if (existsSync('/proc/self/cwd')) {
|
|
26
|
+
try {
|
|
27
|
+
return readdirSync('/proc').filter(pid => /^\d+$/u.test(pid)).flatMap(pid => {
|
|
28
|
+
try { return [readlinkSync(`/proc/${ pid }/cwd`)]; } catch { return []; }
|
|
29
|
+
});
|
|
30
|
+
} catch { return null; }
|
|
31
|
+
}
|
|
32
|
+
const found = spawnSync('lsof', ['-nP', '-w', '-d', 'cwd', '-Fn'], {
|
|
33
|
+
cwd: '/', encoding: 'utf8', timeout: 2000, maxBuffer: 64 * 1024 * 1024,
|
|
34
|
+
});
|
|
35
|
+
if (found.error || found.signal || found.status !== 0) return null;
|
|
36
|
+
return found.stdout.split('\n').filter(line => line.startsWith('n')).map(line => line.slice(1));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param {unknown} lane @param {string} path @param {unknown} offset */
|
|
40
|
+
function receipt(lane, path, offset) {
|
|
41
|
+
if (typeof lane !== 'string' || !/^[\w.-]+$/u.test(lane)) return undefined;
|
|
42
|
+
// Undated receipts cannot end a folder created later. Legacy owners have
|
|
43
|
+
// no cursor, so they must use process/session evidence and active hours.
|
|
44
|
+
if (typeof offset !== 'number' || !Number.isSafeInteger(offset) || offset < 0) return undefined;
|
|
45
|
+
try {
|
|
46
|
+
const log = readFileSync(path);
|
|
47
|
+
if (offset > log.length) return undefined;
|
|
48
|
+
let last;
|
|
49
|
+
for (const line of log.subarray(offset).toString('utf8').split('\n').slice(0, -1))
|
|
50
|
+
if (line.includes(` ${lane} `) && /\s(?:DONE|ENDED|PAUSED):/u.test(line)) last = line;
|
|
51
|
+
return last;
|
|
52
|
+
} catch { return undefined; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @param {string} root @param {number} depth */
|
|
56
|
+
function pidfileLive(root, depth = 0) {
|
|
57
|
+
for (const name of ['.pid', 'pid', 'pidfile', 'server.pid', 'dev.pid']) {
|
|
58
|
+
try {
|
|
59
|
+
const pid = Number(readFileSync(join(root, name), 'utf8').trim());
|
|
60
|
+
if (!Number.isSafeInteger(pid) || pid < 1) continue;
|
|
61
|
+
try { process.kill(pid, 0); return true; } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'EPERM') return true; }
|
|
62
|
+
} catch {/* Unreadable evidence is skipped. */}
|
|
63
|
+
}
|
|
64
|
+
if (depth < 2) {
|
|
65
|
+
try {
|
|
66
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
67
|
+
if (entry.isDirectory() && !entry.isSymbolicLink() && entry.name.startsWith('dev-') &&
|
|
68
|
+
pidfileLive(join(root, entry.name), depth + 1)) return true;
|
|
69
|
+
}
|
|
70
|
+
} catch {/* No readable dev-process children. */}
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {unknown} session @param {string|undefined} activeLog
|
|
76
|
+
* @returns {{live?:boolean,latest?:number}} */
|
|
77
|
+
function sessionEvidence(session, activeLog) {
|
|
78
|
+
if (typeof session !== 'string' || !/^[\w.@:-]+$/u.test(session)) return {};
|
|
79
|
+
// A transcript's existence is not liveness: use its most recent write.
|
|
80
|
+
let latest = 0;
|
|
81
|
+
for (const root of [join(homedir(), '.claude/projects'), join(homedir(), '.codex/sessions')]) {
|
|
82
|
+
try {
|
|
83
|
+
for (const row of readdirSync(root, { recursive: true })) {
|
|
84
|
+
if (!String(row).includes(session)) continue;
|
|
85
|
+
const info = statSync(join(root, String(row)));
|
|
86
|
+
if (info.isFile()) latest = Math.max(latest, info.mtimeMs);
|
|
87
|
+
}
|
|
88
|
+
} catch {/* Unreadable evidence is skipped. */}
|
|
89
|
+
}
|
|
90
|
+
const listed = spawnSync('herdr', ['agent', 'list'], { encoding: 'utf8', timeout: 2000, maxBuffer: 8 * 1024 * 1024 });
|
|
91
|
+
if (listed.status === 0) {
|
|
92
|
+
try {
|
|
93
|
+
/** @type {{agent_session?:{value?:string}}[]} */
|
|
94
|
+
const agents = JSON.parse(listed.stdout)?.result?.agents ?? [];
|
|
95
|
+
if (agents.some(agent => agent.agent_session?.value === session)) return { live: true };
|
|
96
|
+
} catch {/* Unreadable evidence is skipped. */}
|
|
97
|
+
}
|
|
98
|
+
return { live: latest > 0 && activeHoursSince(new Date(latest), { log: activeLog }) < 24, latest };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Read-only classification. Unreadable process evidence always protects a folder.
|
|
102
|
+
* @param {string} path
|
|
103
|
+
* @param {{receipts?:string,activeHours?:number,cwdLive?:boolean,cwds?:string[]|null,sessionLive?:boolean,activeLog?:string}} [options] */
|
|
104
|
+
export function laneLive(path, { receipts = RECEIPTS, activeHours, cwdLive, cwds,
|
|
105
|
+
sessionLive, activeLog = process.env.WS_ACTIVE_HOURS_LOG } = {}) {
|
|
106
|
+
let root;
|
|
107
|
+
try { root = realpathSync(path); } catch { return { state: 'unknown', reason: 'folder unreadable' }; }
|
|
108
|
+
const directories = cwds === undefined && cwdLive === undefined ? processCwds() : cwds;
|
|
109
|
+
if (cwdLive === true || directories?.some(cwd => under(cwd, root)) || pidfileLive(root))
|
|
110
|
+
return { state: 'live', reason: 'a process cwd or pidfile is live' };
|
|
111
|
+
if (cwdLive === undefined && directories === null) return { state: 'live', reason: 'process evidence unreadable' };
|
|
112
|
+
const record = readOwner(root);
|
|
113
|
+
if (!record) {
|
|
114
|
+
const hours = activeHours ?? activeHoursSince(lstatSync(root).mtime, { log: activeLog });
|
|
115
|
+
return { state: 'unknown', reason: hours >= 72 ? 'no readable .owner; at least 72 active hours, investigate' : 'no readable .owner' };
|
|
116
|
+
}
|
|
117
|
+
const evidence = sessionLive === undefined ? sessionEvidence(record.session, activeLog) : { live: sessionLive, latest: 0 };
|
|
118
|
+
if (evidence.live) return { state: 'live', reason: 'owner session is present' };
|
|
119
|
+
const line = receipt(record.lane, receipts, record.receiptOffset);
|
|
120
|
+
if (line && /\s(?:DONE|ENDED):/u.test(line)) return { state: 'ended', reason: 'ending receipt' };
|
|
121
|
+
const since = evidence.latest !== undefined && evidence.latest > 0 ? evidence.latest : Date.parse(record.started ?? record.created ?? '');
|
|
122
|
+
const elapsed = activeHours ?? (Number.isFinite(since) ? activeHoursSince(new Date(since), { log: activeLog }) : 0);
|
|
123
|
+
if (elapsed >= 24) return { state: 'ended', reason: 'owner gone and silent for 24 active hours' };
|
|
124
|
+
return { state: 'live', reason: line ? 'non-ending receipt' : 'no ending receipt' };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
|
|
128
|
+
const [path] = process.argv.slice(2);
|
|
129
|
+
if (!path || process.argv.length !== 3) {
|
|
130
|
+
process.stderr.write('usage: node scripts/lane-live.mjs <lane-root>\n');
|
|
131
|
+
process.exitCode = 2;
|
|
132
|
+
} else {
|
|
133
|
+
const result = laneLive(path, { receipts: process.env.WS_LANE_RECEIPTS ?? RECEIPTS });
|
|
134
|
+
process.stdout.write(`${result.state }: ${ result.reason }\n`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// REPO-DISK J358: a read-only, compact leftovers list for the session brief and
|
|
3
|
+
// daily human audit. It deliberately has no delete operation.
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { lstatSync, readdirSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { join, resolve } from 'node:path';
|
|
8
|
+
import { pathToFileURL } from 'node:url';
|
|
9
|
+
import { laneLive } from './lane-live.mjs';
|
|
10
|
+
|
|
11
|
+
const ROOT = resolve(import.meta.dirname, '..');
|
|
12
|
+
const RECEIPTS = join(homedir(), '.cache/wildshard/lane-receipts.log');
|
|
13
|
+
|
|
14
|
+
/** @param {string} path */
|
|
15
|
+
function size(path) {
|
|
16
|
+
try { return Number.parseInt(execFileSync('du', ['-sk', path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim().split(/\s+/u)[0] ?? '0', 10); } catch { return 0; }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Read each direct tmp folder without mutating it.
|
|
20
|
+
* @param {{root?: string, receipts?: string}} [options] */
|
|
21
|
+
export function leftovers({ root = ROOT, receipts = RECEIPTS } = {}) {
|
|
22
|
+
const tmp = join(resolve(root), 'tmp');
|
|
23
|
+
let names = [];
|
|
24
|
+
try { names = readdirSync(tmp).sort(); } catch { return []; }
|
|
25
|
+
return names.flatMap(name => {
|
|
26
|
+
const path = join(tmp, name);
|
|
27
|
+
try { if (!lstatSync(path).isDirectory() || name.startsWith('.')) return []; } catch { return []; }
|
|
28
|
+
const liveness = laneLive(path, { receipts });
|
|
29
|
+
return [{ name, path, state: liveness.state, reason: liveness.reason, kib: size(path) }];
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** At most four brief lines. @param {ReturnType<typeof leftovers>} rows */
|
|
34
|
+
export function brief(rows) {
|
|
35
|
+
if (rows.length === 0) return [' leftovers: none'];
|
|
36
|
+
return [...rows].sort((a, b) => {
|
|
37
|
+
const state = a.state.localeCompare(b.state), byteOrder = b.kib - a.kib;
|
|
38
|
+
return state !== 0 ? state : byteOrder !== 0 ? byteOrder : a.name.localeCompare(b.name);
|
|
39
|
+
}).slice(0, 4)
|
|
40
|
+
.map(row => ` ${row.state}: tmp/${row.name} (${(row.kib / 1024 / 1024).toFixed(1)} GiB; ${row.reason})`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
|
|
44
|
+
const rootAt = process.argv.indexOf('--root');
|
|
45
|
+
const root = rootAt === -1 ? ROOT : resolve(process.argv[rootAt + 1] ?? '');
|
|
46
|
+
process.stdout.write(`${brief(leftovers({ root, receipts: process.env.WS_LANE_RECEIPTS ?? RECEIPTS })).join('\n')}\n`);
|
|
47
|
+
}
|
|
@@ -201,8 +201,29 @@ try {
|
|
|
201
201
|
Reflect.set(window,'__nativeCopy',original);
|
|
202
202
|
navigator.clipboard.writeText=text=>{
|
|
203
203
|
const raw=/** @type {import('../src/shared/engine/boot/timing').BootTiming} */(Reflect.get(window,'__bootTiming')).read();
|
|
204
|
-
const
|
|
205
|
-
|
|
204
|
+
const spans=raw.entries.filter(row=>row.end!==null&&row.end>row.start).sort((a,b)=>(b.end??0)-b.start-((a.end??0)-a.start)).slice(0,15);
|
|
205
|
+
const duration=(/** @type {Readonly<Record<string,unknown>>} */row)=>Number(row.duration??Number(row.responseEnd??0)-Number(row.startTime??0));
|
|
206
|
+
const resources=[...raw.resources].sort((a,b)=>duration(b)-duration(a)).slice(0,10);
|
|
207
|
+
const network=raw.resources.filter(row=>Number(row.transferSize)>0),cache=raw.resources.filter(row=>row.transferSize===0&&Number(row.encodedBodySize)>0);
|
|
208
|
+
const end=Math.max(0,...raw.entries.filter(row=>row.realm==='page').map(row=>row.end??row.start));
|
|
209
|
+
const edges=[{at:0,change:0},{at:end,change:0}];
|
|
210
|
+
const cover=(/** @type {unknown} */start,/** @type {unknown} */finish)=>{
|
|
211
|
+
if(typeof start!=='number'||typeof finish!=='number'||!Number.isFinite(start)||!Number.isFinite(finish))return;
|
|
212
|
+
const left=Math.max(0,start),right=Math.min(end,finish);
|
|
213
|
+
if(right>left)edges.push({at:left,change:1},{at:right,change:-1});
|
|
214
|
+
};
|
|
215
|
+
for(const row of raw.resources)cover(row.pageStart??(row.realm==='page'?row.startTime:undefined),row.pageEnd??(row.realm==='page'?row.responseEnd:undefined));
|
|
216
|
+
if(raw.navigation!==undefined)cover(raw.navigation.startTime??0,raw.navigation.responseEnd);
|
|
217
|
+
const gaps=/** @type {Array<[number,number]>} */([]);
|
|
218
|
+
let active=0,previous=0;
|
|
219
|
+
for(const edge of edges.sort((a,b)=>a.at-b.at)){
|
|
220
|
+
if(active===0&&edge.at-previous>500)gaps.push([previous/1000,(edge.at-previous)/1000]);
|
|
221
|
+
active+=edge.change;previous=edge.at;
|
|
222
|
+
}
|
|
223
|
+
const expected={entries:raw.entries.length,resources:raw.resources.length,
|
|
224
|
+
spans:spans.map(row=>`[${row.realm}] ${(row.start/1000).toFixed(2)} + ${(((row.end??0)-row.start)/1000).toFixed(2)}`),
|
|
225
|
+
slow:resources.map(row=>`${Number(row.transferSize)>0?row.transferSize:row.encodedBodySize??0} B ${(duration(row)/1000).toFixed(2)} s ${Number(row.transferSize)>0?'network':row.transferSize===0&&Number(row.encodedBodySize)>0?'cache':'unknown'}`),
|
|
226
|
+
gaps,totals:`network ${network.length} / ${network.reduce((sum,row)=>sum+Number(row.transferSize),0)} B; cache ${cache.length} / ${cache.reduce((sum,row)=>sum+Number(row.encodedBodySize),0)} B`};
|
|
206
227
|
const receipt={text,expected,settled:false,success:false};Reflect.set(window,'__copyReceipt',receipt);
|
|
207
228
|
return original(text).then(()=>{receipt.settled=true;receipt.success=true;return undefined;},(/** @type {unknown} */error)=>{receipt.settled=true;throw error;});
|
|
208
229
|
};
|
|
@@ -215,13 +236,25 @@ try {
|
|
|
215
236
|
const native=await navigator.clipboard.readText();
|
|
216
237
|
if(native!==receipt.text)return {ok:false,reason:'native readback differs'};
|
|
217
238
|
const marker='timeline (LS1):\n',at=native.indexOf(marker);
|
|
218
|
-
if(at===-1)return {ok:false,reason:'no
|
|
219
|
-
const
|
|
220
|
-
const
|
|
221
|
-
const
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
reason:
|
|
239
|
+
if(at===-1)return {ok:false,reason:'no timeline digest'};
|
|
240
|
+
const expected=receipt.expected,bytes=new TextEncoder().encode(native).byteLength;
|
|
241
|
+
const gapText=native.split('\n').find(line=>line.startsWith('request-free gaps >0.5 s'))?.split(': ')[1];
|
|
242
|
+
const gaps=/** @type {Array<[number,number]>} */([]);
|
|
243
|
+
for(const item of gapText===undefined||gapText==='none'?[]:gapText.split(', ')){
|
|
244
|
+
const match=/^(\d+(?:\.\d+)?)\+(\d+(?:\.\d+)?)(?: every (\d+(?:\.\d+)?) x(\d+))?$/u.exec(item);
|
|
245
|
+
if(match===null)return {ok:false,reason:'unreadable gap interval'};
|
|
246
|
+
for(let index=0;index<Number(match[4]??1);index++)gaps.push([Number(match[1])+index*Number(match[3]??0),Number(match[2])]);
|
|
247
|
+
}
|
|
248
|
+
const gapsMatch=gaps.length===expected.gaps.length&&gaps.every(([start,ms],index)=>{
|
|
249
|
+
const held=expected.gaps[index];return held!==undefined&&start.toFixed(3)===held[0].toFixed(3)&&ms.toFixed(3)===held[1].toFixed(3);
|
|
250
|
+
});
|
|
251
|
+
const complete=native.includes(`counts: ${expected.entries} spans (`)&&native.includes(`${expected.resources} resources;`)
|
|
252
|
+
&&native.includes('longest spans (start s + duration s):')&&native.includes('slowest resources (bytes, duration s, source):')
|
|
253
|
+
&&native.includes('request-free gaps >0.5 s')&&!native.includes('"entries":')
|
|
254
|
+
&&expected.spans.every((/** @type {string} */fact)=>native.includes(fact))
|
|
255
|
+
&&expected.slow.every((/** @type {string} */fact)=>native.includes(fact))&&native.includes(expected.totals)&&gapsMatch;
|
|
256
|
+
return {ok:complete&&bytes<6000&&document.querySelector('.ws-load-copy')?.textContent==='Copied',
|
|
257
|
+
reason:complete?`compact safe report: ${bytes} bytes, ${expected.entries} spans, ${expected.resources} resources`:'missing compact timeline facts'};
|
|
225
258
|
});
|
|
226
259
|
if(!copied.ok)faults.push(`copy diagnostics: ${copied.reason}`);
|
|
227
260
|
console.log(`${tag}: native copy ${copied.ok?'ok':'FAILED'} · ${copied.reason}`);
|
|
@@ -13,16 +13,18 @@
|
|
|
13
13
|
// --window 1496x717@2: a desktop window (Jake's Mac, 2992x1434 device pixels) on the desktop tier instead of the phone (NB5).
|
|
14
14
|
// --dpr: the render scale the game draws at (Graphics' saved pick; the viewport stays a 2x phone); NB5 reads 1 and 2.
|
|
15
15
|
// --seconds 600: NINE-DRAGON-BENCHMAX NB5's sustained run, printed per minute.
|
|
16
|
+
// --warm-base <url>: revisit on the same origin with another build, retaining the native caches.
|
|
17
|
+
// --assert-home-spans: NB13 refuses an unnamed home interval longer than one second.
|
|
16
18
|
import { writeFileSync } from 'node:fs';
|
|
17
19
|
import { parseArgs } from 'node:util';
|
|
18
20
|
import { chromium, devices } from 'playwright';
|
|
19
21
|
import { KEYCHAIN_ARGS } from '../chromium-keychain.mjs';
|
|
20
22
|
import { NAME_ASKED, developerSettings, saveFixture, levelDownloadFixtures, hideDeveloperOverlays } from '../debug-settings.mjs';
|
|
21
|
-
import { bootTimelineEntries, clockMarkExpression, profileAnchor, profileIdle, stageStalls, STALL_IDLE_SHARE, STALL_WINDOW_MS } from './stalls.mjs';
|
|
23
|
+
import { bootTimelineEntries, clockMarkExpression, profileAnchor, profileIdle, stageStalls, stageGaps, STALL_IDLE_SHARE, STALL_WINDOW_MS } from './stalls.mjs';
|
|
22
24
|
|
|
23
25
|
const { values } = parseArgs({ options: { base: { type: 'string' }, shard: { type: 'string', default: 'Nine' }, throttle: { type: 'string', default: '4' },
|
|
24
26
|
seconds: { type: 'string', default: '60' }, json: { type: 'string' }, profile: { type: 'string' },
|
|
25
|
-
dpr: { type: 'string', default: '2' }, window: { type: 'string' } } });
|
|
27
|
+
dpr: { type: 'string', default: '2' }, window: { type: 'string' }, 'warm-base': {type: 'string'}, 'assert-home-spans': {type: 'boolean', default: false} } });
|
|
26
28
|
if (values.base === undefined) { console.error('usage: benchmax.mjs --base <url> [--shard <card title regex>] [--throttle 4] [--seconds 60] [--dpr 2] [--json <file>] [--profile <file>]'); process.exit(2); }
|
|
27
29
|
// --window <css W>x<css H>@<scale>: a desktop browser window instead of the phone (NB5, Jake's Mac: 1496x717@2 is 2992x1434), desktop tier
|
|
28
30
|
const desktop = /^(\d+)x(\d+)@([\d.]+)$/u.exec(values.window ?? '');
|
|
@@ -52,8 +54,24 @@ try {
|
|
|
52
54
|
/** @param {string} selector */
|
|
53
55
|
const tap = selector => page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.click()`);
|
|
54
56
|
|
|
57
|
+
const visits = values['warm-base'] === undefined ? [base] : [base, values['warm-base']];
|
|
58
|
+
for (const [visit, visitBase] of visits.entries()) {
|
|
59
|
+
if (visit > 0) {
|
|
60
|
+
// Adopt the next build's document while keeping Cache Storage and disk state.
|
|
61
|
+
await page.evaluate(async () => { for (const registration of await navigator.serviceWorker.getRegistrations()) await registration.unregister(); });
|
|
62
|
+
await page.goto('about:blank');
|
|
63
|
+
}
|
|
64
|
+
await cdp.send('Network.enable');
|
|
65
|
+
/** @type {{url: string, fromServiceWorker: boolean, fromDiskCache: boolean}[]} */
|
|
66
|
+
const transfers = [];
|
|
67
|
+
/** @param {import('playwright').Request} request */
|
|
68
|
+
const workerRequest = request => { if (request.serviceWorker() !== null) transfers.push({url: request.url(), fromServiceWorker: false, fromDiskCache: false}); };
|
|
69
|
+
context.on('request', workerRequest);
|
|
70
|
+
/** @param {{type: string, response: {url: string, fromServiceWorker?: boolean, fromDiskCache?: boolean}}} event */
|
|
71
|
+
const resource = event => { if (event.type !== 'Preflight') transfers.push({url: event.response.url, fromServiceWorker: event.response.fromServiceWorker === true, fromDiskCache: event.response.fromDiskCache === true}); };
|
|
72
|
+
cdp.on('Network.responseReceived', resource);
|
|
55
73
|
// the title, as Jake enters a shard: SHARD SELECT, the card, ENTER WORLD (scripts/loading-flow/drive.mjs's route)
|
|
56
|
-
await page.goto(`${base}/`);
|
|
74
|
+
await page.goto(visitBase === base ? `${base}/` : visitBase);
|
|
57
75
|
if (!await until(`!!document.querySelector('.ws-main-select')?.getClientRects().length`, 120_000)) throw new Error('title never ready');
|
|
58
76
|
await sleep(1500);
|
|
59
77
|
await tap('.ws-main-select');
|
|
@@ -62,6 +80,8 @@ try {
|
|
|
62
80
|
const titles = await page.evaluate(`[...document.querySelectorAll('.ws-menu-card')].map(c => (c.querySelector('b')?.textContent ?? c.textContent ?? '').trim().slice(0, 40))`);
|
|
63
81
|
const target = titles.findIndex((/** @type {string} */ title) => shard.test(title));
|
|
64
82
|
if (target === -1) throw new Error(`no card matches ${shard} in ${JSON.stringify(titles)}`);
|
|
83
|
+
// Only the requested shard: opening the deck may prefetch the default card.
|
|
84
|
+
transfers.length = 0;
|
|
65
85
|
await tap(`.ws-menu-dots i[data-i="${target}"]`);
|
|
66
86
|
if (!await until(`document.querySelector('.ws-menu-card.selected')?.dataset.i === '${target}' && !document.querySelector('.ws-menu-play')?.disabled`, 15_000)) throw new Error(`${titles[target]} never selectable`);
|
|
67
87
|
await sleep(800);
|
|
@@ -99,7 +119,7 @@ try {
|
|
|
99
119
|
if (ready.start + ready.ms - at >= 100) gaps.push({ from: at - ready.start, ms: ready.start + ready.ms - at });
|
|
100
120
|
}
|
|
101
121
|
const control = entries.find(e => e.operation === 'app:control-ready')?.start ?? Number.NaN, first = Math.min(...stage.map(e => e.start));
|
|
102
|
-
const timeline = entries.map(e => ({ op: e.operation, realm: e.realm, start: Math.round(e.start), ms: e.end === null ? null : Math.round(e.end - e.start), result: e.result }));
|
|
122
|
+
const timeline = entries.map(e => ({ op: e.operation, realm: e.realm, start: Math.round(e.start), ms: e.end === null ? null : Math.round(e.end - e.start), result: e.result, detail: e.detail }));
|
|
103
123
|
// NB3: readyFrame's named parts of 100 ms or more (spans and waits), in start order
|
|
104
124
|
const readyParts = ready === undefined ? [] : done.filter(e => !e.op.startsWith('stage:') && !e.op.startsWith('game-stage:') && e.ms >= 100
|
|
105
125
|
&& e.start >= ready.start && e.start < ready.start + ready.ms).map(e => ({ op: e.op, from: e.start - ready.start, ms: e.ms }));
|
|
@@ -118,7 +138,8 @@ try {
|
|
|
118
138
|
.map(e => ({ n: n.split('.').pop(), start: Math.round(e.startTime), ms: Math.round(e.duration), key: e.detail?.key, layer: e.detail?.layer })));
|
|
119
139
|
const tileAttach = { raw, warm, tiles: attaches.length, span: attachSpan, contents: [...byContent.values()].sort((a, b) => b.ms - a.ms),
|
|
120
140
|
slowest: [...attaches].sort((a, b) => b.duration - a.duration).slice(0, 5).map(a => ({ key: a.detail?.key, layer: a.detail?.layer, ms: Math.round(a.duration), contents: a.detail?.contents })) };
|
|
121
|
-
|
|
141
|
+
const resources = performance.getEntriesByType('resource').map(r => ({url: r.name, start: r.startTime, transfer: r.transferSize, bytes: r.decodedBodySize}));
|
|
142
|
+
return { resources, workerResources: timing?.resources?.filter(r => r.realm !== 'page') ?? [], phases: { control, firstStage: first }, stage, waits, readyGaps: gaps, readyParts, scriptMemory, tileAttach, timeline };
|
|
122
143
|
})()`);
|
|
123
144
|
|
|
124
145
|
// the play: walk 10 s, then the hoverboard at boost; the game's own frame ring, read every 250 ms
|
|
@@ -182,7 +203,7 @@ try {
|
|
|
182
203
|
const s = ms => `${(ms / 1000).toFixed(1)} s`;
|
|
183
204
|
/** @param {number} n */
|
|
184
205
|
const f = n => n.toFixed(1);
|
|
185
|
-
console.log(`benchmax: ${titles[target]} at ${
|
|
206
|
+
console.log(`benchmax: ${titles[target]} at ${visitBase}, Chromium headless, CPU x${throttle}, ${desktop === null ? '402x874 @2 (phone)' : `${desktop[1]}x${desktop[2]} @${desktop[3]} (desktop)`}, packs, ${visit === 0 ? 'cold' : 'warm next build'}`);
|
|
186
207
|
console.log(`control ${s(load.phases.control)} after the world page's navigation · its first boot stage at ${s(load.phases.firstStage)}`);
|
|
187
208
|
console.log('stages, longest first:'); for (const e of load.stage.slice(0, 10)) console.log(` ${e.op.slice(6).padEnd(16)} ${s(e.ms)}`);
|
|
188
209
|
console.log('named waits >= 200 ms:'); for (const e of load.waits.slice(0, 10)) console.log(` ${e.op.slice(5, 90).padEnd(60)} ${s(e.ms)}`);
|
|
@@ -193,6 +214,28 @@ try {
|
|
|
193
214
|
console.log(` geometry warms: prepare ${ta.warm.prepare.n} · ${s(ta.warm.prepare.ms)} · parked draws ${ta.warm.draws.n} · ${s(ta.warm.draws.ms)}`);
|
|
194
215
|
for (const row of ta.slowest.slice(0, 2)) console.log(` slowest tile ${row.key} ${row.layer} ${s(row.ms)}: ${Object.entries(row.contents ?? {}).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([id, ms]) => `${id.slice(0, 28)} ${ms} ms`).join(', ')}`);
|
|
195
216
|
const bank = (/** @type {{ hits: number, misses: number, retained: number } | null} */ m) => m === null ? 'n/a' : `hits ${m.hits} · misses ${m.misses} · retained ${m.retained}`;
|
|
217
|
+
const home = /** @type {{op: string, start: number, ms: number}[]} */ (load.stage).find(row => row.op === 'stage:home');
|
|
218
|
+
/** @type {{op: string, realm: string, start: number, ms: number | null}[]} */
|
|
219
|
+
const timeline = load.timeline;
|
|
220
|
+
const homeGaps = stageGaps(timeline.map(row => ({operation: row.op, realm: row.realm, start: row.start, end: row.ms === null ? null : row.start + row.ms})), 'home');
|
|
221
|
+
load.homeGaps = homeGaps;
|
|
222
|
+
/** @type {Map<string, {url: string, read: number, decode: number}>} */
|
|
223
|
+
const homeTextures = new Map();
|
|
224
|
+
for (const part of timeline) {
|
|
225
|
+
if (home === undefined || part.start >= home.start + home.ms || part.start + (part.ms ?? 0) <= home.start) continue;
|
|
226
|
+
const match = /^texture:(read|decode) (.+)$/u.exec(part.op), url = match?.[2];
|
|
227
|
+
if (url === undefined) continue;
|
|
228
|
+
const record = homeTextures.get(url) ?? {url, read: 0, decode: 0};
|
|
229
|
+
if (match?.[1] === 'read') record.read += part.ms ?? 0; else record.decode += part.ms ?? 0;
|
|
230
|
+
homeTextures.set(url, record);
|
|
231
|
+
}
|
|
232
|
+
load.homeTextures = [...homeTextures.values()];
|
|
233
|
+
console.log(`home texture files (${homeTextures.size}), read / decode:`);
|
|
234
|
+
for (const file of homeTextures.values()) console.log(` ${file.url} · ${s(file.read)} / ${s(file.decode)}`);
|
|
235
|
+
console.log('home operations >= 100 ms:');
|
|
236
|
+
for (const part of timeline.filter(row => home !== undefined && (row.ms ?? 0) >= 100 && row.start >= home.start && row.start < home.start + home.ms && !/^(?:stage:|game-stage:|app:|sw:)/u.test(row.op)).sort((a, b) => (b.ms ?? 0) - (a.ms ?? 0)).slice(0, 16)) console.log(` ${part.op} · ${s(part.ms ?? 0)}`);
|
|
237
|
+
console.log(`home unlogged >= 100 ms: ${homeGaps.filter(row => row.end - row.start >= 100).map(row => `${s(row.end - row.start)} at +${s(row.start - (home?.start ?? 0))}`).join(', ') || 'none'}`);
|
|
238
|
+
if (values['assert-home-spans'] && (home === undefined || homeGaps.some(row => row.end - row.start > 1000))) { console.error('NB13: home has an unnamed stretch over 1 s (or no completed home stage)'); process.exitCode = 1; }
|
|
196
239
|
console.log(`script memory bank: at control ${bank(load.scriptMemory)} · after play ${bank(play.scriptMemory)}`);
|
|
197
240
|
console.log(`readyFrame unlogged >= 100 ms: ${load.readyGaps.length === 0 ? 'none' : load.readyGaps.map((/** @type {{ ms: number, from: number }} */ g) => `${s(g.ms)} at +${s(g.from)}`).join(', ')}`);
|
|
198
241
|
console.log(`play ${seconds} s: ${f(play.all.fps)} fps · frame p50 ${f(play.all.p50)} / p95 ${f(play.all.p95)} ms · gpu~ p50 ${f(play.all.gpu50)} / p95 ${f(play.all.gpu95)} ms · ${play.draws} draws · ${(play.triangles / 1e6).toFixed(2)} M tris · pixel ratio ${play.pixelRatio}`);
|
|
@@ -200,5 +243,12 @@ try {
|
|
|
200
243
|
console.log(`shadow pass: ${shadow.draws} of ${shadow.allDraws} draws · ${(shadow.triangles / 1e6).toFixed(2)} of ${(shadow.allTriangles / 1e6).toFixed(2)} M tris`);
|
|
201
244
|
play.minutes.forEach((/** @type {{ fps: number, p95: number, gpu95: number, draws95: number, tris95: number }} */ m, /** @type {number} */ i) => { console.log(` minute ${String(i + 1).padStart(2)}: ${f(m.fps)} fps · p95 ${f(m.p95)} ms · gpu~ p95 ${f(m.gpu95)} ms · draws p95 ${m.draws95} · tris p95 ${(m.tris95 / 1e6).toFixed(2)} M`); });
|
|
202
245
|
if (seconds <= 120) play.tens.forEach((/** @type {{ fps: number, p95: number, gpu95: number }} */ t, /** @type {number} */ i) => { console.log(` ${String(i * 10).padStart(3)}-${String(i * 10 + 10).padEnd(3)} s: ${f(t.fps)} fps · p95 ${f(t.p95)} ms · gpu~ p95 ${f(t.gpu95)} ms`); });
|
|
203
|
-
|
|
246
|
+
cdp.off('Network.responseReceived', resource);
|
|
247
|
+
context.off('request', workerRequest);
|
|
248
|
+
const resources = await page.evaluate(() => performance.getEntriesByType('resource').map(r => ({url: r.name, start: r.startTime, bytes: /** @type {PerformanceResourceTiming} */ (r).decodedBodySize})));
|
|
249
|
+
const network = transfers.filter(row => !row.fromServiceWorker && !row.fromDiskCache);
|
|
250
|
+
const cacheCheck = {spawnParts: network.filter(row => /\/assets\/spawn\/parts\/.*\.pack\.br/u.test(row.url)).length, paint: network.filter(row => /\/assets\/nine-dragon\/paint\/.*\.phone\.webp/u.test(row.url)).length};
|
|
251
|
+
console.log(`network: ${cacheCheck.spawnParts} spawn parts, ${cacheCheck.paint} phone paint files`);
|
|
252
|
+
if (values.json !== undefined) writeFileSync(visit === 0 ? values.json : values.json.replace(/(\.json)?$/u, '-warm.json'), `${JSON.stringify({ shard: titles[target], base: visitBase, throttle, dpr: values.dpr, load, play, shadow, where, cacheCheck, transfers, resources }, null, 1)}\n`);
|
|
253
|
+
}
|
|
204
254
|
} finally { await browser.close(); }
|
|
@@ -25,6 +25,8 @@ export function idleWithin(spans: readonly Span[], holes: readonly Span[], from:
|
|
|
25
25
|
export function busiestWindow(spans: readonly Span[], width: number): { at: number; ms: number };
|
|
26
26
|
/** Each listed stage's worst window of idle main thread with no page `wait:` entry open. */
|
|
27
27
|
export function stageStalls(entries: readonly StallEntry[], idle: readonly Span[], stages?: readonly string[]): StageStall[];
|
|
28
|
+
/** Uncovered wall-clock intervals inside a completed stage, ignoring broad parent envelopes. */
|
|
29
|
+
export function stageGaps(entries: readonly StallEntry[], stage: string): Span[];
|
|
28
30
|
/** Stage stalls at or over the share, as fault lines. */
|
|
29
31
|
export function stallFaults(entries: readonly StallEntry[], idle: readonly Span[]): string[];
|
|
30
32
|
/** Where the profile's clock meets the page's, from the clock mark's first sample. */
|
|
@@ -73,6 +73,19 @@ export function stageStalls(entries, idle, stages = STALL_STAGES) {
|
|
|
73
73
|
});
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
+
/** Wall-clock gaps between named operations inside one completed stage.
|
|
77
|
+
* Stage/app envelopes cannot explain their own contents; parallel operations
|
|
78
|
+
* cover their union, clipped to the stage. This reports CPU work as well as IO.
|
|
79
|
+
* @param {readonly StallEntry[]} entries @param {string} stage @returns {Span[]} */
|
|
80
|
+
export function stageGaps(entries, stage) {
|
|
81
|
+
const own = entries.find(row => row.realm === 'page' && row.operation === `stage:${stage}` && row.end !== null);
|
|
82
|
+
if (own === undefined || own.end === null) return [];
|
|
83
|
+
const named = entries.filter(row => row.realm === 'page' && row.end !== null
|
|
84
|
+
&& !/^(?:stage:|game-stage:|app:|sw:)/u.test(row.operation))
|
|
85
|
+
.map(row => ({start: row.start, end: row.end ?? row.start}));
|
|
86
|
+
return idleWithin([{start: own.start, end: own.end}], named, own.start, own.end);
|
|
87
|
+
}
|
|
88
|
+
|
|
76
89
|
/** Stage stalls as fault lines: a window whose unexplained idle reaches STALL_IDLE_SHARE of it.
|
|
77
90
|
* @param {readonly StallEntry[]} entries @param {readonly Span[]} idle @returns {string[]} */
|
|
78
91
|
export function stallFaults(entries, idle) {
|
package/scripts/mmo-bots.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// MMO-PLAN MP0.4: real-socket bots from this Mac (J202), against an isolated production-shaped replica or the staging socket.
|
|
3
3
|
// Never production (J205): there is no flag for it, and the bots refuse any socket but loopback and staging.
|
|
4
4
|
// node scripts/mmo-bots.mjs replica [--bots 32] [--seconds 120] [--seats 32] [--workers 4] [--cells driftwood-isle] [--database <url>]
|
|
5
|
+
// node scripts/mmo-bots.mjs replica --spread --cells driftwood-isle,nalati-grasslands (MP1.7: local cell distribution)
|
|
5
6
|
// node scripts/mmo-bots.mjs replica --remote wildshard [--cpus 9-13] ... (MP1.2: the replica on the box's cores, bots on this Mac)
|
|
6
7
|
// node scripts/mmo-bots.mjs replica [--remote wildshard] --server-from <main commit> ... (MP1.2: that commit's server code)
|
|
7
8
|
// node scripts/mmo-bots.mjs replica --remote wildshard-agent --bots-on-host [--bot-cpus 14-15] ... (MP1.2: bots on the box too)
|
|
@@ -25,7 +26,8 @@
|
|
|
25
26
|
// code, built here under the release's build name, so the release's packs still match it. The bots are built from the same
|
|
26
27
|
// commit, so their code and wire are the server's exactly. It must descend from the release's build; the report names it
|
|
27
28
|
// (`serverFrom`). Every value that reaches the host's shell is a checked slug, number, hex or fixed path.
|
|
28
|
-
// Everything goes in tmp/mmo-bots/<stamp
|
|
29
|
+
// Everything goes in tmp/mmo-bots/<stamp>/ by default, or in the bounded `--work-dir tmp/<lane>/...` path; the release tree is
|
|
30
|
+
// removed after the run and the report stays.
|
|
29
31
|
import { execFileSync, spawn } from 'node:child_process';
|
|
30
32
|
import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from 'node:crypto';
|
|
31
33
|
import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
@@ -47,7 +49,9 @@ const [mode = '', ...rest] = process.argv.slice(2);
|
|
|
47
49
|
const { values } = parseArgs({ args: rest, options: { bots: { type: 'string' }, seconds: { type: 'string' }, seats: { type: 'string', default: '32' }, workers: { type: 'string', default: '4' },
|
|
48
50
|
cells: { type: 'string', default: 'driftwood-isle' }, database: { type: 'string', default: 'memory:' }, keep: { type: 'boolean', default: false },
|
|
49
51
|
remote: { type: 'string' }, cpus: { type: 'string', default: '9-13' }, 'server-from': { type: 'string' },
|
|
50
|
-
'bots-on-host': { type: 'boolean', default: false }, 'bot-cpus': { type: 'string', default: '14-15' }, tailnet: { type: 'boolean', default: false }
|
|
52
|
+
'bots-on-host': { type: 'boolean', default: false }, 'bot-cpus': { type: 'string', default: '14-15' }, tailnet: { type: 'boolean', default: false },
|
|
53
|
+
'work-dir': { type: 'string' }, spread: { type: 'boolean', default: false } } });
|
|
54
|
+
if (values.spread && (mode !== 'replica' || values.remote !== undefined)) throw new Error('--spread is for a local replica');
|
|
51
55
|
const serverFrom = values['server-from'];
|
|
52
56
|
if (serverFrom !== undefined && (mode !== 'replica' || !/^[0-9a-f]{40}$/u.test(serverFrom))) throw new Error('--server-from is a full commit, for a replica');
|
|
53
57
|
// These reach the host's shell inside the replica's env line: only slugs and whole numbers.
|
|
@@ -60,7 +64,9 @@ if (botsOnHost && remote === undefined) throw new Error('--bots-on-host needs --
|
|
|
60
64
|
if (mode !== 'replica' && mode !== 'staging') { console.error('usage: mmo-bots.mjs replica|staging [--bots N] [--seconds S]'); process.exit(2); }
|
|
61
65
|
const bots = Number(values.bots ?? (mode === 'replica' ? 32 : 2)), seconds = Number(values.seconds ?? (mode === 'replica' ? 120 : 60));
|
|
62
66
|
if (!Number.isInteger(bots) || bots < 1 || bots > 64 || !Number.isFinite(seconds) || seconds < 5 || seconds > 3600) throw new Error('--bots 1..64, --seconds 5..3600');
|
|
63
|
-
const
|
|
67
|
+
const workRoot = absolute(ROOT, 'tmp'), workBase = absolute(ROOT, values['work-dir'] ?? 'tmp/mmo-bots');
|
|
68
|
+
if (workBase !== workRoot && !workBase.startsWith(`${workRoot}/`)) throw new Error('--work-dir stays under tmp/');
|
|
69
|
+
const stamp = new Date().toISOString().replaceAll(/[-:]/gu, '').replace(/\..*/u, 'Z'), work = join(workBase, stamp), tag = `${mode === 'replica' ? 'r' : 's'}${stamp.slice(9, 15)}`;
|
|
64
70
|
mkdirSync(work, { recursive: true });
|
|
65
71
|
/** @param {Record<string, unknown>} line */
|
|
66
72
|
const note = line => { const text = JSON.stringify({ at: 'mmo-bots', ...line }); console.info(text); writeFileSync(join(work, 'run.log'), `${text}\n`, { flag: 'a' }); };
|
|
@@ -223,7 +229,7 @@ if (botsOnHost && hostSsh !== null) {
|
|
|
223
229
|
const code = await new Promise(resolve => {
|
|
224
230
|
const child = botsOnHost && remote !== undefined
|
|
225
231
|
? spawn('ssh', ['-o', 'BatchMode=yes', ...ALIVE, remote, `cd ${away}/bots && exec taskset -c ${values['bot-cpus']} node "$HOME/${away}/bots/mmoBots.mjs" ${botArgs.join(' ')} "$HOME/${away}/bots.json" forwarded`], { stdio: ['ignore', 'pipe', 'inherit'] })
|
|
226
|
-
: spawn(process.execPath, [join(out, 'mmoBots.mjs'), ...botArgs, result, mode === 'replica' ? 'forwarded' : 'own'], { stdio: ['ignore', 'pipe', 'inherit'] });
|
|
232
|
+
: spawn(process.execPath, [join(out, 'mmoBots.mjs'), ...botArgs, result, mode === 'replica' ? 'forwarded' : 'own', values.spread ? values.cells : ''], { stdio: ['ignore', 'pipe', 'inherit'] });
|
|
227
233
|
botsChild = child;
|
|
228
234
|
child.stdout.on('data', (/** @type {Buffer} */ chunk) => { process.stdout.write(chunk); writeFileSync(join(work, 'bots.log'), chunk, { flag: 'a' }); });
|
|
229
235
|
child.on('exit', resolve);
|
|
@@ -231,7 +237,7 @@ const code = await new Promise(resolve => {
|
|
|
231
237
|
if (botsOnHost && hostSsh !== null) writeFileSync(result, hostSsh(`cat ${away}/bots.json`));
|
|
232
238
|
const after = mode === 'staging' ? await health() : null;
|
|
233
239
|
await stopRoom();
|
|
234
|
-
const full = readings.slice(playing).filter(row => row.players === bots);
|
|
240
|
+
const full = readings.slice(playing).filter(row => values.spread ? row.players > 0 : row.players === bots);
|
|
235
241
|
const report = { ...JSON.parse(readFileSync(result, 'utf8')), mode, exit: code, ...(serverFrom === undefined ? {} : { serverFrom }), ...(remote === undefined ? {} : { remote, cpus: values.cpus }),
|
|
236
242
|
...(botsOnHost ? { botsOnHost, botCpus: values['bot-cpus'] } : {}),
|
|
237
243
|
...(mode === 'staging' ? { stagingAfter: after } : {}),
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// oxlint-disable promise/prefer-await-to-callbacks -- Browser events, audio sources and the frame cap require browser callbacks.
|
|
2
|
+
// Manual MMO-PLAN GO8 proof: staging only, 30 fps, no physical phone.
|
|
3
|
+
// node scripts/mmo-grid-proof.mjs chromium|webkit tmp/<lane>/grid
|
|
4
|
+
import assert from 'node:assert/strict';
|
|
5
|
+
import {mkdirSync,writeFileSync} from 'node:fs';
|
|
6
|
+
import {join} from 'node:path';
|
|
7
|
+
import {chromium,webkit} from 'playwright';
|
|
8
|
+
import {KEYCHAIN_ARGS} from './chromium-keychain.mjs';
|
|
9
|
+
import {saveFixture} from './debug-settings.mjs';
|
|
10
|
+
import {guardStagingSockets,playerNameSource} from './staging-proof-lines.mjs';
|
|
11
|
+
import {FLOOR_GRID_ENTER} from './frame-floor-navigation.mjs';
|
|
12
|
+
|
|
13
|
+
/** Synthetic PCM only: headless proofs never open a real microphone. */
|
|
14
|
+
function proofMicrophone(){
|
|
15
|
+
if(!navigator.mediaDevices)return;
|
|
16
|
+
navigator.mediaDevices.getUserMedia=()=>{
|
|
17
|
+
const audio=new AudioContext(),osc=audio.createOscillator(),gain=audio.createGain(),dest=audio.createMediaStreamDestination();
|
|
18
|
+
Reflect.set(window,'__mmoAudio',{audio,osc,gain,dest});
|
|
19
|
+
osc.connect(gain);gain.connect(dest);osc.start();gain.gain.value=.6;
|
|
20
|
+
setInterval(()=>{gain.gain.value=gain.gain.value>0?0:.6;},600);
|
|
21
|
+
return audio.resume().then(()=>dest.stream);
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const engine=process.argv[2],out=process.argv[3];
|
|
26
|
+
assert.ok(engine==='chromium'||engine==='webkit');assert.ok(out?.startsWith('tmp/'));mkdirSync(out,{recursive:true});
|
|
27
|
+
const signed=await(await fetch('https://packs.wildshard.io/releases/staging.json')).json(),release=JSON.parse(signed.body);
|
|
28
|
+
assert.equal(release.channel,'staging');assert.equal(release.socket,'wss://rooms-staging.wildshard.io');
|
|
29
|
+
const version=await(await fetch('https://staging.wildshard.io/version.json')).json();assert.equal(version.build,release.engineBuild);
|
|
30
|
+
const browser=await(engine==='webkit'?webkit:chromium).launch({headless:true,args:engine==='webkit'?[]:[...KEYCHAIN_ARGS,'--use-angle=metal']});
|
|
31
|
+
/** @type {string[]} */ const faults=[];
|
|
32
|
+
/** @type {{engine:string,build:string,serial:number,coldTitle?:boolean,visibleAfterPlay?:boolean,leaveMs?:number,errors?:string[],locations?:{select:{inside:string|null,level:string|undefined},infinite:{inside:string|null,level:string|undefined}},chat?:boolean,voiceBothWays?:boolean}} */
|
|
33
|
+
const report={engine,build:version.build,serial:release.serial};
|
|
34
|
+
try {
|
|
35
|
+
const page=async()=>{const c=await browser.newContext({viewport:{width:960,height:600}});await c.grantPermissions(['microphone'],{origin:'https://staging.wildshard.io'});await saveFixture(c,{scope:'device',key:'devMode',data:true});await c.addInitScript(guardStagingSockets,release.socket);await c.addInitScript(proofMicrophone);await c.addInitScript(()=>{window.requestAnimationFrame=callback=>window.setTimeout(()=>callback(performance.now()),1000/30);window.cancelAnimationFrame=id=>window.clearTimeout(id);});const p=await c.newPage();p.on('pageerror',e=>faults.push(e.message));return p;};
|
|
36
|
+
const a=await page(),b=await page(),tag=Date.now().toString(36).slice(-5),nameA=`Seat ${tag} A`,nameB=`Seat ${tag} B`;
|
|
37
|
+
await a.goto('https://staging.wildshard.io/?chunk=driftwood-isle&fps=30&mute=1&nolock=1');
|
|
38
|
+
await a.locator('.ws-main-select').waitFor({timeout:45000});
|
|
39
|
+
report.coldTitle=await a.evaluate(()=>!window.__workerClient&&!window.__wildshard?.world);
|
|
40
|
+
assert.equal(report.coldTitle,true);console.log('PASS cold title has no world or seat');
|
|
41
|
+
await b.goto('https://staging.wildshard.io/?fps=30&mute=1&nolock=1');await b.locator('.ws-main-grid').waitFor({timeout:45000});await b.locator('.ws-main-grid').click();
|
|
42
|
+
/** @param {import('playwright').Page} p @param {string} name */
|
|
43
|
+
const named=async(p,name)=>{await p.locator('#ws-name-box input').waitFor({timeout:90000});await p.locator('#ws-name-box input').fill(name);await p.locator('#ws-name-box button[type=submit]').click();};
|
|
44
|
+
/** @param {import('playwright').Page} p @param {string} name @param {boolean} [alreadyNamed] */
|
|
45
|
+
const enter=async(p,name,alreadyNamed=false)=>{if(!alreadyNamed)await named(p,name);await p.waitForFunction(()=>window.__workerClient&&window.__wildshard?.world?.player,undefined,{timeout:90000});await p.evaluate(FLOOR_GRID_ENTER);await p.waitForFunction(()=>(window.__workerClient?.().frames??0)>30,undefined,{timeout:30000});};
|
|
46
|
+
await enter(b,nameB);console.log('observer seated');
|
|
47
|
+
const before=await b.evaluate(()=>window.__onlinePlayers?.()??[]);assert.equal(before.some(r=>new RegExp(playerNameSource(nameA),'u').test(r.name)),false);
|
|
48
|
+
await a.locator('.ws-main-select').click();await named(a,nameA);await a.locator('.ws-menu-play').click();await enter(a,nameA,true);console.log('subject seated after Play');
|
|
49
|
+
await b.waitForFunction(source=>window.__onlinePlayers?.().some(r=>new RegExp(source,'u').test(r.name)),playerNameSource(nameA),{timeout:15000});
|
|
50
|
+
report.visibleAfterPlay=true;
|
|
51
|
+
/** @param {import('playwright').Page} p */
|
|
52
|
+
const where=async p=>{const value=await p.evaluate(()=>({inside:(/** @type {{state:()=>{inside:string|null}}} */(window.__wildshard.shard.grid)).state().inside,level:window.__wildshard.world?.game.level.id}));return value;};
|
|
53
|
+
report.locations={select:await where(a),infinite:await where(b)};assert.equal(report.locations.select.inside,'driftwood-isle');assert.equal(report.locations.infinite.inside,'driftwood-isle');
|
|
54
|
+
await a.waitForFunction(source=>window.__onlinePlayers?.().some(r=>new RegExp(source,'u').test(r.name)&&r.modelled),playerNameSource(nameB),{timeout:15000});
|
|
55
|
+
/** @param {import('playwright').Page} p @param {string} line */
|
|
56
|
+
const say=async(p,line)=>{await p.locator('#ws-chat input').fill(line);await p.locator('#ws-chat input').press('Enter');};
|
|
57
|
+
await say(a,`grid A ${tag}`);await b.locator('#ws-chat',{hasText:`grid A ${tag}`}).waitFor({timeout:10000});await say(b,`grid B ${tag}`);await a.locator('#ws-chat',{hasText:`grid B ${tag}`}).waitFor({timeout:10000});report.chat=true;console.log('PASS both grid entry routes, bodies and chat');
|
|
58
|
+
for(const p of[a,b]){
|
|
59
|
+
await p.locator('#ws-voice').waitFor({timeout:30000});
|
|
60
|
+
await p.evaluate(proofMicrophone);
|
|
61
|
+
await p.locator('#ws-voice').click();
|
|
62
|
+
await p.locator('#ws-voice[data-state=on]').waitFor({timeout:30000}).catch(async(/** @type {unknown} */ error)=>{
|
|
63
|
+
console.log(JSON.stringify(await p.evaluate(()=>{
|
|
64
|
+
const button=document.querySelector('#ws-voice');
|
|
65
|
+
return {voice:button instanceof HTMLElement?button.dataset.state:undefined,tip:document.querySelector('#ws-voice-tip')?.textContent,mock:navigator.mediaDevices?.getUserMedia.toString().includes('AudioContext')};
|
|
66
|
+
})));
|
|
67
|
+
throw error;
|
|
68
|
+
});
|
|
69
|
+
await p.locator('#ws-chat input').click();
|
|
70
|
+
}
|
|
71
|
+
await a.locator('#ws-voice-peers button[data-linked=true]').waitFor({timeout:45000});await b.locator('#ws-voice-peers button[data-linked=true]').waitFor({timeout:45000});
|
|
72
|
+
for(const p of[a,b])await p.locator('#ws-voice-peers button[data-speaking=true]').waitFor({timeout:20000}).catch(async(/** @type {unknown} */ error)=>{console.log(JSON.stringify(await p.evaluate(()=>({audio:Reflect.get(window,'__mmoAudio')?.audio?.state,peers:document.querySelector('#ws-voice-peers')?.textContent}))));throw error;});report.voiceBothWays=true;
|
|
73
|
+
report.errors=faults;assert.deepEqual(faults,[]);console.log(JSON.stringify(report));writeFileSync(join(out,`grid-${engine}.json`),JSON.stringify(report,null,2));
|
|
74
|
+
} finally {await browser.close();}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// oxlint-disable promise/prefer-await-to-callbacks -- Browser events and the requestAnimationFrame cap require browser callback APIs.
|
|
2
|
+
// Manual MMO-PLAN GO1 proof: staging only, capped at 30 fps; both browsers close on every outcome.
|
|
3
|
+
// node scripts/mmo-seat-proof.mjs chromium|webkit tmp/<lane>/seat
|
|
4
|
+
import assert from 'node:assert/strict';
|
|
5
|
+
import {mkdirSync,writeFileSync} from 'node:fs';
|
|
6
|
+
import {join} from 'node:path';
|
|
7
|
+
import {chromium,webkit} from 'playwright';
|
|
8
|
+
import {KEYCHAIN_ARGS} from './chromium-keychain.mjs';
|
|
9
|
+
import {saveFixture} from './debug-settings.mjs';
|
|
10
|
+
import {guardStagingSockets,playerNameSource} from './staging-proof-lines.mjs';
|
|
11
|
+
import {FLOOR_GRID_ENTER} from './frame-floor-navigation.mjs';
|
|
12
|
+
|
|
13
|
+
const engine=process.argv[2],out=process.argv[3];
|
|
14
|
+
assert.ok(engine==='chromium'||engine==='webkit');assert.ok(out?.startsWith('tmp/'));mkdirSync(out,{recursive:true});
|
|
15
|
+
const signed=await(await fetch('https://packs.wildshard.io/releases/staging.json')).json(),release=JSON.parse(signed.body);
|
|
16
|
+
assert.equal(release.channel,'staging');assert.equal(release.socket,'wss://rooms-staging.wildshard.io');
|
|
17
|
+
const version=await(await fetch('https://staging.wildshard.io/version.json')).json();assert.equal(version.build,release.engineBuild);
|
|
18
|
+
const browser=await(engine==='webkit'?webkit:chromium).launch({headless:true,args:engine==='webkit'?[]:[...KEYCHAIN_ARGS,'--use-angle=metal']});
|
|
19
|
+
/** @type {string[]} */ const faults=[];
|
|
20
|
+
/** @type {{engine:string,build:string,serial:number,coldTitle?:boolean,visibleAfterPlay?:boolean,leaveMs?:number,errors?:string[]}} */
|
|
21
|
+
const report={engine,build:version.build,serial:release.serial};
|
|
22
|
+
try {
|
|
23
|
+
const page=async()=>{const c=await browser.newContext({viewport:{width:960,height:600}});await saveFixture(c,{scope:'device',key:'devMode',data:true});await c.addInitScript(guardStagingSockets,release.socket);await c.addInitScript(()=>{window.requestAnimationFrame=callback=>window.setTimeout(()=>callback(performance.now()),1000/30);window.cancelAnimationFrame=id=>window.clearTimeout(id);});const p=await c.newPage();p.on('pageerror',e=>faults.push(e.message));return p;};
|
|
24
|
+
const a=await page(),b=await page(),tag=Date.now().toString(36).slice(-5),nameA=`Seat ${tag} A`,nameB=`Seat ${tag} B`;
|
|
25
|
+
await a.goto('https://staging.wildshard.io/?chunk=driftwood-isle&fps=30&mute=1&nolock=1');
|
|
26
|
+
await a.locator('.ws-main-select').waitFor({timeout:45000});
|
|
27
|
+
report.coldTitle=await a.evaluate(()=>!window.__workerClient&&!window.__wildshard?.world);
|
|
28
|
+
assert.equal(report.coldTitle,true);console.log('PASS cold title has no world or seat');
|
|
29
|
+
await b.goto('https://staging.wildshard.io/?chunk=driftwood-isle&fps=30&mute=1&nolock=1&skipintro=1');
|
|
30
|
+
/** @param {import('playwright').Page} p @param {string} name */
|
|
31
|
+
const named=async(p,name)=>{await p.locator('#ws-name-box input').waitFor({timeout:90000});await p.locator('#ws-name-box input').fill(name);await p.locator('#ws-name-box button[type=submit]').click();};
|
|
32
|
+
/** @param {import('playwright').Page} p @param {string} name @param {boolean} [alreadyNamed] */
|
|
33
|
+
const enter=async(p,name,alreadyNamed=false)=>{if(!alreadyNamed)await named(p,name);await p.waitForFunction(()=>window.__workerClient&&window.__wildshard?.world?.player,undefined,{timeout:90000});await p.evaluate(FLOOR_GRID_ENTER);await p.waitForFunction(()=>(window.__workerClient?.().frames??0)>30,undefined,{timeout:30000});};
|
|
34
|
+
await enter(b,nameB);console.log('observer seated');
|
|
35
|
+
const before=await b.evaluate(()=>window.__onlinePlayers?.()??[]);assert.equal(before.some(r=>new RegExp(playerNameSource(nameA),'u').test(r.name)),false);
|
|
36
|
+
await a.locator('.ws-main-select').click();await named(a,nameA);await a.locator('.ws-menu-play').click();await enter(a,nameA,true);console.log('subject seated after Play');
|
|
37
|
+
await b.waitForFunction(source=>window.__onlinePlayers?.().some(r=>new RegExp(source,'u').test(r.name)),playerNameSource(nameA),{timeout:15000});
|
|
38
|
+
report.visibleAfterPlay=true;
|
|
39
|
+
await a.keyboard.press('Escape');await a.getByRole('button',{name:/exit to main/iu}).click();
|
|
40
|
+
const start=Date.now();await b.waitForFunction(source=>!window.__onlinePlayers?.().some(r=>new RegExp(source,'u').test(r.name)),playerNameSource(nameA),{timeout:5000});
|
|
41
|
+
report.leaveMs=Date.now()-start;report.errors=faults;assert.deepEqual(faults,[]);console.log(JSON.stringify(report));
|
|
42
|
+
writeFileSync(join(out,`seat-${engine}.json`),JSON.stringify(report,null,2));
|
|
43
|
+
} finally {await browser.close();}
|
|
@@ -200,7 +200,7 @@ for (const engineName of engines) {
|
|
|
200
200
|
let site = { base, close: () => Promise.resolve() }, socket = /^https:\/\/(staging|preview)\./u.test(base) ? arg('socket', 'wss://rooms-staging.wildshard.io') : arg('socket', '');
|
|
201
201
|
if (rigArg !== '') {
|
|
202
202
|
const [dist = '', work = '', keyFile = ''] = rigArg.split(','), { openRig, WORLD_PORT } = await import('./online-rig.mjs');
|
|
203
|
-
site = await openRig({ dist: absolute(dist), work: absolute(work, slug), keyFile, pgBin: 'memory:', pgData: '', shard: slug
|
|
203
|
+
site = await openRig({ dist: absolute(dist), work: absolute(work, slug), keyFile, pgBin: 'memory:', pgData: '', shard: slug });
|
|
204
204
|
socket = `ws://127.0.0.1:${String(WORLD_PORT)}`;
|
|
205
205
|
}
|
|
206
206
|
try {
|