@wildshard/engine 0.1.22 → 0.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/index.html +17 -4
- package/lint/engine-sides.json +9 -0
- package/lint/sim-players.json +2 -13
- package/package.json +36 -3
- 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/app-build/titlePreloads.mjs +8 -5
- package/scripts/bake-road-surfaces.entry.ts +18 -0
- package/scripts/bake-road-surfaces.mjs +44 -0
- package/scripts/changelog.mjs +2 -1
- package/scripts/ci-pack.mjs +3 -3
- package/scripts/engine-ci-shard.mjs +11 -0
- package/scripts/fight-page-census.mjs +131 -0
- package/scripts/goldens/board.py +44 -11
- package/scripts/goldens/capture.mjs +18 -6
- package/scripts/goldens/native-residency.d.mts +2 -0
- package/scripts/goldens/native-residency.mjs +31 -4
- package/scripts/grid-road-lag.mjs +209 -0
- package/scripts/keep-copy.mjs +172 -0
- package/scripts/land.d.mts +4 -1
- package/scripts/land.mjs +121 -9
- 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 +59 -7
- package/scripts/loading-flow/stalls.d.mts +2 -0
- package/scripts/loading-flow/stalls.mjs +13 -0
- package/scripts/map-hash.mjs +1 -1
- package/scripts/mmo-bots.mjs +5 -3
- package/scripts/mmo-grid-proof.mjs +74 -0
- package/scripts/mmo-seat-proof.mjs +43 -0
- package/scripts/nightly-heads.ts +13 -13
- package/scripts/nightly-model.ts +26 -12
- package/scripts/nightly-tag.mjs +2 -4
- package/scripts/nightly.proof.ts +18 -5
- package/scripts/nightly.ts +13 -8
- package/scripts/no-astc-boot.mjs +77 -0
- package/scripts/page-release/content.mjs +19 -10
- package/scripts/page-release/flow.d.mts +3 -2
- package/scripts/page-release/flow.mjs +31 -21
- package/scripts/page-release/packs.d.mts +5 -0
- package/scripts/page-release/packs.mjs +13 -3
- package/scripts/page-release/preview.d.mts +2 -0
- package/scripts/page-release/preview.mjs +74 -0
- package/scripts/page-release.mjs +13 -5
- 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/ring3.proof.ts +71 -0
- package/scripts/ring3.ts +100 -0
- package/scripts/road-drive-proof.mjs +269 -0
- package/scripts/road-memory-probe.mjs +129 -0
- package/scripts/scratch-dir.mjs +33 -14
- package/scripts/scratch-sweep.mjs +15 -23
- package/scripts/server-release/github.mjs +59 -26
- package/scripts/server-release/items.d.mts +7 -0
- package/scripts/server-release/items.mjs +28 -0
- package/scripts/server-release/publish.mjs +24 -2
- package/scripts/server-release/sign.mjs +8 -4
- package/scripts/side-parity.mjs +1 -1
- package/scripts/test-products.json +1 -0
- package/scripts/test_prebuilt_output.py +3 -1
- package/scripts/tsconfig.json +2 -0
- package/scripts/turn-in-shots.mjs +83 -0
- package/scripts/vitest-bench-observe-proof.py +168 -0
- package/scripts/vitest-bench.py +122 -77
- package/scripts/vitest-ci-files.ts +5 -1
- package/scripts/vps/rebuild.sh +3 -1
- package/scripts/vps/wildshard-config +106 -1
- package/scripts/warm-native-chrome.mjs +9 -3
- package/scripts/worker-client-fights.mjs +9 -3
- package/scripts/worktree-reap.mjs +36 -140
- package/scripts/worktree.mjs +92 -12
- package/scripts/zone-gate-proof.mjs +93 -0
- package/src/client/engine/audio/audioLog.ts +7 -2
- package/src/client/engine/boot/diagnostics.ts +69 -1
- package/src/client/engine/boot/sw.ts +3 -1
- package/src/client/engine/core/ktx2.ts +33 -10
- package/src/client/engine/core/ktx2Zstd.ts +2 -1
- package/src/client/engine/models/place.ts +7 -5
- package/src/client/engine/pwa/sw.js +83 -10
- package/src/client/engine/render/dataLook.ts +14 -7
- package/src/client/engine/render/lookLight.ts +64 -20
- package/src/client/engine/render/precompile.ts +6 -0
- package/src/client/engine/render/tiers.ts +9 -0
- package/src/client/engine/ui/Loading.ts +6 -8
- package/src/client/engine/ui/lookLightOption.ts +1 -1
- package/src/client/engine/ui/playerReload.ts +5 -5
- package/src/client/game/audio/cueDirector.ts +2 -1
- package/src/client/game/boot/bytes.generated.ts +4 -1
- package/src/client/game/boot/versions.generated.ts +8 -5
- 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/cellClip.ts +70 -6
- package/src/client/game/grid/dataCellKit.ts +9 -1
- package/src/client/game/grid/gateCard.css +9 -0
- package/src/client/game/grid/gateCard.ts +67 -0
- package/src/client/game/grid/live.ts +17 -3
- package/src/client/game/grid/liveSession.ts +15 -5
- package/src/client/game/grid/neighbourLife.ts +10 -1
- package/src/client/game/grid/neighbourPanels.ts +29 -2
- package/src/client/game/grid/pageEntry.ts +21 -0
- package/src/client/game/grid/products.ts +21 -7
- package/src/client/game/grid/regionalWorld.ts +5 -0
- package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
- package/src/client/game/grid/roadLook.ts +5 -73
- package/src/client/game/grid/roadLookPlatform.ts +11 -6
- package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
- package/src/client/game/grid/roadTilePool.ts +4 -0
- package/src/client/game/grid/session.ts +58 -16
- package/src/client/game/grid/softWallLook.ts +6 -1
- package/src/client/game/plugin/ui.ts +3 -0
- package/src/client/game/population/signals.ts +1 -1
- package/src/client/game/quest/chapterDirector.ts +1 -0
- package/src/client/game/session/play.ts +3 -0
- package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
- package/src/client/game/shardfile/clientSource.ts +5 -2
- package/src/client/game/shardfile/clientWorker.ts +25 -8
- package/src/client/game/shardfile/look.ts +1 -1
- package/src/client/game/shardfile/runtimeProduct.ts +9 -5
- package/src/client/game/shardfile/slabLibrary.ts +37 -0
- package/src/client/game/shardfile/slabRanges.ts +145 -0
- 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 +2 -2
- package/src/client/host/standalone/shell.ts +4 -1
- 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/simulation.ts +32 -8
- package/src/server/game/plugin/mover.ts +18 -14
- package/src/server/game/plugin/simulation.ts +2 -0
- package/src/server/game/shardfile/dataRespawn.ts +47 -0
- package/src/server/game/shardfile/declaredKitItems.ts +31 -7
- package/src/server/host/bake/headlessWorker.ts +3 -3
- package/src/server/host/dedicated/cellWorker.ts +4 -2
- package/src/server/host/dedicated/main.ts +7 -4
- package/src/server/host/dedicated/packReader.ts +15 -2
- package/src/server/host/dedicated/playerStore.ts +1 -1
- package/src/server/host/headlessRuntime.ts +11 -6
- package/src/server/host/standalone/cellWorld.ts +20 -6
- package/src/server/host/standalone/gridServer.ts +20 -6
- package/src/server/host/standalone/roadWorld.ts +36 -0
- package/src/server/host/standalone/serverHost.ts +2 -2
- package/src/shared/engine/entities/AnimalSim.ts +10 -0
- package/src/shared/engine/physics/gridBorders.ts +15 -1
- package/src/shared/engine/physics/transferWalls.ts +9 -4
- package/src/shared/engine/sim/snapshot.ts +5 -5
- package/src/shared/game/grid/allocator.ts +8 -1
- package/src/shared/game/grid/gateCount.ts +27 -0
- package/src/shared/game/grid/zoneWalls.ts +64 -0
- 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/game/strings.ts +2 -0
- 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/shared/host/standalone/harnessPlace.ts +4 -0
- package/src/test/engine/simState.ts +134 -0
- package/src/test/game/builtProduct.ts +6 -0
- package/src/test/game/headless/admittedProductCache.ts +61 -0
- package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
- package/src/test/game/headless/nativeBounds.ts +27 -0
- package/src/test/game/headless/processUsage.ts +22 -0
- package/src/test/game/headless/productSession.ts +39 -0
- package/src/test/game/headless/ropeBodies.ts +60 -0
- package/src/test/game/headless/worker.ts +34 -0
- package/src/test/game/headlessNative.ts +114 -0
- package/src/test/game/headlessWorker.ts +43 -0
- package/src/test/tsconfig.game.json +3 -0
|
@@ -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]';
|
|
@@ -59,7 +41,7 @@ export function processDirectories(){
|
|
|
59
41
|
}
|
|
60
42
|
// From /, so lsof itself never shows up in the folder being checked.
|
|
61
43
|
const listed=spawnSync('lsof',['-a','-d','cwd','-F','pn'],{cwd:'/',encoding:'utf8',maxBuffer:64<<20});
|
|
62
|
-
if(listed.error!==undefined||listed.stdout==='')return undefined;
|
|
44
|
+
if(listed.error!==undefined||listed.status!==0||listed.stdout==='')return undefined;
|
|
63
45
|
let pid=0;
|
|
64
46
|
for(const line of listed.stdout.split('\n')){
|
|
65
47
|
if(line.startsWith('p'))pid=Number(line.slice(1));
|
|
@@ -68,13 +50,14 @@ export function processDirectories(){
|
|
|
68
50
|
return found;
|
|
69
51
|
}
|
|
70
52
|
|
|
71
|
-
/** pid -> parent pid and command line, from `ps`. @returns {Map<number,{ppid:number,command:string}>} */
|
|
53
|
+
/** pid -> parent pid and command line, from `ps`. @returns {Map<number,{ppid:number,state:string,command:string}>} */
|
|
72
54
|
function processTable(){
|
|
73
|
-
/** @type {Map<number,{ppid:number,command:string}>} */const table=new Map();
|
|
74
|
-
const listed=spawnSync('ps',['-Ao','pid=,ppid=,command='],{encoding:'utf8',maxBuffer:64<<20});
|
|
55
|
+
/** @type {Map<number,{ppid:number,state:string,command:string}>} */const table=new Map();
|
|
56
|
+
const listed=spawnSync('ps',['-Ao','pid=,ppid=,stat=,command='],{encoding:'utf8',maxBuffer:64<<20});
|
|
57
|
+
if(listed.error!==undefined||listed.status!==0)throw new Error('process table unreadable');
|
|
75
58
|
for(const line of (listed.stdout??'').split('\n')){
|
|
76
|
-
const match=/^\s*(\d+)\s+(\d+)\s(.*)$/u.exec(line);
|
|
77
|
-
if(match!==null)table.set(Number(match[1]),{ppid:Number(match[2]),
|
|
59
|
+
const match=/^\s*(\d+)\s+(\d+)\s+(\S+)\s(.*)$/u.exec(line);
|
|
60
|
+
if(match!==null)table.set(Number(match[1]),{ppid:Number(match[2]),state:match[3]??'',command:match[4]??''});
|
|
78
61
|
}
|
|
79
62
|
return table;
|
|
80
63
|
}
|
|
@@ -89,10 +72,10 @@ function processTable(){
|
|
|
89
72
|
* @returns {number[]} */
|
|
90
73
|
export function stopWorktreeProcesses(tree,options={}){
|
|
91
74
|
const directories=processDirectories();
|
|
92
|
-
if(directories===undefined)
|
|
75
|
+
if(directories===undefined)throw new Error('process directories unreadable');
|
|
93
76
|
const table=processTable(),spared=new Set();
|
|
94
|
-
// Without the table nothing tells land's own parents apart
|
|
95
|
-
if(!table.has(process.pid))
|
|
77
|
+
// Without the table nothing tells land's own parents apart: retain the tree.
|
|
78
|
+
if(!table.has(process.pid))throw new Error('process ancestry unreadable');
|
|
96
79
|
for(let pid=process.pid;pid>1&&!spared.has(pid);pid=table.get(pid)?.ppid??0)spared.add(pid);
|
|
97
80
|
const shell=(/** @type {string} */ command)=>/^-?(?:\S*\/)?(?:ba|z|da|fi|k|tc|c)?sh$/u.test(command.trim());
|
|
98
81
|
// Only processes whose own working directory is inside: a daemon's children elsewhere are not this worktree's.
|
|
@@ -104,6 +87,17 @@ export function stopWorktreeProcesses(tree,options={}){
|
|
|
104
87
|
const until=Date.now()+3000,nap=new Int32Array(new SharedArrayBuffer(4));
|
|
105
88
|
while(Date.now()<until&&pids.some(pid=>signal(pid,0)))Atomics.wait(nap,0,0,50);
|
|
106
89
|
for(const pid of pids)signal(pid,'SIGKILL');
|
|
90
|
+
const killedUntil=Date.now()+1000;
|
|
91
|
+
let remaining=pids;
|
|
92
|
+
do{
|
|
93
|
+
const current=processTable();
|
|
94
|
+
// Exited children may remain zombies until their blocked parent reaps them.
|
|
95
|
+
// They cannot write; a live or uninspectable process still retains the tree.
|
|
96
|
+
remaining=pids.filter(pid=>current.get(pid)?.state.startsWith('Z')===false);
|
|
97
|
+
if(remaining.length===0)break;
|
|
98
|
+
Atomics.wait(nap,0,0,25);
|
|
99
|
+
}while(Date.now()<killedUntil);
|
|
100
|
+
if(remaining.length>0)throw new Error('a worktree process is still alive');
|
|
107
101
|
return pids;
|
|
108
102
|
}
|
|
109
103
|
|
|
@@ -120,22 +114,8 @@ export function freeBytes(path){
|
|
|
120
114
|
return volume.bavail*volume.bsize;
|
|
121
115
|
}
|
|
122
116
|
|
|
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
117
|
/** Is `sha` on origin/main itself? @param {string} canonical @param {string} sha */
|
|
136
118
|
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
119
|
|
|
140
120
|
/** @typedef {{path:string,head:string,branch:string}} Worktree */
|
|
141
121
|
|
|
@@ -159,102 +139,18 @@ export function linkedWorktrees(canonical){
|
|
|
159
139
|
* @param {NodeJS.ProcessEnv} env @param {(line:string)=>void} say
|
|
160
140
|
*/
|
|
161
141
|
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;}
|
|
142
|
+
// J358: this command is an inventory for a human audit. Land alone removes
|
|
143
|
+
// its own just-landed worktree, after a successful keep-copy.
|
|
166
144
|
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=[];
|
|
145
|
+
const cwds=directories===undefined?null:[...directories.values()];
|
|
192
146
|
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()}`);}
|
|
147
|
+
const slug=basename(tree.path);
|
|
148
|
+
if(resolve(tree.path)!==join(canonical,WORKTREES,slug)){
|
|
149
|
+
say(`skipped ${tree.path}: outside plan worktrees`);continue;
|
|
150
|
+
}
|
|
151
|
+
const state=laneLive(tree.path,{receipts:env.WS_LANE_RECEIPTS,cwds,activeLog:env.WS_ACTIVE_HOURS_LOG});
|
|
152
|
+
const landed=onMain(canonical,tree.head);
|
|
153
|
+
say(`${state.state} ${slug}: ${state.reason}; ${landed?'on origin/main':'not on origin/main'}; manual audit, copy before removal`);
|
|
251
154
|
}
|
|
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
155
|
return 0;
|
|
260
156
|
}
|
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.CODEX_THREAD_ID??env.CLAUDE_SESSION_ID??env.CLAUDE_CODE_SESSION_ID??lane,agent:env.CODEX_THREAD_ID?'codex':env.CLAUDE_SESSION_ID||env.CLAUDE_CODE_SESSION_ID?'claude':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
|
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ZONE-ENTRY ZE5 and ZE8 (J352): the walls and the gate card, by real input. From Driftwood (Shard Select), step out of its east
|
|
3
|
+
// entryway onto the road and shoot Nalati's wall across it; walk into Nalati's west buffer and shoot the gate card at 5 and at 2;
|
|
4
|
+
// at 3 back out and shoot it gone; walk in again, read 5 (the reset) and shoot it at 2. Each shot's page state (the gate's cell, count and card text)
|
|
5
|
+
// goes in one JSON. `--fire` stands on to 0 and records the zone entry: the navigation, the loading screen and the cell as the new home (ZE10).
|
|
6
|
+
// scripts/browser-lane.sh node scripts/zone-gate-proof.mjs --base=<preview or loopback url> --out=<dir> [--device='iPhone 15 Pro'] [--viewport=2992x1434@2]
|
|
7
|
+
// The walker is set 20 m inside Driftwood's east entryway by the in-page harness pose, so preview or a loopback page only (J205).
|
|
8
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { join, resolve as absolute } from 'node:path';
|
|
10
|
+
import { chromium, devices, webkit } from 'playwright';
|
|
11
|
+
import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
|
|
12
|
+
import { saveFixture } from './debug-settings.mjs';
|
|
13
|
+
|
|
14
|
+
/** @param {string} name @param {string} fallback */
|
|
15
|
+
const flag = (name, fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
|
|
16
|
+
const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', '')), engineName = flag('engine', 'chromium'), device = flag('device', ''), fire = process.argv.includes('--fire');
|
|
17
|
+
if (!/^https:\/\/preview\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: zone-gate-proof.mjs --base=<preview or loopback url> --out=<dir>');
|
|
18
|
+
const desk = (/^(\d+)x(\d+)@([\d.]+)$/u.exec(flag('viewport', '2992x1434@2')) ?? [0, '2992', '1434', '2']).slice(1).map(Number);
|
|
19
|
+
const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
|
|
20
|
+
const HALF = 250;
|
|
21
|
+
mkdirSync(out, { recursive: true });
|
|
22
|
+
const tag = `${engineName}${device === '' ? '' : '-phone'}`;
|
|
23
|
+
const result = { base, engine: engineName, viewport: '', at: new Date().toISOString(), build: '', shots: /** @type {Record<string, unknown>[]} */ ([]), fired: /** @type {unknown} */ (null), errors: /** @type {string[]} */ ([]), note: '' };
|
|
24
|
+
const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] : [] });
|
|
25
|
+
let code = 1;
|
|
26
|
+
try {
|
|
27
|
+
result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
|
|
28
|
+
const phone = device === '' ? undefined : devices[device];
|
|
29
|
+
if (device !== '' && phone === undefined) throw new Error(`No Playwright device ${device}`);
|
|
30
|
+
result.viewport = phone === undefined ? `${String(desk[0])}x${String(desk[1])}@${String(desk[2])}` : `${device} ${String(phone.viewport.width)}x${String(phone.viewport.height)}@${String(phone.deviceScaleFactor)}`;
|
|
31
|
+
const context = await browser.newContext(phone ?? { viewport: { width: desk[0] ?? 2992, height: desk[1] ?? 1434 }, deviceScaleFactor: desk[2] ?? 2 }), page = await context.newPage();
|
|
32
|
+
page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
|
|
33
|
+
await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
|
|
34
|
+
await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
|
|
35
|
+
await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: { volume: 0 } });
|
|
36
|
+
await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
|
|
37
|
+
await page.locator('.ws-main-select').click({ timeout: 120_000 });
|
|
38
|
+
if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('gate'); await page.locator('#ws-name-box button[type=submit]').click(); }
|
|
39
|
+
await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
|
|
40
|
+
const index = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes('Driftwood Isle')));
|
|
41
|
+
if (index < 0) throw new Error('No Driftwood Isle card');
|
|
42
|
+
await page.locator('.ws-menu-dots i').nth(index).click();
|
|
43
|
+
await page.locator('.ws-menu-play').click();
|
|
44
|
+
await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
|
|
45
|
+
await sleep(2000);
|
|
46
|
+
await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
|
|
47
|
+
const state = () => page.evaluate(() => { const W = /** @type {any} */ (window), st = W.__wildshard.shard.grid.state(), wf = st.live?.live?.worldFeet ?? W.__wildshard.world.player.position; return { x: Number(wf.x.toFixed(2)), z: Number(wf.z.toFixed(2)), gate: st.gate ?? null, walls: st.softWalls ?? null, inside: st.inside, cur: st.live?.live?.current ?? null }; });
|
|
48
|
+
const origin = await page.evaluate(() => { const W = /** @type {any} */ (window), wf = W.__wildshard.shard.grid.state().live.live.worldFeet, p = W.__wildshard.world.player.position; return { x: wf.x - p.x, z: wf.z - p.z }; });
|
|
49
|
+
const pitch = 562.5, nalatiEdge = origin.x + pitch - HALF;
|
|
50
|
+
const face = (/** @type {number} */ yaw) => page.evaluate(wanted => { /** @type {any} */ (window).__wildshard.world.player.yaw = wanted; }, yaw);
|
|
51
|
+
/** Walk with W held toward x (along z = origin.z) until within 0.4 m. */
|
|
52
|
+
const walkTo = async (/** @type {number} */ x) => {
|
|
53
|
+
for (const ends = Date.now() + 60_000; Date.now() < ends;) {
|
|
54
|
+
const at = await state(); if (Math.abs(at.x - x) < 0.4) break;
|
|
55
|
+
await face(Math.atan2(at.x - x, at.z - origin.z)); await page.keyboard.down('KeyW'); await sleep(Math.min(400, Math.abs(at.x - x) * 200)); await page.keyboard.up('KeyW');
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const shoot = async (/** @type {string} */ name) => { await page.screenshot({ path: join(out, `${tag}-${name}.png`) }); result.shots.push({ name, ...await state() }); };
|
|
59
|
+
await page.evaluate(([px, pz]) => { const p = /** @type {any} */ (window).__wildshard.world.player; p.spawn(px, pz, p.yaw, 1.5); p.link?.place?.(p.position.x, p.position.y, p.position.z, p.yaw); }, [HALF - 20, 0]);
|
|
60
|
+
await sleep(4000);
|
|
61
|
+
await walkTo(origin.x + HALF + 31.25); await face(-Math.PI / 2); await sleep(1500);
|
|
62
|
+
await shoot('road-wall');
|
|
63
|
+
/** Poll the gate until `test` holds (or 8 s). */
|
|
64
|
+
const until = async (/** @type {(gate: any) => boolean} */ test) => { for (const ends = Date.now() + 8000; Date.now() < ends; await sleep(50)) if (test((await state()).gate)) return true; return false; };
|
|
65
|
+
// in, 2 m past the edge line: the card at 5; back out of the buffer at 3 (so the count can't reach 0 on the way out)
|
|
66
|
+
await walkTo(nalatiEdge + 2); await until(gate => gate?.count === 5); await shoot('gate-5');
|
|
67
|
+
await until(gate => gate?.count === 3);
|
|
68
|
+
await walkTo(nalatiEdge - 6); await face(-Math.PI / 2); await sleep(600);
|
|
69
|
+
await shoot('backed-away');
|
|
70
|
+
// in again: 5 (the reset), then 2
|
|
71
|
+
await walkTo(nalatiEdge + 2); await until(gate => gate?.count === 5); await shoot('gate-again');
|
|
72
|
+
await until(gate => gate?.count === 2); await shoot('gate-2');
|
|
73
|
+
if (fire) {
|
|
74
|
+
// stand on: 0 opens the loading screen and the page enters the cell as its home
|
|
75
|
+
const before = page.url();
|
|
76
|
+
const left = await page.waitForEvent('framenavigated', { timeout: 6000 }).then(() => true).catch(() => false);
|
|
77
|
+
await page.screenshot({ path: join(out, `${tag}-gate-0-loading.png`) }).catch(() => undefined);
|
|
78
|
+
const ready = await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 250 }).then(() => true).catch(() => false);
|
|
79
|
+
const home = await page.evaluate(() => { const W = /** @type {any} */ (window), st = W.__wildshard?.shard?.grid?.state?.(); return { home: st?.live?.live?.home ?? st?.home ?? null, current: st?.live?.live?.current ?? null, slug: W.__wildshard?.shard?.slug ?? null }; }).catch(() => null);
|
|
80
|
+
if (ready) await page.screenshot({ path: join(out, `${tag}-entered.png`) });
|
|
81
|
+
result.fired = { navigated: left, before, after: page.url(), ready, home };
|
|
82
|
+
}
|
|
83
|
+
const named = (/** @type {string} */ name) => /** @type {any} */ (result.shots.find(row => row.name === name))?.gate;
|
|
84
|
+
const [at5, gone, again, at2] = ['gate-5', 'backed-away', 'gate-again', 'gate-2'].map(named);
|
|
85
|
+
console.log(JSON.stringify({ at5, at2, gone, again, fired: result.fired }));
|
|
86
|
+
await context.close();
|
|
87
|
+
code = at5?.count === 5 && at2?.count === 2 && gone?.cell === null && again?.count === 5 && result.errors.length === 0 && (!fire || /** @type {any} */ (result.fired)?.ready === true) ? 0 : 1;
|
|
88
|
+
} catch (error) { result.note = String(error).slice(0, 400); console.log(`FAIL ${result.note}`); }
|
|
89
|
+
finally {
|
|
90
|
+
writeFileSync(join(out, `${tag}-zone-gate.json`), `${JSON.stringify(result, null, 2)}\n`);
|
|
91
|
+
await browser.close();
|
|
92
|
+
}
|
|
93
|
+
process.exit(code);
|
|
@@ -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
|
}
|
|
@@ -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
|
+
}
|