@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
|
@@ -1,27 +1,9 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// A worktree at <canonical>/.worktrees/<slug> on plan/<slug> is reaped only when all of these hold:
|
|
5
|
-
// - landed: the branch tip is on origin/main itself (`merge-base --is-ancestor`; land fast-forwards), after a fetch;
|
|
6
|
-
// - clean: `git status --porcelain` is empty (tracked edits and untracked files; ignored build output doesn't count);
|
|
7
|
-
// - idle: no process has its working directory inside it (orphans reparented to pid 1 are stopped first, FL30), no `land` holds its lock, no `worktree new` is running,
|
|
8
|
-
// and nothing in it (index, HEAD, reflog, tip commit) changed for --grace hours (default 24: a lane between
|
|
9
|
-
// landings keeps its worktree). The reaper then holds the worktree's land lock and checks HEAD, the tree, the
|
|
10
|
-
// processes and setup again before it removes anything; a worktree whose folder resolves outside
|
|
11
|
-
// <canonical>/.worktrees/ is skipped.
|
|
12
|
-
// Then: `git worktree remove` (never --force), the local branch deleted only while it still points at the checked
|
|
13
|
-
// commit, and `origin plan/<slug>` deleted (`git push --delete`, which the pre-push lets through without a gate)
|
|
14
|
-
// only if the remote branch is landed too, under a lease on the SHA it had. A worktree that fails any check is kept
|
|
15
|
-
// and named with the reason; an unlanded branch, local or remote, is never touched. Every run appends one receipt.
|
|
16
|
-
// REPO-DISK DK11: a removed worktree takes its tmp/ and build output with it (they are ignored files inside it), and
|
|
17
|
-
// a real run's receipt records the `df` bytes it freed (other writers move df too, so it is a measure, not a ledger).
|
|
18
|
-
// A worktree kept because it is unlanded or dirty and untouched for --stale hours (default 72) is named in the
|
|
19
|
-
// receipt with its `du` size, so the coordinator's brief can put it to its owner.
|
|
1
|
+
// REPO-DISK J358: report plan-worktree liveness for a human audit.
|
|
2
|
+
// This command never removes worktrees or branches and never stops processes.
|
|
20
3
|
import {execFileSync,spawnSync} from 'node:child_process';
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {pidLock} from './pid-lock.mjs';
|
|
4
|
+
import {existsSync,readdirSync,readlinkSync,statSync,statfsSync} from 'node:fs';
|
|
5
|
+
import {basename,join,resolve,sep} from 'node:path';
|
|
6
|
+
import {laneLive} from './lane-live.mjs';
|
|
25
7
|
import {WORKTREES} from './worktree-ignore.mjs';
|
|
26
8
|
|
|
27
9
|
const REAP_USAGE='usage: node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--stale=HOURS] [--no-remote]';
|
|
@@ -120,22 +102,8 @@ export function freeBytes(path){
|
|
|
120
102
|
return volume.bavail*volume.bsize;
|
|
121
103
|
}
|
|
122
104
|
|
|
123
|
-
/** `du -sk` of `path` as GiB text, within `budgetMs` (all of a run's `du` calls share one budget), or why not.
|
|
124
|
-
* @param {string} path @param {number} budgetMs */
|
|
125
|
-
function duSize(path,budgetMs){
|
|
126
|
-
if(budgetMs<1000)return 'size not measured (du budget spent)';
|
|
127
|
-
const listed=spawnSync('du',['-sk',path],{encoding:'utf8',timeout:budgetMs});
|
|
128
|
-
const kib=Number((listed.stdout??'').split('\t')[0]);
|
|
129
|
-
return listed.status===0&&Number.isFinite(kib)&&kib>0?`${(kib/1_048_576).toFixed(1)} GiB`:'size unknown';
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** Signed MiB text for a byte count; the sign is taken after rounding, so a tiny change reads +0. @param {number} bytes */
|
|
133
|
-
const mib=bytes=>{const size=Math.round(bytes/1_048_576);return `${size<0?'-':'+'}${Math.abs(size).toLocaleString('en-US')} MiB`;};
|
|
134
|
-
|
|
135
105
|
/** Is `sha` on origin/main itself? @param {string} canonical @param {string} sha */
|
|
136
106
|
export const onMain=(canonical,sha)=>sha!==''&&tryGit(canonical,['merge-base','--is-ancestor',sha,'origin/main']).status===0;
|
|
137
|
-
/** Commits of `sha` that origin/main lacks. @param {string} canonical @param {string} sha */
|
|
138
|
-
const aheadOfMain=(canonical,sha)=>Number(tryGit(canonical,['rev-list','--count',`origin/main..${sha}`]).stdout.trim()||'0');
|
|
139
107
|
|
|
140
108
|
/** @typedef {{path:string,head:string,branch:string}} Worktree */
|
|
141
109
|
|
|
@@ -159,102 +127,18 @@ export function linkedWorktrees(canonical){
|
|
|
159
127
|
* @param {NodeJS.ProcessEnv} env @param {(line:string)=>void} say
|
|
160
128
|
*/
|
|
161
129
|
export function reap(canonical,options,env,say){
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
const fetched=tryGit(canonical,['fetch','--quiet','origin','+refs/heads/main:refs/remotes/origin/main']);
|
|
165
|
-
if(fetched.status!==0){say(`reap STOP cannot fetch origin main: ${fetched.stderr.trim()}`);return 1;}
|
|
130
|
+
// J358: this command is an inventory for a human audit. Land alone removes
|
|
131
|
+
// its own just-landed worktree, after a successful keep-copy.
|
|
166
132
|
const directories=processDirectories();
|
|
167
|
-
const
|
|
168
|
-
/** @type {string[]} */const reaped=[];
|
|
169
|
-
/** @type {string[]} */const kept=[];
|
|
170
|
-
/** @type {string[]} */const stale=[];
|
|
171
|
-
const duUntil=now+60_000;
|
|
172
|
-
/** DK11: an unlanded or dirty worktree untouched for --stale hours goes on the receipt with its size. Untouched
|
|
173
|
-
* means no Git activity, no change to a dirty path, and no process inside.
|
|
174
|
-
* @param {string} slug @param {string} path @param {string} why @param {string[]} [dirty] porcelain lines */
|
|
175
|
-
const staleCheck=(slug,path,why,dirty=[])=>{
|
|
176
|
-
let gitDir='',physical='';
|
|
177
|
-
try{gitDir=git(path,['rev-parse','--absolute-git-dir']).trim();physical=realpathSync(path);}catch{return;}
|
|
178
|
-
if(directories===undefined||[...directories.values()].some(cwd=>cwd===physical||cwd.startsWith(`${physical}${sep}`)))return;
|
|
179
|
-
let newest=0;
|
|
180
|
-
try{newest=lastActivity(path,gitDir);}catch{return;}
|
|
181
|
-
for(const line of dirty.slice(0,500)){
|
|
182
|
-
const name=line.slice(3).split(' -> ').at(-1)??'';
|
|
183
|
-
try{newest=Math.max(newest,statSync(join(path,name.replaceAll(/^"|"$/gu,''))).mtimeMs);}catch{/* Deleted: no mtime. */}
|
|
184
|
-
}
|
|
185
|
-
const idle=(now-newest)/3_600_000;
|
|
186
|
-
if(idle<options.staleHours)return;
|
|
187
|
-
const entry=`${slug} (${duSize(path,duUntil-Date.now())}, idle ${(idle/24).toFixed(1)} d, ${why})`;
|
|
188
|
-
stale.push(entry);
|
|
189
|
-
say(`stale ${entry}`);
|
|
190
|
-
};
|
|
191
|
-
/** @type {string[]} */const remotes=[];
|
|
133
|
+
const cwds=directories===undefined?null:[...directories.values()];
|
|
192
134
|
for(const tree of linkedWorktrees(canonical)){
|
|
193
|
-
const slug=basename(tree.path)
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if(tree.branch!==branch){keep(`on ${tree.branch===''?'a detached HEAD':tree.branch}, not plan/${slug}`);continue;}
|
|
201
|
-
if(!existsSync(tree.path)){keep('its folder is gone; `git worktree prune` clears it');continue;}
|
|
202
|
-
// Landed means the tip is on main itself (land fast-forwards): \`git cherry\` would miss a merge's own changes.
|
|
203
|
-
if(!onMain(canonical,tree.head)){const why=`${String(aheadOfMain(canonical,tree.head))} commit(s) not on main`;keep(why);staleCheck(slug,tree.path,why);continue;}
|
|
204
|
-
const dirty=git(tree.path,['--no-optional-locks','status','--porcelain','--untracked-files=all']).split('\n').filter(Boolean);
|
|
205
|
-
if(dirty.length>0){const why=`${String(dirty.length)} uncommitted path(s)`;keep(`${why}, first ${dirty[0]?.slice(3)}`);staleCheck(slug,tree.path,why,dirty);continue;}
|
|
206
|
-
const gitDir=git(tree.path,['rev-parse','--absolute-git-dir']).trim();
|
|
207
|
-
const busy=(/** @type {Map<number,string>|undefined} */ seen)=>seen===undefined?'cannot list process working directories'
|
|
208
|
-
:[...seen].filter(([,path])=>path===physical||path.startsWith(`${physical}${sep}`)).map(([pid])=>String(pid)).join(', ');
|
|
209
|
-
// FL30: orphans (reparented to pid 1) in a landed, clean worktree are nobody's; they don't make it busy, and they
|
|
210
|
-
// are stopped only once it passed the grace, under its land lock (J206 review).
|
|
211
|
-
const orphans=new Set(stopWorktreeProcesses(physical,{orphansOnly:true,dryRun:true}));
|
|
212
|
-
const using=busy(directories===undefined?undefined:new Map([...directories].filter(([pid])=>!orphans.has(pid))));
|
|
213
|
-
if(using!==''){keep(directories===undefined?using:`in use by pid ${using}`);continue;}
|
|
214
|
-
const idleHours=Math.max(0,(now-lastActivity(tree.path,gitDir))/3_600_000);
|
|
215
|
-
if(options.graceHours>0&&idleHours<options.graceHours){keep(`active ${idleHours.toFixed(1)} h ago, under the ${String(options.graceHours)} h grace`);continue;}
|
|
216
|
-
// Hold the worktree's land lock (land can't start under it; a running land holds it already), then check again
|
|
217
|
-
// what could have changed since: HEAD, a commit, an edit, a new process inside, a worktree setup.
|
|
218
|
-
/** @type {(() => void)|undefined} */let release;
|
|
219
|
-
try{release=pidLock(join(gitDir,'wildshard-land.lock'));}catch(error){keep(error instanceof Error?error.message:String(error));continue;}
|
|
220
|
-
if(release===undefined){keep('land is running there');continue;}
|
|
221
|
-
try{
|
|
222
|
-
if(orphans.size>0){
|
|
223
|
-
const stopped=stopWorktreeProcesses(physical,{orphansOnly:true,dryRun:options.dryRun});
|
|
224
|
-
if(stopped.length>0)say(`${options.dryRun?'would stop':'stopped '} ${slug}: orphaned pid ${stopped.join(', ')}`);
|
|
225
|
-
}
|
|
226
|
-
const head=tryGit(tree.path,['rev-parse','HEAD']).stdout.trim();
|
|
227
|
-
const now2=git(tree.path,['--no-optional-locks','status','--porcelain','--untracked-files=all']).trim();
|
|
228
|
-
const seen2=processDirectories();
|
|
229
|
-
const using2=busy(seen2===undefined||!options.dryRun?seen2:new Map([...seen2].filter(([pid])=>!orphans.has(pid))));
|
|
230
|
-
const why=head!==tree.head?`HEAD moved to ${head.slice(0,10)} during the check`:now2!==''?'edited during the check':using2!==''?`in use during the check (${using2})`
|
|
231
|
-
:existsSync(join(common,'wildshard-worktree-setup.lock'))?'a worktree setup started during the check':!onMain(canonical,head)?'not on main during the check':'';
|
|
232
|
-
if(why!==''){keep(why);continue;}
|
|
233
|
-
if(options.dryRun){say(`would reap ${slug}: landed, clean, idle ${idleHours.toFixed(1)} h`);reaped.push(slug);continue;}
|
|
234
|
-
const removed=tryGit(canonical,['worktree','remove',tree.path]);
|
|
235
|
-
if(removed.status!==0){keep(`git worktree remove refused: ${removed.stderr.trim()}`);continue;}
|
|
236
|
-
}finally{release();}
|
|
237
|
-
// Only while the branch is still the commit checked above; anything newer is somebody's work.
|
|
238
|
-
const deleted=tryGit(canonical,['update-ref','-d',branch,tree.head]);
|
|
239
|
-
say(`reaped ${slug}: worktree removed${deleted.status===0?', branch deleted':`, branch kept (${deleted.stderr.trim()})`}`);
|
|
240
|
-
reaped.push(slug);
|
|
241
|
-
if(!options.remote)continue;
|
|
242
|
-
const listed=tryGit(canonical,['ls-remote','--heads','origin',branch]);
|
|
243
|
-
const sha=listed.status===0?listed.stdout.trim().split(/\s+/u)[0]??'':'';
|
|
244
|
-
if(sha===''){if(listed.status!==0)say(` ${slug}: origin not reachable; its remote branch is left`);continue;}
|
|
245
|
-
// The remote branch goes only if it is landed too: its commit must be here and add nothing main lacks.
|
|
246
|
-
if(tryGit(canonical,['cat-file','-e',`${sha}^{commit}`]).status!==0){remotes.push(`${slug} kept (origin has ${sha.slice(0,10)}, unknown here)`);say(` ${slug}: origin plan/${slug} is ${sha.slice(0,10)}, not fetched here; left`);continue;}
|
|
247
|
-
if(!onMain(canonical,sha)){remotes.push(`${slug} kept (origin has unlanded commits)`);say(` ${slug}: origin plan/${slug} holds commits not on main; left`);continue;}
|
|
248
|
-
const pushed=tryGit(canonical,['push','--quiet',`--force-with-lease=${branch}:${sha}`,'origin','--delete',branch]);
|
|
249
|
-
if(pushed.status===0){remotes.push(`${slug} deleted`);say(` ${slug}: origin plan/${slug} deleted`);}
|
|
250
|
-
else{remotes.push(`${slug} delete failed`);say(` ${slug}: origin plan/${slug} not deleted: ${pushed.stderr.trim()}`);}
|
|
135
|
+
const slug=basename(tree.path);
|
|
136
|
+
if(resolve(tree.path)!==join(canonical,WORKTREES,slug)){
|
|
137
|
+
say(`skipped ${tree.path}: outside plan worktrees`);continue;
|
|
138
|
+
}
|
|
139
|
+
const state=laneLive(tree.path,{receipts:env.WS_LANE_RECEIPTS,cwds,activeLog:env.WS_ACTIVE_HOURS_LOG});
|
|
140
|
+
const landed=onMain(canonical,tree.head);
|
|
141
|
+
say(`${state.state} ${slug}: ${state.reason}; ${landed?'on origin/main':'not on origin/main'}; manual audit, copy before removal`);
|
|
251
142
|
}
|
|
252
|
-
if(!options.dryRun)tryGit(canonical,['worktree','prune']);
|
|
253
|
-
const freed=options.dryRun?'':`; df ${mib(freeBytes(canonical)-freeBefore)}`;
|
|
254
|
-
if(freed!=='')say(`df free changed ${freed.slice(5)} during the run`);
|
|
255
|
-
const lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):'reaper';
|
|
256
|
-
const line=`${new Date().toISOString().slice(11,16)} UTC ${lane} worktree reap ${basename(canonical)}${options.dryRun?' (dry run)':''}: ${reaped.length===0?'none':`${options.dryRun?'would reap':'reaped'} ${reaped.join(', ')}`}; kept ${kept.length===0?'none':kept.join(', ')}${remotes.length===0?'':`; origin ${remotes.join(', ')}`}${freed}${stale.length===0?'':`; stale ${String(options.staleHours)} h+: ${stale.join(', ')}`}`;
|
|
257
|
-
const file=resolve(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log'));
|
|
258
|
-
try{mkdirSync(dirname(file),{recursive:true});appendFileSync(file,`${line}\n`);}catch(error){say(`reap receipt unavailable: ${String(error)}`);}
|
|
259
143
|
return 0;
|
|
260
144
|
}
|
package/scripts/worktree.mjs
CHANGED
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
// 3. `pnpm install --frozen-lockfile --offline`: pnpm's store, cloned, not downloaded;
|
|
11
11
|
// 4. `pnpm pins` when the repo has that script (shard products from ~/.cache/wildshard/pins);
|
|
12
12
|
// 5. names the herdr pane (inside herdr only) and prints the land steps.
|
|
13
|
+
// Before step 1 adds anything, meta REPO-DISK DK9 (Q41): it refuses when the repo's volume has under MIN_FREE_GIB
|
|
14
|
+
// free or the repo already has MAX_WORKTREES live worktrees under .worktrees/, and names the oldest parked one.
|
|
15
|
+
// WS_WORKTREE_FREE_GIB stands in for the measured free GiB (tests); setting it is a deliberate override.
|
|
13
16
|
//
|
|
14
17
|
// Never copied: .env*, tmp/, .review/, .cache/, browser profiles, leases, ports, push proofs; the worktree gets
|
|
15
18
|
// only tracked files and its own install. Each step's seconds go to <worktree>/tmp/worktree-setup.json and, with
|
|
@@ -19,12 +22,13 @@
|
|
|
19
22
|
// (scripts/worktree-reap.mjs) removes landed, clean, idle worktrees with their branches, local and on origin.
|
|
20
23
|
import {execFileSync,spawn,spawnSync} from 'node:child_process';
|
|
21
24
|
import {randomBytes} from 'node:crypto';
|
|
22
|
-
import {appendFileSync,existsSync,linkSync,lstatSync,mkdirSync,readFileSync,rmSync,statSync,unlinkSync,writeFileSync} from 'node:fs';
|
|
25
|
+
import {appendFileSync,existsSync,linkSync,lstatSync,mkdirSync,readFileSync,realpathSync,rmSync,statSync,statfsSync,unlinkSync,writeFileSync} from 'node:fs';
|
|
23
26
|
import {homedir} from 'node:os';
|
|
24
27
|
import {basename,dirname,join,resolve} from 'node:path';
|
|
25
28
|
import {pathToFileURL} from 'node:url';
|
|
26
29
|
import {WORKTREES} from './worktree-ignore.mjs';
|
|
27
|
-
import {
|
|
30
|
+
import {clonePaths} from './apfs-clone.mjs';
|
|
31
|
+
import {freeBytes,lastActivity,linkedWorktrees,onMain,parseReapArgs,reap} from './worktree-reap.mjs';
|
|
28
32
|
|
|
29
33
|
export const SLUG=/^[a-z0-9][a-z0-9._-]{0,63}$/u;
|
|
30
34
|
const REGULAR=/^100(?:644|755)$/u;
|
|
@@ -50,7 +54,7 @@ for source, target in zip(parts[0::2], parts[1::2]):
|
|
|
50
54
|
sys.exit(f'{target.decode()}: {os.strerror(ctypes.get_errno())}')
|
|
51
55
|
finally:
|
|
52
56
|
os.close(fd)`;
|
|
53
|
-
const USAGE='usage: node scripts/worktree.mjs new <slug> [--no-install] [--no-pins] [--no-herdr] [--no-clone]\n node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]';
|
|
57
|
+
const USAGE='usage: node scripts/worktree.mjs new <slug> [--row=PLAN-ROW] [--no-install] [--no-pins] [--no-herdr] [--no-clone]\n node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]';
|
|
54
58
|
|
|
55
59
|
class StopError extends Error{name='StopError';}
|
|
56
60
|
|
|
@@ -82,15 +86,67 @@ export function withStoreUse(env,what,fn){
|
|
|
82
86
|
}finally{rmSync(mine,{force:true});}
|
|
83
87
|
}
|
|
84
88
|
|
|
89
|
+
/** Meta REPO-DISK DK9 (DEV-SPEED Q41): at most this many live plan worktrees per repo. */
|
|
90
|
+
export const MAX_WORKTREES=6;
|
|
91
|
+
/** Meta REPO-DISK DK9: refuse a new worktree when the repo's volume has less free than this, in GiB. */
|
|
92
|
+
export const MIN_FREE_GIB=60;
|
|
93
|
+
|
|
94
|
+
/** Free GiB on the volume holding `path`; WS_WORKTREE_FREE_GIB fakes it (tests). @param {string} path @param {NodeJS.ProcessEnv} env */
|
|
95
|
+
export function freeGib(path,env){
|
|
96
|
+
const faked=env.WS_WORKTREE_FREE_GIB;
|
|
97
|
+
if(faked!==undefined&&faked!==''){
|
|
98
|
+
const value=Number(faked);
|
|
99
|
+
if(!Number.isFinite(value)||value<0)throw new StopError(`WS_WORKTREE_FREE_GIB=${faked} is not a number of GiB`);
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
const volume=statfsSync(path);
|
|
103
|
+
return volume.bavail*volume.bsize/2**30;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* DK9: why `worktree new` must not add another worktree here, or '' when it may. Live means a registered worktree
|
|
108
|
+
* whose folder exists under <canonical>/.worktrees/. A refusal names the oldest parked one (on plan/<slug>, landed:
|
|
109
|
+
* its tip on origin/main, and clean), by its last Git activity, and the reap command that frees it.
|
|
110
|
+
* @param {string} canonical @param {NodeJS.ProcessEnv} env @returns {string}
|
|
111
|
+
*/
|
|
112
|
+
export function capRefusal(canonical,env){
|
|
113
|
+
const roots=new Set([join(canonical,WORKTREES),join(realpathSync(canonical),WORKTREES)]);
|
|
114
|
+
const live=linkedWorktrees(canonical).filter(tree=>roots.has(dirname(resolve(tree.path)))&&existsSync(tree.path));
|
|
115
|
+
const free=freeGib(canonical,env);
|
|
116
|
+
const full=live.length>=MAX_WORKTREES,low=free<MIN_FREE_GIB;
|
|
117
|
+
if(!full&&!low)return '';
|
|
118
|
+
const why=[
|
|
119
|
+
...(full?[`${basename(canonical)} already has ${String(live.length)} live worktrees under ${WORKTREES}/ (cap ${String(MAX_WORKTREES)})`]:[]),
|
|
120
|
+
...(low?[`only ${free.toFixed(1)} GiB free on the volume of ${canonical} (floor ${String(MIN_FREE_GIB)} GiB)`]:[]),
|
|
121
|
+
].join(', and ');
|
|
122
|
+
const parked=live.flatMap(tree=>{
|
|
123
|
+
const slug=basename(tree.path);
|
|
124
|
+
if(tree.branch!==`refs/heads/plan/${slug}`||!onMain(canonical,tree.head))return [];
|
|
125
|
+
// Activity first, and a status that takes no optional lock: a plain `git status` may rewrite the index and so
|
|
126
|
+
// make every worktree look active now.
|
|
127
|
+
const at=lastActivity(tree.path,git(tree.path,['rev-parse','--absolute-git-dir']).trim());
|
|
128
|
+
const dirty=spawnSync('git',['--no-optional-locks','status','--porcelain','--untracked-files=all'],{cwd:tree.path,encoding:'utf8',maxBuffer:64<<20});
|
|
129
|
+
if(dirty.status!==0||dirty.stdout.trim()!=='')return [];
|
|
130
|
+
return [{slug,at}];
|
|
131
|
+
}).sort((a,b)=>a.at-b.at);
|
|
132
|
+
const oldest=parked[0];
|
|
133
|
+
const hint=oldest===undefined
|
|
134
|
+
?`none of them is parked (landed on origin/main and clean): land one, or remove one by hand`
|
|
135
|
+
:`the oldest parked worktree is ${WORKTREES}/${oldest.slug} (landed, clean, idle ${((Date.now()-oldest.at)/3_600_000).toFixed(1)} h); \`node scripts/worktree.mjs reap\` frees it once idle 24 h with no process inside, or land and remove one by hand`;
|
|
136
|
+
return `${why}; ${hint}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
85
139
|
/** @param {string[]} argv */
|
|
86
140
|
export function parseArgs(argv){
|
|
87
141
|
const [command,slug,...rest]=argv;
|
|
88
142
|
if(command!=='new'||slug===undefined)throw new StopError(USAGE);
|
|
89
143
|
if(!SLUG.test(slug))throw new StopError(`slug "${slug}" must match ${SLUG.source}`);
|
|
90
144
|
const flags=new Set(['--no-install','--no-pins','--no-herdr','--no-clone']);
|
|
91
|
-
const
|
|
145
|
+
const row=rest.find(arg=>arg.startsWith('--row='));
|
|
146
|
+
const unknown=rest.filter(arg=>!flags.has(arg)&&arg!==row);
|
|
92
147
|
if(unknown.length>0)throw new StopError(`unknown option ${unknown.join(' ')}\n${USAGE}`);
|
|
93
|
-
|
|
148
|
+
if(row!==undefined&&!/^--row=[A-Z][A-Z0-9-]*\d+[a-z]?$/u.test(row))throw new StopError(`invalid plan row ${row}\n${USAGE}`);
|
|
149
|
+
return {slug,row:row?.slice('--row='.length)??null,install:!rest.includes('--no-install'),pins:!rest.includes('--no-pins'),herdr:!rest.includes('--no-herdr'),clone:!rest.includes('--no-clone')};
|
|
94
150
|
}
|
|
95
151
|
|
|
96
152
|
/** The canonical checkout of the repo `cwd` is in: the main worktree, never a linked one. @param {string} cwd */
|
|
@@ -277,6 +333,9 @@ export function worktreeNew(argv,cwd=process.cwd(),env=process.env){
|
|
|
277
333
|
if(existsSync(tree))throw new StopError(`${relative} already exists; work there, or pick another slug`);
|
|
278
334
|
if(tryGit(canonical,['rev-parse','--verify','--quiet',`refs/heads/${branch}`]).status===0)throw new StopError(`branch ${branch} already exists; delete it or pick another slug`);
|
|
279
335
|
timed('fetch',()=>{git(canonical,['fetch','--quiet','origin','main']);base=git(canonical,['rev-parse','origin/main']).trim();return `origin/main ${base.slice(0,10)}; ${followMain(canonical,base)}`;});
|
|
336
|
+
// DK9: after the fetch, so "landed" reads the current origin/main; before anything is added.
|
|
337
|
+
const refused=capRefusal(canonical,env);
|
|
338
|
+
if(refused!=='')throw new StopError(refused);
|
|
280
339
|
// Git refuses `-b` for a branch that appeared since the check, before anything here owns one.
|
|
281
340
|
timed('add',()=>{git(canonical,['worktree','add','--quiet','--no-checkout','-b',branch,relative,base]);});
|
|
282
341
|
try{
|
|
@@ -304,9 +363,24 @@ export function worktreeNew(argv,cwd=process.cwd(),env=process.env){
|
|
|
304
363
|
throw error;
|
|
305
364
|
}
|
|
306
365
|
}finally{unlock();}
|
|
307
|
-
|
|
366
|
+
// DK10: keep unchanged split content on shared APFS blocks. This is an
|
|
367
|
+
// ignored, regenerable output; the next split compares its actual bytes.
|
|
368
|
+
const content=join(canonical,'dist-content');
|
|
369
|
+
if(options.clone&&process.platform==='darwin'){
|
|
370
|
+
try{
|
|
371
|
+
if(existsSync(content)&&lstatSync(content).isDirectory()&&!lstatSync(content).isSymbolicLink()
|
|
372
|
+
&&tryGit(tree,['check-ignore','--quiet','dist-content/']).status===0){
|
|
373
|
+
timed('content',()=>{const method=clonePaths([[content,join(tree,'dist-content')]],{copy:false});return `${method} (APFS content, no copy fallback)`;});
|
|
374
|
+
}
|
|
375
|
+
}catch(error){
|
|
376
|
+
rmSync(join(tree,'dist-content'),{recursive:true,force:true});
|
|
377
|
+
process.stderr.write(`worktree: content clone skipped (${error instanceof Error?error.message:String(error)})\n`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
const manifest=join(tree,'package.json');
|
|
381
|
+
const scripts=existsSync(manifest)?/** @type {{scripts?:Record<string,string>}} */(JSON.parse(readFileSync(manifest,'utf8'))).scripts??{}:{};
|
|
308
382
|
const childEnv=Object.fromEntries(Object.entries(env).filter(([key])=>!key.startsWith('GIT_')));
|
|
309
|
-
if(options.install)timed('install',()=>withStoreUse(env,'worktree install',()=>run(tree,'pnpm',['install','--frozen-lockfile','--offline'],childEnv)));
|
|
383
|
+
if(options.install&&existsSync(manifest))timed('install',()=>withStoreUse(env,'worktree install',()=>run(tree,'pnpm',['install','--frozen-lockfile','--offline'],childEnv)));
|
|
310
384
|
if(options.pins&&scripts.pins!==undefined)timed('pins',()=>run(tree,'pnpm',['--silent','pins'],childEnv));
|
|
311
385
|
if(options.herdr&&env.HERDR_ENV==='1'&&env.HERDR_PANE_ID!==undefined&&env.HERDR_PANE_ID!==''){
|
|
312
386
|
const named=spawnSync('herdr',['pane','rename',env.HERDR_PANE_ID,`${basename(canonical)} ${branch}`],{encoding:'utf8'});
|
|
@@ -321,17 +395,23 @@ export function worktreeNew(argv,cwd=process.cwd(),env=process.env){
|
|
|
321
395
|
const total=Number(((performance.now()-began)/1000).toFixed(2));
|
|
322
396
|
const disk=diskCost(tree,freeBefore);
|
|
323
397
|
process.stdout.write(`worktree disk ${disk.text}\n`);
|
|
324
|
-
const
|
|
398
|
+
const created=new Date().toISOString();
|
|
399
|
+
const lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):null;
|
|
400
|
+
const record={slug:options.slug,branch,base,tree,total,steps,disk,finished:created};
|
|
401
|
+
let receiptOffset=null;
|
|
402
|
+
try{receiptOffset=statSync(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log')).size;}
|
|
403
|
+
catch(error){if(error instanceof Error&&'code'in error&&error.code==='ENOENT')receiptOffset=0;}
|
|
404
|
+
const owner={lane,session:env.CLAUDE_SESSION_ID??env.CLAUDE_CODE_SESSION_ID??env.CODEX_THREAD_ID??lane,agent:env.CLAUDE_SESSION_ID||env.CLAUDE_CODE_SESSION_ID?'claude':env.CODEX_THREAD_ID||lane?'codex':'unknown',row:options.row??env.WS_PLAN_ROW??null,created,activeHours:null,receiptOffset};
|
|
405
|
+
writeFileSync(join(tree,'.owner'),`${JSON.stringify(owner,null,2)}\n`,{flag:'wx'});
|
|
325
406
|
mkdirSync(join(tree,'tmp'),{recursive:true});
|
|
326
407
|
writeFileSync(join(tree,'tmp/worktree-setup.json'),`${JSON.stringify(record,null,2)}\n`);
|
|
327
|
-
|
|
328
|
-
if(lane!==''){
|
|
408
|
+
if(lane!==null){
|
|
329
409
|
const file=resolve(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log'));
|
|
330
410
|
try{mkdirSync(dirname(file),{recursive:true});appendFileSync(file,`${new Date().toISOString().slice(11,16)} UTC ${lane} worktree new ${basename(canonical)}/${relative} on ${branch} from ${base.slice(0,10)} in ${total.toFixed(1)} s (${steps.map(row=>`${row.step} ${row.seconds.toFixed(1)}`).join(', ')}); ${disk.text}\n`);}
|
|
331
411
|
catch(error){process.stderr.write(`worktree receipt unavailable: ${String(error)}\n`);}
|
|
332
412
|
}
|
|
333
|
-
const name=lane
|
|
334
|
-
process.stdout.write(`\nworktree ready in ${total.toFixed(1)} s: ${tree} on ${branch}\n\nLand (J240):\n cd ${tree}\n # commit by pathspec as usual; the hooks allow commits here on ${branch}\n WS_LANE_NAME=${name} node scripts/land.mjs\n # it pushes ${branch}, waits for its
|
|
413
|
+
const name=lane??'<lane>';
|
|
414
|
+
process.stdout.write(`\nworktree ready in ${total.toFixed(1)} s: ${tree} on ${branch}\n\nLand (J240):\n cd ${tree}\n # commit by pathspec as usual; the hooks allow commits here on ${branch}\n WS_LANE_NAME=${name} node scripts/land.mjs\n # it pushes ${branch}, waits for its hosted CI (land.config.json workflows), rebases and fast-forwards main;\n # check its receipt in ~/.cache/wildshard/lane-receipts.log. Force only your own plan/* branch\n # after a rebase (--force-with-lease), never main.\n`);
|
|
335
415
|
return 0;
|
|
336
416
|
}
|
|
337
417
|
|
package/src/client/app/entry.ts
CHANGED
|
@@ -437,7 +437,7 @@ async function startSelected(): Promise<void> {
|
|
|
437
437
|
const imports = prepareBootImports(bootAwait('app:common-service-imports', Promise.all([speciesModule, iconsModule, pickupsModule, pickupRowsModule, propsModule,
|
|
438
438
|
starterModule, hoverboardModule, voicesModule, boarModule, familiesModule, sourceModule, runtimeModule,
|
|
439
439
|
gridEntryModule, pathsModule, prefetchModule])));
|
|
440
|
-
const [{ sharedWeaponVoices, declaredWeaponVoices }, { BOAR_LOOK }, { declaredKitItemFamilies },
|
|
440
|
+
const [{ sharedWeaponVoices, declaredWeaponVoices }, { BOAR_LOOK }, { declaredKitItemFamilies, declaredItemIcon },
|
|
441
441
|
{ configuredShardfile, installShardfileProduct, installManifestShardfile, preparePageResidency }, { browserShardfileOptions },
|
|
442
442
|
{ pageGridRecovery }, { loadingPath }, { gridPrefetchStatus }] = await Promise.all([
|
|
443
443
|
voicesModule, boarModule, familiesModule, sourceModule, runtimeModule, gridEntryModule, pathsModule,
|
|
@@ -475,12 +475,11 @@ async function startSelected(): Promise<void> {
|
|
|
475
475
|
if (path === 'grid') modules('grid');
|
|
476
476
|
// Hybrid shardfile entries retain real TypeScript stages until their page is data-only.
|
|
477
477
|
loading.setPath(loadingPath(path, game.shard.boot?.steps, path === 'shardfile' && source === null && game.shard.shardfile === undefined));
|
|
478
|
-
const declaredIcons = ['lock', 'check', 'poi', 'you', 'map', 'pack', 'star', 'book', 'heart', 'pin', 'laurel', 'sword', 'glyph', 'coin', 'purse', 'crossbow', 'rifle', 'lever', 'longbow', 'grapple', 'horse'] as const;
|
|
479
478
|
const bindings: Parameters<typeof installShardfileProduct>[2] = {
|
|
480
479
|
imageOwner,
|
|
481
480
|
instance: page.instance ?? (source === null ? 'template-solo' : `standalone-${source.identity.slug}`), catalogue: [], items: declaredKitItemFamilies(), voices: declaredWeaponVoices,
|
|
482
481
|
...(page.residency === undefined ? {} : { residency: page.residency }),
|
|
483
|
-
icon:
|
|
482
|
+
icon: declaredItemIcon,
|
|
484
483
|
recipes: new Map([['kit.look.boar', (row, species) => { if (row.animation.recipe !== 'kit.pose.quadruped') throw new Error('Unknown boar pose recipe'); return { ...BOAR_LOOK, id: row.id, species: species.id, kind: species.kind }; }]]),
|
|
485
484
|
};
|
|
486
485
|
imports.check();
|
|
@@ -6,11 +6,14 @@
|
|
|
6
6
|
*
|
|
7
7
|
* audioLog('sfx', 'leverShot', true) // kind, name, ok (false = not decoded / not shipped), detail
|
|
8
8
|
*/
|
|
9
|
-
export interface AudioLogEntry { t: number; kind: 'music' | 'sfx' | 'bark' | 'bed' | 'zone' | 'wire'; name: string; ok?: boolean; detail?: string }
|
|
9
|
+
export interface AudioLogEntry { t: number; kind: 'music' | 'sfx' | 'bark' | 'bed' | 'zone' | 'wire' | 'cue'; name: string; ok?: boolean; detail?: string }
|
|
10
|
+
/** EG-15: every trigger since boot, by `kind name`: how many sounded (`ok` not false) and how many found no sound. The ring forgets; this doesn't. */
|
|
11
|
+
export type AudioTally = Record<string, { played: number; silent: number }>;
|
|
10
12
|
|
|
11
13
|
const MAX = 400;
|
|
12
14
|
const log: AudioLogEntry[] = [];
|
|
13
|
-
|
|
15
|
+
const tally: AudioTally = {};
|
|
16
|
+
if (typeof window !== 'undefined') Object.assign(window as unknown as { __audioLog: AudioLogEntry[]; __audioTally: AudioTally }, { __audioLog: log, __audioTally: tally });
|
|
14
17
|
|
|
15
18
|
/** record one audio trigger (music, sfx, bark, bed …) in the `window.__audioLog` ring a headless check reads */
|
|
16
19
|
export function audioLog(kind: AudioLogEntry['kind'], name: string, ok?: boolean, detail?: string): void {
|
|
@@ -19,4 +22,6 @@ export function audioLog(kind: AudioLogEntry['kind'], name: string, ok?: boolean
|
|
|
19
22
|
if (detail !== undefined) e.detail = detail;
|
|
20
23
|
log.push(e);
|
|
21
24
|
if (log.length > MAX) log.shift();
|
|
25
|
+
const row = tally[`${kind} ${name}`] ??= { played: 0, silent: 0 };
|
|
26
|
+
if (ok === false) row.silent++; else row.played++;
|
|
22
27
|
}
|
|
@@ -4,6 +4,7 @@ import { beginLoadingWait, finishLoadingWait } from '../../../shared/engine/boot
|
|
|
4
4
|
import { currentLoadingTimeline } from '../../../shared/engine/boot/timeline';
|
|
5
5
|
import { bootProgress } from '../../../shared/engine/boot/timing';
|
|
6
6
|
import { diagnosticNow } from '../../../shared/engine/core/clock';
|
|
7
|
+
import { clearDownloadGiveUp, downloadGiveUp, onDownloadGiveUp, type DownloadGiveUp } from './downloadGiveUp';
|
|
7
8
|
|
|
8
9
|
/** A missing or interrupted transport, never a parsed-content or admission refusal. */
|
|
9
10
|
export class ContentReadError extends Error {
|
|
@@ -140,7 +141,10 @@ function reportStall(target: Document, error: ContentReadError, step: string | n
|
|
|
140
141
|
try { captureBrowserError(error, engineScreenTags('loading-stall', 'content-read', step ?? 'loading', { url: error.url })); }
|
|
141
142
|
catch { /* a report never holds the retry */ }
|
|
142
143
|
}
|
|
143
|
-
|
|
144
|
+
/** FM6 mode 36: how long a read may wait on RETRY, with nothing left that reads again by itself, before its line becomes the
|
|
145
|
+
* download-failed page. The line (modes 33 to 35) is the pause; the page says the download stopped, with what to do. */
|
|
146
|
+
export const DOWNLOAD_GIVE_UP_MS = 30_000;
|
|
147
|
+
async function retryFromCard(error: ContentReadError, signal?: AbortSignal, reads = 2): Promise<void> {
|
|
144
148
|
if (typeof document === 'undefined') throw error;
|
|
145
149
|
const target = document, timeline = currentLoadingTimeline(), scope = new Scope('content-read-button');
|
|
146
150
|
let group = retryGroups.get(target);
|
|
@@ -157,6 +161,18 @@ async function retryFromCard(error: ContentReadError, signal?: AbortSignal): Pro
|
|
|
157
161
|
owner: timeline?.waitOwner ?? null, step: timeline?.snapshot().current ?? null,
|
|
158
162
|
retry: () => {for (const retry of pending) retry();}, retryNavigation: false, ...contentFailure(error) });
|
|
159
163
|
shellRetry(scope, error, () => {for (const retry of pending) retry();});
|
|
164
|
+
// FM6 mode 36: the download gave up (before or while this read waits), so nothing more arrives by itself: the page says so
|
|
165
|
+
const page = (given: DownloadGiveUp): void => { void (async () => {
|
|
166
|
+
const { downloadFailedPage } = await import('../ui/downloadFailed');
|
|
167
|
+
if (!scope.disposed) downloadFailedPage(scope, given, `${error.url} · ${error.message}`, () => {for (const retry of pending) retry();});
|
|
168
|
+
})(); };
|
|
169
|
+
// or this read itself has waited DOWNLOAD_GIVE_UP_MS with every read it makes by itself spent (RETRY adds no new counter)
|
|
170
|
+
const given = downloadGiveUp();
|
|
171
|
+
if (given !== null) page(given);
|
|
172
|
+
else {
|
|
173
|
+
scope.onDispose(onDownloadGiveUp(page));
|
|
174
|
+
scope.timeout(DOWNLOAD_GIVE_UP_MS, () => { page({ attempts: reads, status: error.status, detail: error.url }); });
|
|
175
|
+
}
|
|
160
176
|
});
|
|
161
177
|
} finally {
|
|
162
178
|
if (id !== undefined) finishLoadingWait(id);
|
|
@@ -186,14 +202,18 @@ async function busyWait(error: ContentReadError, ms: number, signal?: AbortSigna
|
|
|
186
202
|
export async function readContent(url: string, maximum: number, options: ContentReadOptions): Promise<Uint8Array<ArrayBuffer>> {
|
|
187
203
|
if (!Number.isSafeInteger(maximum) || maximum < 0 || maximum > 25_000_000) throw new Error('Invalid content wire cap');
|
|
188
204
|
if (options.expectedBytes !== undefined && (!Number.isSafeInteger(options.expectedBytes) || options.expectedBytes < 0 || options.expectedBytes > maximum)) throw new Error('Invalid expected content length');
|
|
189
|
-
let retried = false;
|
|
205
|
+
let retried = false, reads = 0;
|
|
190
206
|
for (;;) {
|
|
191
207
|
options.signal?.throwIfAborted();
|
|
208
|
+
reads++;
|
|
192
209
|
try {
|
|
193
210
|
let response: Response;
|
|
194
211
|
try { response = await options.fetch(url, { ...(retried ? { cache: 'reload' } : {}), ...(options.signal === undefined ? {} : { signal: options.signal }) }); }
|
|
195
212
|
catch (error) { options.signal?.throwIfAborted(); throw new ContentReadError(url, 'connection unavailable', error); }
|
|
196
|
-
|
|
213
|
+
const bytes = await body(response, url, maximum, options.read, options.expectedBytes, options.response);
|
|
214
|
+
// FM6 mode 36: a read that waited on RETRY now arrives, so the download works again: a later stall shows the card's line first
|
|
215
|
+
if (reads > 2) clearDownloadGiveUp();
|
|
216
|
+
return bytes;
|
|
197
217
|
} catch (error) {
|
|
198
218
|
options.signal?.throwIfAborted();
|
|
199
219
|
if (!(error instanceof ContentReadError)) throw error;
|
|
@@ -208,7 +228,7 @@ export async function readContent(url: string, maximum: number, options: Content
|
|
|
208
228
|
// Instead of RETRY forever, the page reloads past its worker into the live build (once per build and tab).
|
|
209
229
|
if (options.retry === undefined && error.missing && typeof document !== 'undefined'
|
|
210
230
|
&& await (await import('./browserChunkRecovery')).reloadIfStaleBuild()) await new Promise<void>(() => { /* never settles: the page is navigating */ });
|
|
211
|
-
await (options.retry === undefined ? retryFromCard(error, options.signal) : options.retry(error)); retried = false;
|
|
231
|
+
await (options.retry === undefined ? retryFromCard(error, options.signal, reads) : options.retry(error)); retried = false;
|
|
212
232
|
}
|
|
213
233
|
}
|
|
214
234
|
}
|
|
@@ -44,7 +44,7 @@ function numbers(value:unknown,keys:readonly string[]):Record<string,number|bool
|
|
|
44
44
|
}
|
|
45
45
|
const realm=(value:unknown):string=>typeof value==='string'&&/^(?:page|service-worker|worker:[0-9]{1,5})$/u.test(value)?value:'other';
|
|
46
46
|
/** Only build-system shaped public IDs are labels; arbitrary identifiers are not. */
|
|
47
|
-
export const diagnosticBuild=(value:unknown):string=>typeof value==='string'&&/^[a-f0-9]{7,40}
|
|
47
|
+
export const diagnosticBuild=(value:unknown):string=>typeof value==='string'&&/^[a-f0-9]{7,40}(?:-[a-z0-9]{6,16})?$/u.test(value)?value:'unknown';
|
|
48
48
|
/** LD3: engine operations named in a paste beyond OPERATIONS: an explicit list (Codex review of ca3c1d8: a pattern let
|
|
49
49
|
* any `app:<text>` through). A name not listed here or in OPERATIONS still becomes `operation-N`. */
|
|
50
50
|
const NAMED_OPERATIONS=new Set(['download:cache-check','app:session-code-ready','app:session-start','app:first-game-step-start',
|
|
@@ -193,3 +193,71 @@ export function safeBootDiagnostics(timing:BootTiming|undefined):Readonly<Record
|
|
|
193
193
|
handoff:{...numbers(handoff,['timeOrigin',...DETAIL_NUMBERS]),input:input(handoff['input'])},
|
|
194
194
|
};
|
|
195
195
|
}
|
|
196
|
+
|
|
197
|
+
/** NB15: only the privacy projection reaches the clipboard. Keep the local
|
|
198
|
+
* collector complete, but rank its useful facts instead of copying its JSON. */
|
|
199
|
+
export function compactBootDiagnostics(timing:BootTiming|undefined):{summary:readonly string[];timeline:readonly string[]}{
|
|
200
|
+
const safe=safeBootDiagnostics(timing);
|
|
201
|
+
if(safe===null)return {summary:[],timeline:['timeline (LS1): unavailable']};
|
|
202
|
+
const entries=list(safe['entries']).map(record),resources=list(safe['resources']).map(record);
|
|
203
|
+
const spans=entries.flatMap(row=>{
|
|
204
|
+
const start=number(row['start']),end=number(row['end']);
|
|
205
|
+
return start!==null&&end!==null&&end>start?[{name:String(row['operation']),realm:String(row['realm']),start,end,ms:end-start}]:[];
|
|
206
|
+
});
|
|
207
|
+
const label=(value:unknown,limit:number):string=>{
|
|
208
|
+
const text=typeof value==='string'?value:'unknown';
|
|
209
|
+
return text.length<=limit?text:`${text.slice(0,Math.floor(limit/2))}…${text.slice(-Math.floor(limit/2))}`;
|
|
210
|
+
};
|
|
211
|
+
const network=resources.filter(row=>(number(row['transferSize'])??0)>0);
|
|
212
|
+
const cached=resources.filter(row=>number(row['transferSize'])===0&&(number(row['encodedBodySize'])??0)>0);
|
|
213
|
+
const bytes=(rows:readonly Readonly<Record<string,unknown>>[],key:string):number=>rows.reduce((sum,row)=>sum+(number(row[key])??0),0);
|
|
214
|
+
const seconds=(ms:number):string=>(ms/1000).toFixed(2);
|
|
215
|
+
const duration=(row:Readonly<Record<string,unknown>>):number=>number(row['duration'])??Math.max(0,(number(row['responseEnd'])??0)-(number(row['startTime'])??0));
|
|
216
|
+
const timeline=[
|
|
217
|
+
'timeline (LS1):',
|
|
218
|
+
`counts: ${entries.length} spans (${spans.length} complete), ${resources.length} resources; network ${network.length} / ${bytes(network,'transferSize')} B; cache ${cached.length} / ${bytes(cached,'encodedBodySize')} B; unknown ${resources.length-network.length-cached.length}`,
|
|
219
|
+
'longest spans (start s + duration s):',
|
|
220
|
+
...spans.sort((a,b)=>b.ms-a.ms).slice(0,15).map(row=>` ${label(row.name,88)} [${row.realm}] ${seconds(row.start)} + ${seconds(row.ms)}`),
|
|
221
|
+
'slowest resources (bytes, duration s, source):',
|
|
222
|
+
...resources.sort((a,b)=>duration(b)-duration(a)).slice(0,10).map(row=>{
|
|
223
|
+
const transfer=number(row['transferSize']),encoded=number(row['encodedBodySize'])??0;
|
|
224
|
+
const source=transfer!==null&&transfer>0?'network':transfer===0&&encoded>0?'cache':'unknown';
|
|
225
|
+
return ` ${label(row['url'],100)} ${transfer!==null&&transfer>0?transfer:encoded} B ${seconds(duration(row))} s ${source}`;
|
|
226
|
+
}),
|
|
227
|
+
];
|
|
228
|
+
// Worker resource receipts carry their measured page-clock translation.
|
|
229
|
+
// Merge those with page requests; unaligned worker clocks cannot fill a gap.
|
|
230
|
+
const end=Math.max(0,...entries.filter(row=>row['realm']==='page').map(row=>number(row['end'])??number(row['start'])??0));
|
|
231
|
+
const intervals=resources.flatMap(row=>{
|
|
232
|
+
const page=row['realm']==='page';
|
|
233
|
+
const start=number(row['pageStart'])??(page?number(row['startTime']):null);
|
|
234
|
+
const finish=number(row['pageEnd'])??(page?number(row['responseEnd'])??(start===null?null:start+duration(row)):null);
|
|
235
|
+
return start!==null&&finish!==null&&finish>start&&start<end?[{start:Math.max(0,start),end:Math.min(end,finish)}]:[];
|
|
236
|
+
});
|
|
237
|
+
const navigation=record(safe['navigation']),responseEnd=number(navigation['responseEnd']);
|
|
238
|
+
const requestStart=Math.max(0,number(navigation['startTime'])??0);
|
|
239
|
+
if(responseEnd!==null&&responseEnd>requestStart&&requestStart<end)intervals.push({start:requestStart,end:Math.min(end,responseEnd)});
|
|
240
|
+
intervals.sort((a,b)=>a.start-b.start);
|
|
241
|
+
const gaps:{start:number;ms:number}[]=[];
|
|
242
|
+
let cursor=0;
|
|
243
|
+
for(const interval of intervals){
|
|
244
|
+
if(interval.start-cursor>500)gaps.push({start:cursor,ms:interval.start-cursor});
|
|
245
|
+
cursor=Math.max(cursor,interval.end);
|
|
246
|
+
}
|
|
247
|
+
if(end-cursor>500)gaps.push({start:cursor,ms:end-cursor});
|
|
248
|
+
// Keep every interval. Repeated polling gaps need one readable run rather
|
|
249
|
+
// than hundreds of identical durations; no gap is sampled or discarded.
|
|
250
|
+
const gapLines:string[]=[],stamp=(ms:number):string=>String(Number((ms/1000).toFixed(3)));
|
|
251
|
+
for(let index=0;index<gaps.length;){
|
|
252
|
+
const gap=gaps[index];if(gap===undefined)break;
|
|
253
|
+
const next=gaps[index+1],stride=next===undefined?0:Number(((next.start-gap.start)/1000).toFixed(9));
|
|
254
|
+
let count=1;
|
|
255
|
+
if(stride>0)while(gaps[index+count]!==undefined&&stamp(gaps[index+count]?.ms??0)===stamp(gap.ms)
|
|
256
|
+
&&stamp(gaps[index+count]?.start??0)===stamp((Number(stamp(gap.start))+count*stride)*1000))count++;
|
|
257
|
+
const repeated=count>=3;
|
|
258
|
+
gapLines.push(`${stamp(gap.start)}+${stamp(gap.ms)}${repeated?` every ${stride} x${count}`:''}`);
|
|
259
|
+
index+=repeated?count:1;
|
|
260
|
+
}
|
|
261
|
+
timeline.push(`request-free gaps >0.5 s (page clock, start+duration s): ${gapLines.join(', ')||'none'}`);
|
|
262
|
+
return {summary:list(safe['summary']).filter((value):value is string=>typeof value==='string'),timeline};
|
|
263
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// FM6 mode 36 (meta docs/plans/MMO-FAILURE-MODES-PLAN.md): the world's download gave up. The spawn download is the load's one bounded
|
|
2
|
+
// operation: each part gets its reads (spawnDownload.ts PART_READS), then the job refuses and its waits fall through to the
|
|
3
|
+
// network. When a read that falls through then waits on the card's RETRY too, nothing more will arrive by itself, so the card's
|
|
4
|
+
// line (modes 33 to 35) becomes the `download-failed` page (contentRead.ts). A read that waits on RETRY for
|
|
5
|
+
// DOWNLOAD_GIVE_UP_MS (the spawn manifest's own read, say) gives up the same way. Dependency-free, so the spawn download and the content
|
|
6
|
+
// read share it without either pulling the other in. One page document holds one load's fact.
|
|
7
|
+
|
|
8
|
+
/** What was measured when the download gave up, never a guess. The address and status are for Details and Copy diagnostics only. */
|
|
9
|
+
export interface DownloadGiveUp {
|
|
10
|
+
/** reads of the file or part that refused, its last one included (a RETRY round's reads add to the same count) */
|
|
11
|
+
readonly attempts: number;
|
|
12
|
+
/** the last HTTP status the part answered, null for no HTTP response */
|
|
13
|
+
readonly status: number | null;
|
|
14
|
+
/** what failed, with its address */
|
|
15
|
+
readonly detail: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
let fact: DownloadGiveUp | null = null;
|
|
19
|
+
const listeners = new Set<(given: DownloadGiveUp) => void>();
|
|
20
|
+
|
|
21
|
+
/** The spawn download's job refused (not a cancel). Every read waiting on the card hears it. */
|
|
22
|
+
export function noteDownloadGiveUp(given: DownloadGiveUp): void {
|
|
23
|
+
fact = given;
|
|
24
|
+
for (const listen of listeners) listen(given);
|
|
25
|
+
}
|
|
26
|
+
/** A new download starts: the last one's refusal is over. */
|
|
27
|
+
export function clearDownloadGiveUp(): void { fact = null; }
|
|
28
|
+
/** The refusal of this page's download, if it gave up. */
|
|
29
|
+
export function downloadGiveUp(): DownloadGiveUp | null { return fact; }
|
|
30
|
+
/** Hear a refusal from now on; returns the unsubscribe. */
|
|
31
|
+
export function onDownloadGiveUp(listen: (given: DownloadGiveUp) => void): () => void {
|
|
32
|
+
listeners.add(listen);
|
|
33
|
+
return () => { listeners.delete(listen); };
|
|
34
|
+
}
|
|
@@ -355,6 +355,8 @@ export class EquipmentService implements WeaponHooks {
|
|
|
355
355
|
get reach(): number | undefined { return this.current.reach; }
|
|
356
356
|
|
|
357
357
|
/** Give every weapon its line to the server (P1-E5.3-E1). */
|
|
358
|
+
/** The server's weapon wire this page's kit is bound to (TC-E1b: an entered data cell's kit takes the road's). */
|
|
359
|
+
get boundWire(): WeaponWire | null { return this.serverWire; }
|
|
358
360
|
bindWire(wire: WeaponWire | null): void { this.serverWire = wire; for (const w of this.list) w.wire = wire; wire?.equip(this.current.row.id); }
|
|
359
361
|
/** A named interaction the server must judge: nothing, where no server owns the player. */
|
|
360
362
|
interact(id: string): void { this.serverWire?.interact(id); }
|
|
@@ -360,6 +360,7 @@ export class Game {
|
|
|
360
360
|
* they hold) go with their row; a re-registered id starts a fresh record. */
|
|
361
361
|
private readonly faultSystems = new WeakMap<object, GameSystem<(dt: number, t: number) => void>>();
|
|
362
362
|
private anonymous = 0;
|
|
363
|
+
private observers = 0;
|
|
363
364
|
/** E357 F2: list order is the execution order; observation never registers a system. */
|
|
364
365
|
systemLabels(): Record<'input' | 'fixed.pre' | 'fixed.step' | 'fixed.post' | 'update' | 'late', string[]> {
|
|
365
366
|
const phases = this.app.systemsByPhase();
|
|
@@ -904,10 +905,13 @@ export class Game {
|
|
|
904
905
|
onUpdate(fn: (dt: number, t: number) => void, label?: string, core = false): void { this.register('update', fn, label, core); }
|
|
905
906
|
/** One player-owned callback survives world-frame changes and ends with the original player scope. */
|
|
906
907
|
onPlayerUpdate(fn: (dt: number, t: number) => void, label: string): void { this.register('update', fn, label, false, this.playerScope, false); }
|
|
907
|
-
/**
|
|
908
|
+
/**
|
|
909
|
+
* E357 F2: a temporary harness observer of simulation frames, removed when its walk finishes. Each has its own system id:
|
|
910
|
+
* the dev hook holds several at once (its ground sweep, each part's lamps and water), and one shared id threw on the second.
|
|
911
|
+
*/
|
|
908
912
|
watchFrames(fn: (dt: number) => void): () => void {
|
|
909
913
|
const scope = this.levelScope.child('observer');
|
|
910
|
-
this.register('update', fn,
|
|
914
|
+
this.register('update', fn, `harness.walk.${String(this.observers++)}`, false, scope, false);
|
|
911
915
|
return () => { scope.dispose(); };
|
|
912
916
|
}
|
|
913
917
|
/** First in the frame: read controls into intents the fixed steps consume (the player's move, a queued jump). */
|