@wildshard/engine 0.1.22 → 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.
Files changed (100) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +2 -0
  3. package/lint/sim-players.json +2 -13
  4. package/package.json +9 -2
  5. package/scripts/apfs-clone.mjs +5 -2
  6. package/scripts/app-build/catalogue.ts +39 -8
  7. package/scripts/app-build/serviceWorker.ts +4 -1
  8. package/scripts/app-build/splitOutput.mjs +33 -11
  9. package/scripts/ci-pack.mjs +3 -3
  10. package/scripts/engine-ci-shard.mjs +11 -0
  11. package/scripts/fight-page-census.mjs +131 -0
  12. package/scripts/goldens/board.py +44 -11
  13. package/scripts/goldens/native-residency.d.mts +1 -0
  14. package/scripts/goldens/native-residency.mjs +18 -4
  15. package/scripts/keep-copy.mjs +120 -0
  16. package/scripts/land.mjs +36 -6
  17. package/scripts/lane-live.mjs +136 -0
  18. package/scripts/leftovers-report.mjs +47 -0
  19. package/scripts/loading-card-proof.mjs +42 -9
  20. package/scripts/loading-flow/benchmax.mjs +57 -7
  21. package/scripts/loading-flow/stalls.d.mts +2 -0
  22. package/scripts/loading-flow/stalls.mjs +13 -0
  23. package/scripts/mmo-bots.mjs +5 -3
  24. package/scripts/mmo-grid-proof.mjs +74 -0
  25. package/scripts/mmo-seat-proof.mjs +43 -0
  26. package/scripts/nightly-heads.ts +13 -13
  27. package/scripts/nightly-model.ts +26 -12
  28. package/scripts/nightly.proof.ts +18 -5
  29. package/scripts/nightly.ts +13 -8
  30. package/scripts/no-astc-boot.mjs +77 -0
  31. package/scripts/physics-route.json +6 -6
  32. package/scripts/pins-reuse.mjs +1 -0
  33. package/scripts/pins-staging.ts +54 -0
  34. package/scripts/pins.ts +5 -0
  35. package/scripts/ring3.proof.ts +71 -0
  36. package/scripts/ring3.ts +100 -0
  37. package/scripts/scratch-dir.mjs +31 -12
  38. package/scripts/scratch-sweep.mjs +15 -23
  39. package/scripts/server-release/items.d.mts +7 -0
  40. package/scripts/server-release/items.mjs +28 -0
  41. package/scripts/server-release/publish.mjs +9 -1
  42. package/scripts/side-parity.mjs +1 -1
  43. package/scripts/test-products.json +1 -0
  44. package/scripts/tsconfig.json +2 -0
  45. package/scripts/vitest-ci-files.ts +5 -1
  46. package/scripts/vps/wildshard-config +106 -1
  47. package/scripts/warm-native-chrome.mjs +9 -3
  48. package/scripts/worker-client-fights.mjs +9 -3
  49. package/scripts/worktree-reap.mjs +15 -131
  50. package/scripts/worktree.mjs +92 -12
  51. package/src/client/engine/audio/audioLog.ts +7 -2
  52. package/src/client/engine/boot/diagnostics.ts +69 -1
  53. package/src/client/engine/core/ktx2.ts +5 -3
  54. package/src/client/engine/core/ktx2Zstd.ts +2 -1
  55. package/src/client/engine/pwa/sw.js +26 -8
  56. package/src/client/engine/render/dataLook.ts +14 -7
  57. package/src/client/engine/render/lookLight.ts +64 -20
  58. package/src/client/engine/ui/Loading.ts +6 -8
  59. package/src/client/engine/ui/lookLightOption.ts +1 -1
  60. package/src/client/game/audio/cueDirector.ts +2 -1
  61. package/src/client/game/boss/arenaRoom.ts +4 -3
  62. package/src/client/game/boss/roamingProjection.ts +1 -1
  63. package/src/client/game/devScene/hook.ts +1 -1
  64. package/src/client/game/devScene/liveLook.ts +1 -1
  65. package/src/client/game/grid/dataCellKit.ts +9 -1
  66. package/src/client/game/grid/products.ts +21 -7
  67. package/src/client/game/grid/session.ts +6 -4
  68. package/src/client/game/population/signals.ts +1 -1
  69. package/src/client/game/quest/chapterDirector.ts +1 -0
  70. package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
  71. package/src/client/game/shardfile/clientWorker.ts +22 -6
  72. package/src/client/game/shardfile/look.ts +1 -1
  73. package/src/client/game/shardfile/runtimeProduct.ts +9 -5
  74. package/src/client/game/shardfile/wirePage.ts +5 -2
  75. package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
  76. package/src/cook/game/cookWorker.ts +8 -5
  77. package/src/cook/game/tierTextures.ts +5 -3
  78. package/src/server/engine/net/simWorld.ts +3 -4
  79. package/src/server/game/grid/cellHome.ts +58 -0
  80. package/src/server/game/grid/simulation.ts +5 -4
  81. package/src/server/game/plugin/mover.ts +18 -14
  82. package/src/server/game/shardfile/declaredKitItems.ts +31 -7
  83. package/src/server/host/bake/headlessWorker.ts +3 -3
  84. package/src/server/host/dedicated/cellWorker.ts +4 -2
  85. package/src/server/host/dedicated/main.ts +7 -4
  86. package/src/server/host/dedicated/packReader.ts +15 -2
  87. package/src/server/host/dedicated/playerStore.ts +1 -1
  88. package/src/server/host/headlessRuntime.ts +11 -6
  89. package/src/server/host/standalone/cellWorld.ts +20 -6
  90. package/src/server/host/standalone/gridServer.ts +3 -1
  91. package/src/server/host/standalone/roadWorld.ts +6 -0
  92. package/src/shared/engine/physics/gridBorders.ts +15 -1
  93. package/src/shared/engine/sim/snapshot.ts +5 -5
  94. package/src/shared/game/ledger.ts +13 -4
  95. package/src/shared/game/loot/platformCatalogue.ts +14 -0
  96. package/src/shared/game/quest/ledger.ts +3 -3
  97. package/src/shared/game/shardfile/items.ts +9 -1
  98. package/src/shared/host/headlessJourney.ts +3 -3
  99. package/src/shared/host/headlessTape.ts +7 -6
  100. package/src/shared/host/releaseRows.ts +4 -1
@@ -38,17 +38,31 @@ export async function goldenRefinementBinding(base,source) {
38
38
  throw new Error('Native reader requires the served Nine product');
39
39
  const servedIndex=Buffer.from(await(await fetch(new URL('/shardfiles/nine-dragon-stack/shard.json',base))).arrayBuffer());
40
40
  if(!servedIndex.equals(index))throw new Error('Served Nine index differs from exact preview');
41
- const code=`b/${source.build}`,codeFolder=existsSync(join(root,code))?code:'assets',dist=join(root,codeFolder);
42
- const chunks=readdirSync(dist).filter(file=>file.endsWith('.js')).map(file=>({file,bytes:readFileSync(join(dist,file))}))
41
+ const chunks=buildCodeChunks(root,source.build).map(chunk=>({chunk,bytes:readFileSync(join(root,chunk))}))
43
42
  .filter(row=>row.bytes.includes('Invalid or duplicate refinement job'));
44
43
  if (chunks.length!==1) throw new Error('Native refinement chunk is missing or ambiguous');
45
- const {file,bytes}=chunks[0],binding=refinementExports(bytes.toString('utf8'));
46
- const chunk=`/${codeFolder}/${file}`,served=Buffer.from(await(await fetch(new URL(chunk,base))).arrayBuffer());
44
+ const {chunk,bytes}=chunks[0],binding=refinementExports(bytes.toString('utf8'));
45
+ const served=Buffer.from(await(await fetch(new URL(chunk,base))).arrayBuffer());
47
46
  if (!served.equals(bytes)) throw new Error('Served native refinement differs from exact preview');
48
47
  return {...binding,sha:pinned?.sha??source.sha,build:source.build,preview:pinned===undefined?'working-tree':'pinned',
49
48
  nineIndexSHA256:createHash('sha256').update(index).digest('hex'),chunk,chunkSHA256:createHash('sha256').update(served).digest('hex')};
50
49
  }
51
50
 
51
+ /** This build's code chunks, as served paths: its own folder `b/<build>`, plus the
52
+ * content-named chunks in the shared `b/c` that its `importmap.json` names (J217
53
+ * LD6). The shared folder can also hold other builds' chunks, so it is never
54
+ * listed. A build without `b/<build>` keeps everything in `assets/`.
55
+ * @param {string} root the preview's dist @param {string} build */
56
+ export function buildCodeChunks(root,build) {
57
+ const own=`b/${build}`;
58
+ if (!existsSync(join(root,own))) return readdirSync(join(root,'assets')).filter(file=>file.endsWith('.js')).map(file=>`/assets/${file}`);
59
+ const chunks=readdirSync(join(root,own)).filter(file=>file.endsWith('.js')).map(file=>`/${own}/${file}`);
60
+ const map=join(root,'importmap.json');
61
+ if (existsSync(map)) for (const target of Object.values(JSON.parse(readFileSync(map,'utf8')).imports??{}))
62
+ if (typeof target==='string'&&target.startsWith('/b/c/')&&target.endsWith('.js')&&!chunks.includes(target)) chunks.push(target);
63
+ return chunks;
64
+ }
65
+
52
66
  /** Fail closed when the compiler shape changes; no guessed export or copied release binding.
53
67
  * @param {string} source */
54
68
  export function refinementExports(source) {
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+ // REPO-DISK DK18a/J358: preserve a worktree before a human removes it. This
3
+ // helper only writes a copy; it has no delete operation.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, writeFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { basename, join, resolve } from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+
11
+ const MAX_UNTRACKED_BYTES = 50 * 1024 * 1024;
12
+ const DEFAULT_KEEP_ROOT = join(homedir(), '.cache/wildshard/session-keep');
13
+ const RETENTION_DAYS = 14;
14
+
15
+ /** @param {string} cwd @param {string[]} args */
16
+ const run = (cwd, args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
17
+ /** @param {string} cwd @param {string[]} args */
18
+ const text = (cwd, args) => {
19
+ const result = run(cwd, args);
20
+ if (result.status !== 0) throw new Error(`keep-copy: git ${args.join(' ')} failed: ${result.stderr.trim()}`);
21
+ return result.stdout;
22
+ };
23
+
24
+ /** @param {string} path @param {string} root @param {Date} now */
25
+ function destination(path, root, now) {
26
+ const day = now.toISOString().slice(0, 10);
27
+ const stamp = now.toISOString().slice(11, 19).replaceAll(':', '-');
28
+ return join(root, day, `${basename(path)}__${process.pid}-${stamp}-${randomUUID()}`);
29
+ }
30
+
31
+ /** @param {string} path @param {string[]} files */
32
+ function bytes(path, files) {
33
+ return files.reduce((total, file) => total + lstatSync(join(path, file)).size, 0);
34
+ }
35
+
36
+ /** Snapshot every recoverable byte before copying and again after stopping
37
+ * writers. Status alone misses edits within an existing untracked folder.
38
+ * @param {string} root */
39
+ export function worktreeState(root) {
40
+ const hash = createHash('sha256');
41
+ for (const file of text(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean)) {
42
+ const path = join(root, file), info = lstatSync(path);
43
+ if (!info.isFile() && !info.isSymbolicLink()) throw new Error(`cannot snapshot ${file}`);
44
+ hash.update(JSON.stringify([file, info.mode, info.size]));
45
+ hash.update(info.isSymbolicLink() ? readlinkSync(path) : readFileSync(path));
46
+ }
47
+ return JSON.stringify([
48
+ text(root, ['rev-parse', 'HEAD']), text(root, ['symbolic-ref', '--quiet', 'HEAD']),
49
+ text(root, ['status', '--porcelain', '--untracked-files=all']),
50
+ text(root, ['diff', '--binary', 'HEAD']), text(root, ['diff', '--cached', '--binary', 'HEAD']),
51
+ hash.digest('hex'),
52
+ ]);
53
+ }
54
+
55
+ /** Copy recoverable Git worktree state. It never deletes or mutates `path`.
56
+ * @param {string} path @param {{keepRoot?: string, now?: Date}} [options] */
57
+ export function keepCopy(path, { keepRoot = DEFAULT_KEEP_ROOT, now = new Date() } = {}) {
58
+ const root = resolve(path);
59
+ if (!existsSync(root)) throw new Error(`keep-copy: ${root} does not exist`);
60
+ const repo = text(root, ['rev-parse', '--show-toplevel']).trim();
61
+ const files = text(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean);
62
+ const dir = destination(root, resolve(keepRoot), now);
63
+ mkdirSync(dir, { recursive: true });
64
+ /** @type {{source:string,repository:string,created:string,bundle:boolean,patch:boolean,untracked:string|{files:number,bytes:number}}} */
65
+ const manifest = { source: root, repository: repo, created: now.toISOString(), bundle: false, patch: false, untracked: 'none' };
66
+ const unpublished = run(root, ['log', '--branches', '--tags', '--not', '--remotes', '--format=%H']);
67
+ if (unpublished.status !== 0) throw new Error(`keep-copy: cannot inspect unpublished commits: ${unpublished.stderr.trim()}`);
68
+ if (unpublished.stdout.trim() !== '') {
69
+ text(root, ['bundle', 'create', join(dir, 'unpublished.bundle'), '--branches', '--tags', '--not', '--remotes']);
70
+ manifest.bundle = true;
71
+ }
72
+ const patch = text(root, ['diff', '--binary', 'HEAD']);
73
+ const indexPatch = text(root, ['diff', '--cached', '--binary', 'HEAD']);
74
+ if (indexPatch !== '') writeFileSync(join(dir, 'index.patch'), indexPatch);
75
+ if (patch !== '') {
76
+ writeFileSync(join(dir, 'tracked.patch'), patch);
77
+ manifest.patch = true;
78
+ }
79
+ if (files.length > 0) {
80
+ const total = bytes(root, files);
81
+ if (total <= MAX_UNTRACKED_BYTES) {
82
+ const archive = spawnSync('tar', ['-czf', join(dir, 'untracked.tgz'), '--', ...files], { cwd: root, encoding: 'utf8' });
83
+ if (archive.status !== 0) throw new Error(`keep-copy: tar failed: ${archive.stderr.trim()}`);
84
+ manifest.untracked = { files: files.length, bytes: total };
85
+ } else throw new Error('keep-copy: untracked files exceed 50 MiB; source must be kept');
86
+ }
87
+ writeFileSync(join(dir, 'MANIFEST.json'), `${JSON.stringify(manifest, null, 2)}\n`);
88
+ return { dir, manifest };
89
+ }
90
+
91
+ /** List retention candidates for a human audit. This never removes a copy.
92
+ * @param {{keepRoot?: string, now?: Date}} [options] */
93
+ export function oldKeepCopies({ keepRoot = DEFAULT_KEEP_ROOT, now = new Date() } = {}) {
94
+ if (!existsSync(keepRoot)) return [];
95
+ const rows = [];
96
+ for (const day of readdirSync(keepRoot, { withFileTypes: true }).filter(entry => entry.isDirectory())) {
97
+ const parent = join(keepRoot, day.name);
98
+ for (const child of readdirSync(parent, { withFileTypes: true }).filter(entry => entry.isDirectory())) {
99
+ const manifest = join(parent, child.name, 'MANIFEST.json');
100
+ try {
101
+ const created = new Date(JSON.parse(readFileSync(manifest, 'utf8')).created);
102
+ const age = Math.floor((now.getTime() - created.getTime()) / 86_400_000);
103
+ if (Number.isFinite(age) && age >= RETENTION_DAYS) rows.push({ path: join(parent, child.name), age });
104
+ } catch {/* Unreadable evidence is skipped. */}
105
+ }
106
+ }
107
+ return rows.sort((left, right) => right.age - left.age || left.path.localeCompare(right.path));
108
+ }
109
+
110
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
111
+ try {
112
+ const [path] = process.argv.slice(2);
113
+ if (!path || process.argv.length !== 3) throw new Error('usage: node scripts/keep-copy.mjs <worktree>');
114
+ const result = keepCopy(path, { keepRoot: process.env.WS_SESSION_KEEP_ROOT ?? DEFAULT_KEEP_ROOT });
115
+ process.stdout.write(`${result.dir}\n`);
116
+ } catch (error) {
117
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
118
+ process.exitCode = 1;
119
+ }
120
+ }
package/scripts/land.mjs CHANGED
@@ -15,6 +15,7 @@
15
15
  // 8. Delete origin's plan branch and remove this worktree (--keep skips it).
16
16
  // Main's CI runs after every landing; if it goes red, the lane that landed last fixes it forward or reverts it.
17
17
  import {execFileSync,spawn,spawnSync} from 'node:child_process';
18
+ import {keepCopy,worktreeState} from './keep-copy.mjs';
18
19
  import {appendFileSync,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs';
19
20
  import {homedir} from 'node:os';
20
21
  import {dirname,join,resolve} from 'node:path';
@@ -159,8 +160,8 @@ function ghApi(repo,path){
159
160
  }
160
161
 
161
162
  /** J193/J200: `quarantine (n)` jobs run quarantined files with their ordinary exit code and are continue-on-error;
162
- * they are red by design until rewritten and never block a landing. So is J186's report-only `boundaries` job (EV3b). */
163
- const NONBLOCKING_JOB=/^(?:quarantine|boundaries)(?: \(\d+\))?$/u;
163
+ * they are red by design until rewritten and never block a landing. Boundaries blocks after TS15's green soak. */
164
+ const NONBLOCKING_JOB=/^quarantine(?: \(\d+\))?$/u;
164
165
  const FAILED=new Set(['failure','timed_out','cancelled','startup_failure']);
165
166
 
166
167
  /** A run's failed jobs, split into the blocking ones and the non-blocking quarantine ones.
@@ -825,16 +826,45 @@ class Landing{
825
826
  const deleted=tryGit(this.root,['push','--quiet',`--force-with-lease=refs/heads/${this.branch}:${this.planTip}`,'origin','--delete',this.branch]);
826
827
  parts.push(deleted.status===0?`origin ${this.branch} deleted`:`origin ${this.branch} kept (${deleted.stderr.trim().split('\n').at(-1)??'push refused'})`);
827
828
  }
828
- const dirty=tryGit(this.root,['status','--porcelain']).stdout.trim();
829
+ const dirtyResult=tryGit(this.root,['status','--porcelain','--untracked-files=all']);
830
+ const dirty=dirtyResult.stdout.trimEnd();
831
+ const generatedOnly=dirty!==''&&dirty.split('\n').every(line=>/^[ MAD?]{2} (?:[^"\n]+\.generated\.ts|public\/assets\/gpu\/[^"\n]+)$/u.test(line));
832
+ const patchBefore=tryGit(this.root,['diff','--binary','HEAD']);
829
833
  const now=tryGit(this.root,['symbolic-ref','--quiet','HEAD']).stdout.trim(),at=tryGit(this.root,['rev-parse','HEAD']).stdout.trim();
830
834
  if(now!==`refs/heads/${this.branch}`||at!==head)parts.push(`worktree kept: HEAD moved off ${this.branch} ${short(head)} after landing`);
831
- else if(dirty!=='')parts.push(`worktree kept: ${dirty.split('\n').length} uncommitted or untracked path(s)`);
835
+ else if(dirtyResult.status!==0||patchBefore.status!==0)parts.push('worktree kept: status unreadable');
836
+ else if(dirty!==''&&!generatedOnly)parts.push(`worktree kept: ${dirty.split('\n').length} uncommitted or untracked path(s)`);
832
837
  else{
838
+ // J358's sole removal exception: this land owns this just-landed worktree.
839
+ // Copy first; any failure retains the source and its local branch.
840
+ let before;
841
+ try{
842
+ before=worktreeState(this.root);
843
+ const saved=keepCopy(this.root,{keepRoot:this.env.WS_SESSION_KEEP_ROOT});
844
+ this.say('copied',`recoverable worktree state saved at ${saved.dir}`);
845
+ }catch(error){
846
+ const line=parts.concat(`worktree kept: copy failed (${error instanceof Error?error.message:String(error)})`).join('; ');
847
+ this.say('cleaned',line);
848
+ return line;
849
+ }
850
+ const unchanged=()=>{try{return worktreeState(this.root)===before;}catch{return false;}};
851
+ if(!unchanged()){
852
+ const line=parts.concat('worktree kept: changed during copy').join('; ');
853
+ this.say('cleaned',line);return line;
854
+ }
833
855
  // TEST-SPEED FL30: nothing started here may outlive the folder (an orphaned Vitest held the CPU slots).
834
856
  let stopped=[];
835
- try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{/* Listing failed: remove as before. */}
857
+ try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{
858
+ const line=parts.concat('worktree kept: process cleanup failed').join('; ');
859
+ this.say('cleaned',line);return line;
860
+ }
836
861
  if(stopped.length>0)parts.push(`stopped ${String(stopped.length)} process(es) still running there (pid ${stopped.join(', ')})`);
837
- const removed=tryGit(canonical,['worktree','remove',this.root]);
862
+ // Shutdown handlers may write after the copy. Protect their last writes.
863
+ if(!unchanged()){
864
+ const line=parts.concat('worktree kept: changed during process cleanup').join('; ');
865
+ this.say('cleaned',line);return line;
866
+ }
867
+ const removed=tryGit(canonical,['worktree','remove',...(generatedOnly?['--force']:[]),this.root]);
838
868
  if(removed.status===0){
839
869
  tryGitLocked(canonical,['update-ref','-d',`refs/heads/${this.branch}`,head],process.env,this.retry);
840
870
  parts.push(`worktree and ${this.branch} removed; continue from ${canonical}`);
@@ -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 expected={entries:raw.entries.map(({id,start,end})=>({id,start,end})),resources:raw.resources.length,
205
- counters:Object.keys(raw.counters).length,realms:Object.keys(raw.realms??{}).length};
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 complete timeline'};
219
- const parsed=JSON.parse(native.slice(at+marker.length)),expected=receipt.expected;
220
- const entries=parsed.entries.map((/** @type {{id:number,start:number,end:number|null}} */{id,start,end})=>({id,start,end}));
221
- const complete=JSON.stringify(entries)===JSON.stringify(expected.entries)&&parsed.resources.length===expected.resources
222
- &&Object.keys(parsed.counters).length===expected.counters&&parsed.realms.length===expected.realms;
223
- return {ok:complete&&parsed.exportPrivacy==='own-paths-other-urls-and-free-text-removed'&&document.querySelector('.ws-load-copy')?.textContent==='Copied',
224
- reason:complete?`complete safe report: ${entries.length} events`:'timeline or numeric facts truncated'};
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
- return { phases: { control, firstStage: first }, stage, waits, readyGaps: gaps, readyParts, scriptMemory, tileAttach, timeline };
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 ${base}, Chromium headless, CPU x${throttle}, ${desktop === null ? '402x874 @2 (phone)' : `${desktop[1]}x${desktop[2]} @${desktop[3]} (desktop)`}, packs, cold`);
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
- if (values.json !== undefined) writeFileSync(values.json, `${JSON.stringify({ shard: titles[target], base, throttle, dpr: values.dpr, load, play, shadow, where }, null, 1)}\n`);
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. */