@wildshard/engine 0.1.22 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +2 -0
  3. package/lint/sim-players.json +2 -13
  4. package/package.json +9 -2
  5. package/scripts/apfs-clone.mjs +5 -2
  6. package/scripts/app-build/catalogue.ts +39 -8
  7. package/scripts/app-build/serviceWorker.ts +4 -1
  8. package/scripts/app-build/splitOutput.mjs +33 -11
  9. package/scripts/ci-pack.mjs +3 -3
  10. package/scripts/engine-ci-shard.mjs +11 -0
  11. package/scripts/fight-page-census.mjs +131 -0
  12. package/scripts/goldens/board.py +44 -11
  13. package/scripts/goldens/native-residency.d.mts +1 -0
  14. package/scripts/goldens/native-residency.mjs +18 -4
  15. package/scripts/keep-copy.mjs +120 -0
  16. package/scripts/land.mjs +36 -6
  17. package/scripts/lane-live.mjs +136 -0
  18. package/scripts/leftovers-report.mjs +47 -0
  19. package/scripts/loading-card-proof.mjs +42 -9
  20. package/scripts/loading-flow/benchmax.mjs +57 -7
  21. package/scripts/loading-flow/stalls.d.mts +2 -0
  22. package/scripts/loading-flow/stalls.mjs +13 -0
  23. package/scripts/mmo-bots.mjs +5 -3
  24. package/scripts/mmo-grid-proof.mjs +74 -0
  25. package/scripts/mmo-seat-proof.mjs +43 -0
  26. package/scripts/nightly-heads.ts +13 -13
  27. package/scripts/nightly-model.ts +26 -12
  28. package/scripts/nightly.proof.ts +18 -5
  29. package/scripts/nightly.ts +13 -8
  30. package/scripts/no-astc-boot.mjs +77 -0
  31. package/scripts/physics-route.json +6 -6
  32. package/scripts/pins-reuse.mjs +1 -0
  33. package/scripts/pins-staging.ts +54 -0
  34. package/scripts/pins.ts +5 -0
  35. package/scripts/ring3.proof.ts +71 -0
  36. package/scripts/ring3.ts +100 -0
  37. package/scripts/scratch-dir.mjs +31 -12
  38. package/scripts/scratch-sweep.mjs +15 -23
  39. package/scripts/server-release/items.d.mts +7 -0
  40. package/scripts/server-release/items.mjs +28 -0
  41. package/scripts/server-release/publish.mjs +9 -1
  42. package/scripts/side-parity.mjs +1 -1
  43. package/scripts/test-products.json +1 -0
  44. package/scripts/tsconfig.json +2 -0
  45. package/scripts/vitest-ci-files.ts +5 -1
  46. package/scripts/vps/wildshard-config +106 -1
  47. package/scripts/warm-native-chrome.mjs +9 -3
  48. package/scripts/worker-client-fights.mjs +9 -3
  49. package/scripts/worktree-reap.mjs +15 -131
  50. package/scripts/worktree.mjs +92 -12
  51. package/src/client/engine/audio/audioLog.ts +7 -2
  52. package/src/client/engine/boot/diagnostics.ts +69 -1
  53. package/src/client/engine/core/ktx2.ts +5 -3
  54. package/src/client/engine/core/ktx2Zstd.ts +2 -1
  55. package/src/client/engine/pwa/sw.js +26 -8
  56. package/src/client/engine/render/dataLook.ts +14 -7
  57. package/src/client/engine/render/lookLight.ts +64 -20
  58. package/src/client/engine/ui/Loading.ts +6 -8
  59. package/src/client/engine/ui/lookLightOption.ts +1 -1
  60. package/src/client/game/audio/cueDirector.ts +2 -1
  61. package/src/client/game/boss/arenaRoom.ts +4 -3
  62. package/src/client/game/boss/roamingProjection.ts +1 -1
  63. package/src/client/game/devScene/hook.ts +1 -1
  64. package/src/client/game/devScene/liveLook.ts +1 -1
  65. package/src/client/game/grid/dataCellKit.ts +9 -1
  66. package/src/client/game/grid/products.ts +21 -7
  67. package/src/client/game/grid/session.ts +6 -4
  68. package/src/client/game/population/signals.ts +1 -1
  69. package/src/client/game/quest/chapterDirector.ts +1 -0
  70. package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
  71. package/src/client/game/shardfile/clientWorker.ts +22 -6
  72. package/src/client/game/shardfile/look.ts +1 -1
  73. package/src/client/game/shardfile/runtimeProduct.ts +9 -5
  74. package/src/client/game/shardfile/wirePage.ts +5 -2
  75. package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
  76. package/src/cook/game/cookWorker.ts +8 -5
  77. package/src/cook/game/tierTextures.ts +5 -3
  78. package/src/server/engine/net/simWorld.ts +3 -4
  79. package/src/server/game/grid/cellHome.ts +58 -0
  80. package/src/server/game/grid/simulation.ts +5 -4
  81. package/src/server/game/plugin/mover.ts +18 -14
  82. package/src/server/game/shardfile/declaredKitItems.ts +31 -7
  83. package/src/server/host/bake/headlessWorker.ts +3 -3
  84. package/src/server/host/dedicated/cellWorker.ts +4 -2
  85. package/src/server/host/dedicated/main.ts +7 -4
  86. package/src/server/host/dedicated/packReader.ts +15 -2
  87. package/src/server/host/dedicated/playerStore.ts +1 -1
  88. package/src/server/host/headlessRuntime.ts +11 -6
  89. package/src/server/host/standalone/cellWorld.ts +20 -6
  90. package/src/server/host/standalone/gridServer.ts +3 -1
  91. package/src/server/host/standalone/roadWorld.ts +6 -0
  92. package/src/shared/engine/physics/gridBorders.ts +15 -1
  93. package/src/shared/engine/sim/snapshot.ts +5 -5
  94. package/src/shared/game/ledger.ts +13 -4
  95. package/src/shared/game/loot/platformCatalogue.ts +14 -0
  96. package/src/shared/game/quest/ledger.ts +3 -3
  97. package/src/shared/game/shardfile/items.ts +9 -1
  98. package/src/shared/host/headlessJourney.ts +3 -3
  99. package/src/shared/host/headlessTape.ts +7 -6
  100. package/src/shared/host/releaseRows.ts +4 -1
@@ -8,6 +8,9 @@
8
8
  # wildshard-config cook <tag> AUTO-RELEASE AR4 (J355): move the cook worker to vX.Y.Z and
9
9
  # the build a signed release names for it; roll back on failure
10
10
  # wildshard-config show cook print the cook worker's tag and build
11
+ # wildshard-config saves list [--production] QA 11-15 row 24: every player's id, name and created_at
12
+ # wildshard-config saves delete-test <id>... [--production] [--yes]
13
+ # a test or bot player's rows, a dry run unless --yes
11
14
  # Settings live in /etc/wildshard/<channel>.settings (640 root:wildshard-<channel>), which the units read after <channel>.env.
12
15
  # Secrets stay in the root-only .env, and this never prints one or writes one (it reads only the placement rows there, for
13
16
  # the pair check below): only the keys in SETTINGS below, each
@@ -274,9 +277,111 @@ def cook(args):
274
277
  return 1
275
278
 
276
279
 
280
+ # QA 11-15 row 24 (Jake: "why dont you have an admin tool you can run on the VPS to clean it up yourself"): the agents clear
281
+ # the players their own probes and bots left in a saves database, and nobody else. Staging unless --production; a delete is a
282
+ # dry run unless --yes. Only a name a test or a bot takes can go: a probe's r<N><shard> (r13pine), the live proofs' Agent X,
283
+ # and Bot. Every table with a player_id column loses that player's rows and `player` its row, in one transaction that checks
284
+ # the names again under a row lock; the box journal (tag wildshard-saves) records each delete.
285
+ SAVES_ID = r'[A-Za-z0-9:._-]{1,128}'
286
+ TEST_NAMES = r'r[0-9]+[a-z][a-z0-9-]*|Agent( [A-Za-z0-9]+)+|[Bb]ot([ _-]?[A-Za-z0-9]+)?'
287
+ SAVES_MAX = 50
288
+ SAVES_TABLE = r'[a-z_][a-z0-9_]{0,62}'
289
+
290
+
291
+ def psql(channel, sql, variables=None):
292
+ """Rows (tab-separated fields) from SQL on the channel's saves database, run as postgres. The ids reach it only as psql
293
+ variables (:'ids'), never inside the SQL text."""
294
+ if TEST:
295
+ command = os.environ.get('WILDSHARD_CONFIG_TEST_PSQL', '/nonexistent').split(' ')
296
+ else:
297
+ command = ['/usr/sbin/runuser', '-u', 'postgres', '--', '/usr/bin/psql', '--cluster', '16/main', '-d', f'saves_{channel}']
298
+ command += ['-X', '-q', '-t', '-A', '-F', '\t', '-v', 'ON_ERROR_STOP=1']
299
+ for key, value in (variables or {}).items():
300
+ command += ['-v', f'{key}={value}']
301
+ try:
302
+ run = subprocess.run(command, input=sql, capture_output=True, text=True, cwd='/', env=helper_env())
303
+ except OSError as error:
304
+ stop(f'psql did not start: {error}')
305
+ if run.returncode != 0:
306
+ stop(f'psql on saves_{channel} exited {run.returncode}: {(run.stderr.strip().splitlines() or ["no message"])[-1]}')
307
+ return [line.split('\t') for line in run.stdout.splitlines() if line != '']
308
+
309
+
310
+ def journal(line):
311
+ """One line in the box journal, tag wildshard-saves; the test's stand-in logger instead (never as root)."""
312
+ logger = os.environ.get('WILDSHARD_CONFIG_TEST_LOGGER') if TEST else '/usr/bin/logger'
313
+ if logger:
314
+ subprocess.run([logger, '-t', 'wildshard-saves', '-p', 'auth.notice', '--', line], cwd='/', env=helper_env())
315
+
316
+
317
+ def saves(args, production):
318
+ channel = 'production' if production else 'staging'
319
+ if args[1:2] == ['list'] and len(args) == 2:
320
+ for row in psql(channel, "select id, name, to_char(created_at at time zone 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') "
321
+ 'from player order by created_at, id;'):
322
+ print(' '.join(row))
323
+ return 0
324
+ if args[1:2] != ['delete-test']:
325
+ stop('usage: wildshard-config saves list [--production] | saves delete-test <id>... [--production] [--yes]')
326
+ sure = '--yes' in args
327
+ ids = [arg for arg in args[2:] if arg != '--yes']
328
+ if not ids or len(ids) > SAVES_MAX or len(set(ids)) != len(ids):
329
+ stop(f'name 1 to {SAVES_MAX} player ids, none twice')
330
+ for player in ids:
331
+ if re.fullmatch(SAVES_ID, player) is None:
332
+ stop(f'{player!r} is not a player id (A-Z a-z 0-9 : . _ -)')
333
+ variables = {'ids': '{' + ','.join(f'"{player}"' for player in ids) + '}', 'names': f'^({TEST_NAMES})$', 'n': str(len(ids))}
334
+ names = dict(psql(channel, "select id, name from player where id = any(:'ids'::text[]);", variables))
335
+ missing = [player for player in ids if player not in names]
336
+ if missing:
337
+ stop(f'no player {", ".join(missing)} in saves_{channel}; nothing deleted')
338
+ kept = [f'{player} ({names[player]!r})' for player in ids if re.fullmatch(TEST_NAMES, names[player]) is None]
339
+ if kept:
340
+ stop(f'not a test or bot name, so refused: {", ".join(kept)}; nothing deleted')
341
+ tables = [row[0] for row in psql(channel, "select table_name from information_schema.columns where table_schema = 'public' "
342
+ "and column_name = 'player_id' and table_name <> 'player' order by table_name;")]
343
+ for table in tables:
344
+ if re.fullmatch(SAVES_TABLE, table) is None:
345
+ stop(f'unexpected table name {table!r}; nothing deleted')
346
+ counts = {}
347
+ if tables:
348
+ union = ' union all '.join(f"select '{table}', player_id, count(*) from public.\"{table}\" where player_id = any(:'ids'::text[]) "
349
+ 'group by player_id' for table in tables)
350
+ for table, player, count in psql(channel, union + ';', variables):
351
+ counts.setdefault(player, []).append(f'{table} {count}')
352
+ for player in ids:
353
+ print(f'{"delete" if sure else "would":<7} saves_{channel} {player} {names[player]!r}: {", ".join(counts.get(player, [])) or "no rows"} and its player row')
354
+ if not sure:
355
+ print('dry run: nothing deleted; add --yes to delete')
356
+ return 0
357
+ # Under a row lock the names are read again, so a player who took a real name since is never deleted.
358
+ deletes = '\n'.join(f"with gone as (delete from public.\"{table}\" where player_id = any(:'ids'::text[]) returning 1) "
359
+ f"select '{table}', count(*) from gone;" for table in tables)
360
+ done = psql(channel, f"""begin;
361
+ select count(*) = :n as matched from (select id from player where id = any(:'ids'::text[]) and name ~ :'names' for update) locked \\gset
362
+ \\if :matched
363
+ {deletes}
364
+ with gone as (delete from player where id = any(:'ids'::text[]) returning 1) select 'player', count(*) from gone;
365
+ commit;
366
+ \\else
367
+ rollback;
368
+ select 'changed', 0;
369
+ \\endif
370
+ """, variables)
371
+ if ['changed', '0'] in done:
372
+ stop('a player changed its name or left while this ran; nothing deleted')
373
+ summary = ', '.join(f'{table} {count}' for table, count in done)
374
+ who = os.environ.get('SUDO_USER', 'root')
375
+ journal(f'saves delete-test saves_{channel} by {who}: ' + ' '.join(f'{player}={names[player]!r}' for player in ids) + f' ({summary})')
376
+ print(f'ok saves_{channel} deleted {summary}; the box journal has it (journalctl -t wildshard-saves)')
377
+ return 0
378
+
379
+
277
380
  def main(argv):
278
381
  production = '--production' in argv
279
382
  args = [arg for arg in argv if arg != '--production']
383
+ if args and args[0] == 'saves':
384
+ return saves(args, production)
280
385
  if args and args[0] == 'cook':
281
386
  return cook(args)
282
387
  if args[:2] == ['show', 'cook'] and len(args) == 2:
@@ -285,7 +390,7 @@ def main(argv):
285
390
  stop('the cook worker moves with: wildshard-config cook vX.Y.Z')
286
391
  if not args or args[0] not in ('show', 'set', 'split'):
287
392
  stop('usage: wildshard-config show <channel> | set <channel> <KEY> <value> [<KEY> <value>]... [--production] | split <channel> '
288
- '| cook vX.Y.Z | show cook')
393
+ '| cook vX.Y.Z | show cook | saves list|delete-test ...')
289
394
  verb = args[0]
290
395
  if len(args) < 2 or args[1] not in CHANNELS:
291
396
  stop('the channel is production or staging')
@@ -3,15 +3,21 @@ import {existsSync} from 'node:fs';
3
3
  import {open, readdir, realpath} from 'node:fs/promises';
4
4
  import {dirname, join, resolve} from 'node:path';
5
5
  import {pathToFileURL} from 'node:url';
6
- import {chromium} from 'playwright';
6
+ import {createRequire} from 'node:module';
7
7
 
8
8
  /** The native control and its untimed disk preparation must select the same
9
9
  * installed browser. Explicit selection wins, with no fallback after failure.
10
10
  * @returns {string} */
11
11
  export function nativeChromeExecutable() {
12
12
  const candidates=[process.env.CHROME_PATH,process.env.CHROME_BIN,
13
- ...(process.platform==='linux'?['/usr/bin/google-chrome','/usr/bin/chromium']:[]),chromium.executablePath()];
14
- const executable=candidates.find(file=>file!==undefined&&existsSync(file));
13
+ ...(process.platform==='linux'?['/usr/bin/google-chrome','/usr/bin/chromium']:[])];
14
+ const selected=candidates.find(file=>file!==undefined&&existsSync(file));
15
+ if(selected!==undefined)return selected;
16
+ // Native controls with an explicit executable need no automation graph.
17
+ // Keep the ordinary installed-Playwright fallback for unprepared local runs.
18
+ const {chromium}=createRequire(import.meta.url)('playwright');
19
+ const fallback=chromium.executablePath();
20
+ const executable=existsSync(fallback)?fallback:undefined;
15
21
  if(executable===undefined)throw new Error('No installed Chromium for the original trusted-input control');
16
22
  return executable;
17
23
  }
@@ -12,9 +12,12 @@ const listen = page => page.evaluate(() => {
12
12
  for (const name of ['combat', 'sting']) record(world.music, name);
13
13
  });
14
14
  const heardOf = page => page.evaluate(() => (window.__said ?? []).slice(-14));
15
+ /** EG-15: when the census sets `sink`, it sees every page these journeys open (`opened`) and reads each one last as its context closes. */
16
+ export const pageCensus = { sink: null };
15
17
  /** Open one shard with the row on, entered and on the wire. */
16
18
  async function open(browser, phone, base, slug, query = '') {
17
- const context = await browser.newContext(phone), page = await context.newPage(), errors = [];
19
+ const context = await browser.newContext(phone), page = await context.newPage(), errors = [], { sink } = pageCensus;
20
+ if (sink !== null) { const close = context.close.bind(context); context.close = async () => { await sink.closing(slug, page); return close(); }; }
18
21
  page.on('pageerror', error => { errors.push(error.message.slice(0, 300)); });
19
22
  page.on('console', line => { if (line.type() === 'error') errors.push(line.text().slice(0, 300)); });
20
23
  await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
@@ -23,8 +26,11 @@ async function open(browser, phone, base, slug, query = '') {
23
26
  await page.waitForFunction(() => typeof window.__workerClient === 'function', undefined, { timeout: 150_000 });
24
27
  await page.evaluate(FLOOR_GRID_ENTER);
25
28
  await page.waitForFunction(() => window.__workerClient().frames > 30, undefined, { timeout: 60_000 });
29
+ if (sink !== null) sink.opened(slug, page);
26
30
  return { context, page, errors };
27
31
  }
32
+ /** A fresh boot of the same shard by its own URL, as a player reopens it. A reload can't: a started page drops its query, so it lands on the title. */
33
+ const reboot = (page, base, slug, query = '') => page.goto(new URL(`/?chunk=${slug}&mute=1&nolock=1${query}`, base).href, { waitUntil: 'load' });
28
34
  const report = page => page.evaluate(() => window.__workerClient());
29
35
  const fight = (page, id) => page.evaluate(want => window.__workerClientFights().find(row => row.id === want) ?? null, id);
30
36
  const place = (page, x, y, z) => page.evaluate(([px, py, pz]) => { window.__wildshard.world.player.link.place(px, py, pz, 0); }, [x, y, z]);
@@ -721,7 +727,7 @@ async function qaraJourney(browser, phone, base, step) {
721
727
  await step('qara: a save keeps him fallen and a page\'s fresh boot reads it back', async () => {
722
728
  await page.evaluate(() => Promise.race([window.__workerClientSave(), new Promise(resolve => { setTimeout(resolve, 20_000); })]));
723
729
  const before = await fight(page, id);
724
- await page.reload({ waitUntil: 'load' });
730
+ await reboot(page, base, 'nalati-grasslands', '&bossGod');
725
731
  await page.waitForFunction(() => window.__wildshard?.world?.player !== undefined, undefined, { timeout: 150_000 });
726
732
  await page.waitForFunction(() => typeof window.__workerClient === 'function', undefined, { timeout: 150_000 });
727
733
  await page.evaluate(FLOOR_GRID_ENTER);
@@ -810,7 +816,7 @@ async function qyranJourney(browser, phone, base, step) {
810
816
  await step('qyran: a save keeps him fallen and a page\'s fresh boot reads it back', async () => {
811
817
  await page.evaluate(() => Promise.race([window.__workerClientSave(), new Promise(resolve => { setTimeout(resolve, 20_000); })]));
812
818
  const before = await fight(page, id);
813
- await page.reload({ waitUntil: 'load' });
819
+ await reboot(page, base, 'nalati-grasslands');
814
820
  await page.waitForFunction(() => window.__wildshard?.world?.player !== undefined, undefined, { timeout: 150_000 });
815
821
  await page.waitForFunction(() => typeof window.__workerClient === 'function', undefined, { timeout: 150_000 });
816
822
  await page.evaluate(FLOOR_GRID_ENTER);
@@ -1,27 +1,9 @@
1
- // DEV-SPEED DS13: `node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]` removes the plan
2
- // worktrees whose work is on main, and nothing else. Safe to run any time, from any checkout of the repo.
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 {appendFileSync,existsSync,mkdirSync,readdirSync,readlinkSync,realpathSync,statSync,statfsSync} from 'node:fs';
22
- import {homedir} from 'node:os';
23
- import {basename,dirname,join,resolve,sep} from 'node:path';
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
- const common=join(canonical,'.git');
163
- if(existsSync(join(common,'wildshard-worktree-setup.lock'))){say('reap STOP a worktree setup is running; retry when it finishes');return 1;}
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 realRoot=realpathSync(canonical),now=Date.now(),freeBefore=freeBytes(canonical);
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),branch=`refs/heads/plan/${slug}`;
194
- const keep=(/** @type {string} */ why)=>{kept.push(`${slug} (${why})`);say(`kept ${slug}: ${why}`);};
195
- if(resolve(tree.path)!==join(canonical,WORKTREES,slug)&&resolve(tree.path)!==join(realRoot,WORKTREES,slug)){say(`skipped ${tree.path}: not a plan worktree of this checkout`);continue;}
196
- // Physically too: a linked .worktrees/ or worktree folder may point anywhere.
197
- let physical='';
198
- try{physical=realpathSync(tree.path);}catch{/* Gone: kept below. */}
199
- if(physical!==''&&(physical!==join(realRoot,WORKTREES,slug)||realpathSync(join(canonical,WORKTREES))!==join(realRoot,WORKTREES))){say(`skipped ${tree.path}: resolves to ${physical}, outside ${join(realRoot,WORKTREES)}`);continue;}
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
  }
@@ -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 {freeBytes,parseReapArgs,reap} from './worktree-reap.mjs';
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 unknown=rest.filter(arg=>!flags.has(arg));
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
- return {slug,install:!rest.includes('--no-install'),pins:!rest.includes('--no-pins'),herdr:!rest.includes('--no-herdr'),clone:!rest.includes('--no-clone')};
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
- const scripts=/** @type {{scripts?:Record<string,string>}} */(JSON.parse(readFileSync(join(tree,'package.json'),'utf8'))).scripts??{};
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 record={slug:options.slug,branch,base,tree,total,steps,disk,finished:new Date().toISOString()};
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
- const lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):'';
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===''?'<lane>':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 ci and ring-1, 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`);
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
 
@@ -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
- if (typeof window !== 'undefined') (window as unknown as { __audioLog: AudioLogEntry[] }).__audioLog = log;
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
  }