@wildshard/engine 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lint/engine-sides.json +5 -0
  3. package/lint/shardfile-boundaries.mjs +4 -2
  4. package/lint/sim-players.json +2 -13
  5. package/lint/wildshard-plugin.js +1 -1
  6. package/package.json +10 -2
  7. package/scripts/apfs-clone.mjs +5 -2
  8. package/scripts/app-build/catalogue.ts +39 -8
  9. package/scripts/app-build/serviceWorker.ts +4 -1
  10. package/scripts/app-build/splitOutput.mjs +33 -11
  11. package/scripts/audio-download-proof.mjs +1 -1
  12. package/scripts/check-spelled-paths.mjs +6 -3
  13. package/scripts/ci-pack.mjs +3 -3
  14. package/scripts/committed-fast-checks.mjs +2 -2
  15. package/scripts/engine-ci-shard.mjs +11 -0
  16. package/scripts/failmode-cases.mjs +1 -1
  17. package/scripts/failmode-proof.mjs +35 -11
  18. package/scripts/fight-page-census.mjs +131 -0
  19. package/scripts/goldens/board.py +44 -11
  20. package/scripts/goldens/native-residency.d.mts +1 -0
  21. package/scripts/goldens/native-residency.mjs +18 -4
  22. package/scripts/grid-crossing-walk-proof.mjs +3 -3
  23. package/scripts/hover-speed-probe.mjs +2 -2
  24. package/scripts/keep-copy.mjs +120 -0
  25. package/scripts/land.mjs +36 -6
  26. package/scripts/lane-live.mjs +136 -0
  27. package/scripts/leftovers-report.mjs +47 -0
  28. package/scripts/loading-card-proof.mjs +42 -9
  29. package/scripts/loading-flow/benchmax.mjs +57 -7
  30. package/scripts/loading-flow/stalls.d.mts +2 -0
  31. package/scripts/loading-flow/stalls.mjs +13 -0
  32. package/scripts/mmo-bots.mjs +11 -5
  33. package/scripts/mmo-grid-proof.mjs +74 -0
  34. package/scripts/mmo-seat-proof.mjs +43 -0
  35. package/scripts/net-lag-proof.mjs +1 -1
  36. package/scripts/nightly-heads.ts +13 -13
  37. package/scripts/nightly-model.ts +26 -12
  38. package/scripts/nightly.proof.ts +18 -5
  39. package/scripts/nightly.ts +13 -8
  40. package/scripts/no-astc-boot.mjs +77 -0
  41. package/scripts/online-rig.mjs +7 -7
  42. package/scripts/parity/boot-smoke.mjs +1 -1
  43. package/scripts/physics-route.json +6 -6
  44. package/scripts/pins-reuse.mjs +1 -0
  45. package/scripts/pins-staging.ts +54 -0
  46. package/scripts/pins.ts +5 -0
  47. package/scripts/release-cook.mjs +6 -2
  48. package/scripts/ring3.proof.ts +71 -0
  49. package/scripts/ring3.ts +100 -0
  50. package/scripts/scratch-dir.mjs +31 -12
  51. package/scripts/scratch-sweep.mjs +15 -23
  52. package/scripts/server-release/items.d.mts +7 -0
  53. package/scripts/server-release/items.mjs +28 -0
  54. package/scripts/server-release/publish.mjs +9 -1
  55. package/scripts/side-parity.mjs +1 -1
  56. package/scripts/test-products.json +1 -21
  57. package/scripts/tsconfig.json +2 -0
  58. package/scripts/vitest-ci-files.ts +5 -1
  59. package/scripts/vps/cook-follow.d.mts +6 -0
  60. package/scripts/vps/cook-follow.mjs +45 -0
  61. package/scripts/vps/harden-apply.sh +10 -1
  62. package/scripts/vps/rebuild.sh +104 -36
  63. package/scripts/vps/wildshard-config +106 -3
  64. package/scripts/warm-native-chrome.mjs +9 -3
  65. package/scripts/worker-client-fights.mjs +9 -3
  66. package/scripts/worktree-reap.mjs +15 -131
  67. package/scripts/worktree.mjs +92 -12
  68. package/src/client/app/entry.ts +2 -3
  69. package/src/client/engine/audio/audioLog.ts +7 -2
  70. package/src/client/engine/boot/contentRead.ts +24 -4
  71. package/src/client/engine/boot/diagnostics.ts +69 -1
  72. package/src/client/engine/boot/downloadGiveUp.ts +34 -0
  73. package/src/client/engine/combat/EquipmentService.ts +2 -0
  74. package/src/client/engine/core/Game.ts +6 -2
  75. package/src/client/engine/core/ktx2.ts +5 -3
  76. package/src/client/engine/core/ktx2Zstd.ts +2 -1
  77. package/src/client/engine/pwa/sw.js +26 -8
  78. package/src/client/engine/render/dataLook.ts +14 -7
  79. package/src/client/engine/render/lookLight.ts +64 -20
  80. package/src/client/engine/ui/Loading.ts +6 -8
  81. package/src/client/engine/ui/downloadFailed.ts +54 -0
  82. package/src/client/engine/ui/lookLightOption.ts +1 -1
  83. package/src/client/game/audio/cueDirector.ts +2 -1
  84. package/src/client/game/boot/spawnDownload.ts +12 -1
  85. package/src/client/game/boss/arenaRoom.ts +4 -3
  86. package/src/client/game/boss/roamingProjection.ts +1 -1
  87. package/src/client/game/devScene/hook.ts +1 -1
  88. package/src/client/game/devScene/liveLook.ts +1 -1
  89. package/src/client/game/grid/copyPrompts.ts +3 -4
  90. package/src/client/game/grid/dataCellKit.ts +99 -0
  91. package/src/client/game/grid/enteredEquipment.ts +11 -2
  92. package/src/client/game/grid/live.ts +9 -299
  93. package/src/client/game/grid/liveSession.ts +31 -8
  94. package/src/client/game/grid/neighbourLife.ts +50 -32
  95. package/src/client/game/grid/products.ts +21 -7
  96. package/src/client/game/grid/reveal.ts +7 -2
  97. package/src/client/game/grid/session.ts +10 -74
  98. package/src/client/game/plugin/weaponFamily.ts +6 -0
  99. package/src/client/game/population/signals.ts +1 -1
  100. package/src/client/game/quest/chapterDirector.ts +1 -0
  101. package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
  102. package/src/client/game/shardfile/clientWorker.ts +35 -9
  103. package/src/client/game/shardfile/look.ts +1 -1
  104. package/src/client/game/shardfile/runtimeProduct.ts +9 -5
  105. package/src/client/game/shardfile/wirePage.ts +5 -2
  106. package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
  107. package/src/client/host/online/shell.ts +37 -13
  108. package/src/cook/game/cookWorker.ts +8 -5
  109. package/src/cook/game/tierTextures.ts +5 -3
  110. package/src/server/engine/net/simWorld.ts +3 -4
  111. package/src/server/game/grid/cellHome.ts +58 -0
  112. package/src/server/game/grid/room.ts +2 -38
  113. package/src/server/game/grid/simulation.ts +5 -4
  114. package/src/server/game/plugin/mover.ts +18 -14
  115. package/src/server/game/shardfile/declaredKitItems.ts +39 -9
  116. package/src/server/host/bake/headlessWorker.ts +3 -3
  117. package/src/server/host/dedicated/cellHost.ts +2 -2
  118. package/src/server/host/dedicated/cellProtocol.ts +1 -1
  119. package/src/server/host/dedicated/cellWorker.ts +5 -3
  120. package/src/server/host/dedicated/dedicatedRoom.ts +8 -3
  121. package/src/server/host/dedicated/gridCells.ts +5 -3
  122. package/src/server/host/dedicated/main.ts +12 -7
  123. package/src/server/host/dedicated/packReader.ts +15 -2
  124. package/src/server/host/dedicated/playerStore.ts +1 -1
  125. package/src/server/host/dedicated/workerTable.ts +0 -10
  126. package/src/server/host/dedicated/world.ts +39 -5
  127. package/src/server/host/headlessRuntime.ts +11 -6
  128. package/src/server/host/standalone/cellWorld.ts +21 -7
  129. package/src/server/host/standalone/gridServer.ts +3 -1
  130. package/src/server/host/standalone/roadWorld.ts +6 -0
  131. package/src/shared/engine/physics/gridBorders.ts +15 -1
  132. package/src/shared/engine/saves/shape.ts +17 -2
  133. package/src/shared/engine/sim/snapshot.ts +5 -5
  134. package/src/shared/engine/strings.ts +10 -0
  135. package/src/shared/game/grid/placementRows.ts +4 -3
  136. package/src/shared/game/ledger.ts +13 -4
  137. package/src/shared/game/loot/platformCatalogue.ts +14 -0
  138. package/src/shared/game/quest/ledger.ts +3 -3
  139. package/src/shared/game/shardfile/items.ts +9 -1
  140. package/src/shared/host/headlessJourney.ts +3 -3
  141. package/src/shared/host/headlessTape.ts +7 -6
  142. package/src/shared/host/releaseRows.ts +4 -1
  143. package/src/client/game/grid/cellLoading.ts +0 -110
  144. package/src/client/game/grid/cellScreens.ts +0 -48
@@ -10,7 +10,6 @@ import type { GridAssembly, GridCell, GridPoint } from '../../../shared/game/gri
10
10
  import type { ResidencyAllocator } from '../../../shared/game/grid/allocator';
11
11
  import { GridContinuationCache, GRID_CONTINUATION_CACHE_BYTES } from '../../../shared/game/grid/continuations';
12
12
  import { gridBoardLimitAt } from '../../../shared/game/grid/rules';
13
- import { leadPlayer } from '@wildshard/engine/sim/leadPlayer';
14
13
 
15
14
  /** Admission returns one owned, renderer-free regional host; its world is always in authored local coordinates. */
16
15
  export interface GridResident { readonly host: SimHost; readonly dispose: () => void }
@@ -18,6 +17,8 @@ export interface GridResident { readonly host: SimHost; readonly dispose: () =>
18
17
  export interface GridSimLease { release: () => void; update?: (state: { needed?: boolean; distance?: number }) => void }
19
18
  /** Durable snapshots and native/browser admission are injected; no network operation runs during a fixed tick. */
20
19
  export interface GridSimulationPorts {
20
+ /** The session's owning seat; older standalone callers use actor.player. */
21
+ readonly owner?: string;
21
22
  readonly highway: GridResident;
22
23
  load: (cell: GridCell, saved: SimSnapshot | undefined) => Promise<GridResident>;
23
24
  save?: (instance: string, snapshot: SimSnapshot) => boolean;
@@ -83,7 +84,7 @@ export function carryMotion(from: PlayerSim, to: PlayerSim): void {
83
84
 
84
85
  /**
85
86
  * Independent local physics worlds; only a world with a player in it advances, while visible neighbours remain frozen.
86
- * Each player crosses on their own (P1-E3.9). `owner` is the player this session was built around, the lead of every host:
87
+ * Each player crosses on their own (P1-E3.9). `owner` is the explicit seat this session was built around:
87
88
  * its systems bind to that seat, so when it leaves others behind the seat stays, parked, and a lone player never parks.
88
89
  */
89
90
  export class GridSimulation {
@@ -105,8 +106,8 @@ export class GridSimulation {
105
106
  constructor(assembly: GridAssembly, ports: GridSimulationPorts) {
106
107
  this.assembly = assembly; this.ports = ports;
107
108
  this.limit = ports.maxResidents ?? 4;
108
- const owner = leadPlayer(ports.highway.host);
109
- if (!Number.isInteger(this.limit) || this.limit < 1 || this.limit > 9 || ports.highway.host.embedded || !owner.hasMotor) throw new RangeError('Invalid grid simulation owner');
109
+ const owner = ports.highway.host.players.get(ports.owner ?? 'actor.player');
110
+ if (!Number.isInteger(this.limit) || this.limit < 1 || this.limit > 9 || ports.highway.host.embedded || owner === undefined || !owner.hasMotor) throw new RangeError('Invalid grid simulation owner');
110
111
  this.owner = owner.id; this.sites.set(owner.id, null);
111
112
  if (ports.reserve !== undefined && ports.residentBytes === undefined) throw new Error('Sim reservation needs admitted resident bytes');
112
113
  if (ports.allocator !== undefined && (ports.residentBytes === undefined || ports.reserve !== undefined)) throw new Error('Use one sim reservation owner with admitted bytes');
@@ -24,7 +24,6 @@ import { MoverMechanic, type NativeMoverMotion } from '@wildshard/engine/sim/mov
24
24
  import { parseMovers, type MoverData } from "@wildshard/format/movers";
25
25
  import { carryPrompt } from "../../../shared/game/shardfile/wirePrompts";
26
26
  import { actRoutes } from "@wildshard/engine/sim/actRoutes";
27
- import { leadPlayer } from '@wildshard/engine/sim/leadPlayer';
28
27
  import { questBooks } from '@wildshard/engine/quest/players';
29
28
  import { publishScriptBody } from '@wildshard/engine/sim/shardRows';
30
29
 
@@ -208,6 +207,8 @@ export class MoverRuntime {
208
207
  private readonly carryPoses = new Map<string, CarryPose>();
209
208
  /** Who rides each carry mover, when it is not the lead (P1-E3.10). A lone player's save never holds one. */
210
209
  private readonly riders = new Map<string, string>();
210
+ /** Owner of legacy unnamed carry commands, selected when the native host installs. */
211
+ private nativeOwner = 'actor.player';
211
212
  private readonly previousRides = new Map<string, boolean>();
212
213
  private readonly flags: Pick<Flags, 'has' | 'set'> | undefined;
213
214
  private readonly riderFlags: MoverPorts['riderFlags'];
@@ -279,10 +280,11 @@ export class MoverRuntime {
279
280
  }
280
281
  /** Queue a host-validated interact command; scene dispatch resolves the stable mover id, never an arbitrary function export. */
281
282
  command(id: string, action: 1 | 2 | 3, player?: string): void {
283
+ const rider = player === this.nativeOwner ? undefined : player;
282
284
  const row = this.data.find(m => m.id === id); if (row === undefined) throw new Error('Unknown mover');
283
285
  if (row.carry !== undefined) {
284
- if (this.riding(id) || this.carrying(player) || action === 3) return;
285
- if (player === undefined) this.riders.delete(id); else this.riders.set(id, player);
286
+ if (this.riding(id) || this.carrying(rider) || action === 3) return;
287
+ if (rider === undefined) this.riders.delete(id); else this.riders.set(id, rider);
286
288
  }
287
289
  this.pending.set(id, action);
288
290
  }
@@ -292,8 +294,8 @@ export class MoverRuntime {
292
294
  if (id !== undefined && rows.length === 0) throw new Error('Unknown mover');
293
295
  return rows.some(row => row.carry !== undefined && (this.pending.has(row.id) || [1, 0.5].includes(this.host.world.entity(row.entity)?.fields[6] ?? 0)));
294
296
  }
295
- /** Whether `player` (the lead when absent) is on a carry mover: each carries the one who called it. */
296
- carrying(player?: string): boolean { return this.data.some(row => row.carry !== undefined && this.riders.get(row.id) === player && this.riding(row.id)); }
297
+ /** Whether `player` (the configured owner when absent) is on a carry mover. */
298
+ carrying(player?: string): boolean { const rider = player === this.nativeOwner ? undefined : player; return this.data.some(row => row.carry !== undefined && this.riders.get(row.id) === rider && this.riding(row.id)); }
297
299
  /** View-only edges, including first arrival hints, never an authored update hook. */
298
300
  takeRideTransitions(id: string): readonly MoverRideTransition[] { return this.rideEvents.get(id)?.splice(0) ?? []; }
299
301
  /** Borrow the same declared prompts on the page; the native command names are the stable mover ids. */
@@ -324,7 +326,7 @@ export class MoverRuntime {
324
326
  }
325
327
  private carryNative(host: SimHost): void {
326
328
  for (const [id, carry] of this.carryPoses) {
327
- const named = this.riders.get(id), rider = named === undefined ? leadPlayer(host) : host.players.get(named);
329
+ const named = this.riders.get(id), rider = host.players.get(named ?? this.nativeOwner);
328
330
  if (!carry.riding) this.riders.delete(id);
329
331
  if (rider === undefined) continue; // left the world mid-ride: the boat goes on without them
330
332
  rider.position.set(...carry.at); rider.motor.resetAt(rider.position); rider.velocity.y = 0; rider.fall.grounded = false; if (!carry.riding) rider.yaw = carry.yaw;
@@ -332,23 +334,24 @@ export class MoverRuntime {
332
334
  this.carryPoses.clear();
333
335
  }
334
336
  /** Protect ordinary walking while the existing fixed mover lane publishes carry. */
335
- bindNativeCarry(host: SimHost): void {
337
+ bindNativeCarry(host: SimHost, owner = 'actor.player'): void {
336
338
  if (!this.data.some(row => row.carry !== undefined)) return;
339
+ if (!host.players.has(owner)) throw new RangeError('Unknown native carry owner');
340
+ this.nativeOwner = owner;
337
341
  host.events.answer('player.carrying', carried => carried || this.carrying(), host.scope);
338
- const lead = leadPlayer(host);
339
- host.leading.push(body => this.carrying(body === lead ? undefined : body.id)); // a client's capsule stays out of a boat's way
342
+ host.leading.push(body => this.carrying(body.id === owner ? undefined : body.id)); // a client's capsule stays out of a boat's way
340
343
  const routes = actRoutes(host);
341
344
  for (const row of this.data) row.carry?.prompts.forEach(({ at: [x, y, z], radius }, end) => {
342
345
  routes.claims.set(carryPrompt(row.id, end), player => {
343
346
  const body = host.players.get(player)?.position;
344
- if (body !== undefined && Math.hypot(body.x - x, body.y - y, body.z - z) <= radius + CARRY_REACH) this.command(row.id, end === 0 ? 1 : 2, player === lead.id ? undefined : player);
347
+ if (body !== undefined && Math.hypot(body.x - x, body.y - y, body.z - z) <= radius + CARRY_REACH) this.command(row.id, end === 0 ? 1 : 2, player === owner ? undefined : player);
345
348
  else routes.refused++;
346
349
  });
347
350
  });
348
351
  host.events.answer('player.traversal', dt => {
349
352
  const player = host.traversing;
350
353
  if (typeof dt !== 'number') return dt;
351
- if (player === null || player === lead) return this.carrying();
354
+ if (player === null || player.id === owner) return this.carrying();
352
355
  return this.carrying(player.id) ? true : dt;
353
356
  }, host.scope);
354
357
  host.onStep('movers.carry', () => { this.carryNative(host); }, undefined, 'afterBodies');
@@ -537,7 +540,7 @@ export class MoverScriptDriver {
537
540
  schedules: [this.schedule(() => { if (this.runtime === undefined) throw new Error('Missing mover runtime'); return this.runtime; }, permissions), ...(extra?.schedules ?? [])] });
538
541
  }
539
542
  /** Attach native handles to the same host; an explicit drive owns one fixed tick, never another script host. */
540
- install(sim: SimHost, input: ReturnType<typeof createShardfileComposedLane> | DeclaredMoverComposition, options: { id: string; restoring?: boolean; restoreFlags?: ReadonlySet<string>; activation?: MoverActivationPorts; drive?: boolean; permissions?: () => ReadonlyMap<string, number>; joined?: boolean }): MoverRuntime {
543
+ install(sim: SimHost, input: ReturnType<typeof createShardfileComposedLane> | DeclaredMoverComposition, options: { id: string; owner?: string; restoring?: boolean; restoreFlags?: ReadonlySet<string>; activation?: MoverActivationPorts; drive?: boolean; permissions?: () => ReadonlyMap<string, number>; joined?: boolean }): MoverRuntime {
541
544
  if (this.runtime !== undefined) throw new Error('Mover driver is already installed');
542
545
  const lane = 'host' in input ? input : this.compose({ ...input.content, sim: { ...input.content.sim, scripts: [...input.assets.keys()] } }, input.assets,
543
546
  { rules: input.rules, entities: [], actors: new Map(), query: () => [] }, undefined, options.permissions,
@@ -548,13 +551,14 @@ export class MoverScriptDriver {
548
551
  const riderFlags = arrivals.length === 0 ? undefined : (rider: string | undefined): Flags | undefined => {
549
552
  if (sim.players.size === 0) return sim.flags;
550
553
  const books = questBooks(sim); books.claim(arrivals);
551
- return rider === undefined ? books.lead.flags : sim.players.has(rider) ? books.of(rider).flags : undefined;
554
+ const player = rider ?? options.owner ?? 'actor.player';
555
+ return sim.players.has(player) ? books.of(player).flags : undefined;
552
556
  };
553
557
  const runtime = new MoverRuntime(this.data, { lane, flags: sim.flags, ...(riderFlags === undefined ? {} : { riderFlags }), host: lane.host, physics: () => sim.physics, scope: sim.scope,
554
558
  ...(options.restoring === undefined ? {} : { restoring: options.restoring }),
555
559
  ...(options.restoreFlags === undefined ? {} : { restoreFlags: options.restoreFlags }),
556
560
  activation: { ground: () => playerGrounds(sim), ...options.activation } });
557
- this.runtime = runtime; runtime.bindNativeCarry(sim);
561
+ this.runtime = runtime; runtime.bindNativeCarry(sim, options.owner);
558
562
  for (const row of this.data) publishScriptBody(sim, row.id, () => runtime.pose(row.id));
559
563
  // `joined`: a save from before these movers had their step holds none of it, so its world has no bodies to reconnect: build them
560
564
  let continued = false;
@@ -19,7 +19,7 @@ import type { AimCommand } from '@wildshard/engine/input/commands';
19
19
  import type { SimHost, SimValue } from '@wildshard/engine/sim';
20
20
  import type { PlayerSim } from '@wildshard/engine/sim/playerSim';
21
21
  import { publishOwned } from '@wildshard/engine/sim/shardRows';
22
- import { declaredKitSlots, LEVER_FAMILY, leverLines, leverProfile, SERVER_KIT_FAMILIES, type LeverProfile } from '../../../shared/game/shardfile/items';
22
+ import { declaredKitSlots, LEVER_FAMILY, leverLines, leverProfile, rackMeleeRows, SERVER_KIT_FAMILIES, takenLine, type LeverProfile } from '../../../shared/game/shardfile/items';
23
23
  import { playerSeats, type PlayerSeat } from '../plugin/playerSeats';
24
24
  import { nativeRangedHit } from '../plugin/nativeItems';
25
25
  import { installStatusEffects } from './statusEffects';
@@ -45,7 +45,9 @@ export interface DeclaredKitItems {
45
45
  type Cycle = InstanceType<typeof RangedAction.Cycle>;
46
46
  /** One player's lever: the cycle and its reserve, whether they have taken it, and the time since a dry pull (its auto-reload window). */
47
47
  interface LeverSeat { readonly act: Cycle; readonly store: { reserve: number }; taken: boolean; sinceEmpty: number }
48
- interface KitSeat extends PlayerSeat { readonly runtimes: ReadonlyMap<string, ItemRuntime>; readonly levers: ReadonlyMap<string, LeverSeat> }
48
+ interface KitSeat extends PlayerSeat { readonly runtimes: ReadonlyMap<string, ItemRuntime>; readonly levers: ReadonlyMap<string, LeverSeat>; readonly racked: Set<string> }
49
+ /** The continuation key of a player's rack weapons still on their racks (TC-E4): no item id starts with '#'. */
50
+ const RACKED = '#racked';
49
51
  type LeverRow = Extract<Shardfile['items']['rows'][number], { kind: 'weapon' }>;
50
52
  const finiteNumber = v.pipe(v.number(), v.finite()), count = v.pipe(finiteNumber, v.integer(), v.minValue(0));
51
53
  const LeverSaved = v.strictObject({ tube: count, chambered: v.boolean(), caseInChamber: v.boolean(), hammerCocked: v.boolean(),
@@ -64,6 +66,8 @@ function restoreLever(seat: LeverSeat, value: unknown): void {
64
66
  seat.store.reserve = s.reserve; seat.sinceEmpty = s.sinceEmpty; seat.taken = s.taken;
65
67
  }
66
68
 
69
+ /** The most rounds a lever's reserve holds from its rack's restocks (TC-E1d). */
70
+ export const RESTOCK_CAP = 999;
67
71
  const finite = (aim: AimCommand): boolean => [aim.origin.x, aim.origin.y, aim.origin.z, aim.direction.x, aim.direction.y, aim.direction.z].every(Number.isFinite);
68
72
  function isStates(value: unknown): value is Record<string, ItemState> { return typeof value === 'object' && value !== null && !Array.isArray(value); }
69
73
 
@@ -79,9 +83,14 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
79
83
  const prompts = new Map<string, { readonly at: readonly [number, number, number]; readonly radius: number }[]>();
80
84
  for (const row of shard.targets.interactions) prompts.set(row.scene, [...(prompts.get(row.scene) ?? []), row]);
81
85
  // A rack's prompt names its lever's scene: the page sends the prompt's own id, and this kit runs it, not a script (a shard may have none).
82
- const leverPrompts = new Map(shard.targets.interactions.flatMap(row => (shard.targets.itemActions ?? []).some(action => action.scene === row.scene && levers.has(action.item)) ? [[row.id, row.scene] as const] : []));
83
86
  const slots = declaredKitSlots(shard.items.rows), weapons = [...slots.keys()];
87
+ // TEMPLATE-E2E TC-E1c: the loadout's primary lever is in hand from the start; any other waits for its rack
88
+ const primary = shard.items.loadout.primary;
84
89
  const scenes = new Map((shard.targets.itemActions ?? []).filter(row => rows.some(item => item.id === row.item)).map(row => [row.scene, row] as const));
90
+ // TEMPLATE-E2E TC-E4 (J361: Mossgate's sword is found on a rack): a melee weapon a rack takes starts on that rack, per player
91
+ const rackMelee = rackMeleeRows(shard);
92
+ // A rack's prompt arrives by its own id (the page's wire id): a lever's or a racked melee weapon's names its scene
93
+ const leverPrompts = new Map(shard.targets.interactions.flatMap(row => (shard.targets.itemActions ?? []).some(action => action.scene === row.scene && (levers.has(action.item) || rackMelee.has(action.item))) ? [[row.id, row.scene] as const] : []));
85
94
  const fields = (shard.targets.itemFields ?? []).flatMap(row => {
86
95
  const field = shard.state.player.find(entry => entry.id === row.fieldId);
87
96
  return field === undefined || field.privacy === 'host' ? [] : [{ item: row.item, name: field.name, property: row.property }];
@@ -105,10 +114,11 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
105
114
  })] as const));
106
115
  const seated = new Map([...levers].map(([id, { profile }]) => {
107
116
  const store = { reserve: profile.reserve };
108
- const seat: LeverSeat = { act: new RangedAction.Cycle(store, { magazine: profile.magazine, reload: profile.reload, ...profile.lever }), store, taken: false, sinceEmpty: 99 };
117
+ const seat: LeverSeat = { act: new RangedAction.Cycle(store, { magazine: profile.magazine, reload: profile.reload, ...profile.lever }), store, taken: id === primary, sinceEmpty: 99 };
109
118
  return [id, seat] as const;
110
119
  }));
111
- return { runtimes, levers: seated,
120
+ const racked = new Set(rackMelee);
121
+ return { runtimes, levers: seated, racked,
112
122
  step: dt => {
113
123
  for (const runtime of runtimes.values()) runtime.step(host.state.tick, dt);
114
124
  const holding = weapons[player.held];
@@ -120,14 +130,18 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
120
130
  for (const _event of seat.act.events(dt, due)) { /* The seat has no presentation: the page plays its own cycle. */ }
121
131
  }
122
132
  },
123
- snapshot: (): SimValue => ({ ...Object.fromEntries([...runtimes].map(([id, runtime]) => [id, runtime.snapshot()])), ...Object.fromEntries([...seated].map(([id, seat]) => [id, leverSnapshot(seat)])) }) as unknown as SimValue,
133
+ snapshot: (): SimValue => ({ ...Object.fromEntries([...runtimes].map(([id, runtime]) => [id, runtime.snapshot()])), ...Object.fromEntries([...seated].map(([id, seat]) => [id, leverSnapshot(seat)])),
134
+ ...(rackMelee.size === 0 ? {} : { [RACKED]: [...racked].sort() }) }),
124
135
  restore: value => {
125
136
  if (!isStates(value)) throw new Error('Invalid declared kit item continuation');
126
137
  // A player's document can come from an older room (E7.4): its tick is that room's. The runtime's tick only orders steps,
127
138
  // so it never stands ahead of this host's.
128
139
  for (const [id, runtime] of runtimes) { const saved = value[id]; if (saved !== undefined) runtime.restore({ ...saved, tick: Math.max(-1, Math.min(saved.tick, host.state.tick - 1)) }); }
129
140
  // A save made before a lever existed leaves it fresh.
130
- for (const [id, seat] of seated) { const saved: unknown = value[id]; if (saved !== undefined) restoreLever(seat, saved); }
141
+ for (const [id, seat] of seated) { const saved: unknown = value[id]; if (saved !== undefined) restoreLever(seat, saved); if (id === primary) seat.taken = true; }
142
+ // A save from before TC-E4 has no rack list: its weapons stay on their racks, as a fresh player's do.
143
+ const saved: unknown = value[RACKED];
144
+ if (Array.isArray(saved)) { racked.clear(); for (const id of saved) if (typeof id === 'string' && rackMelee.has(id)) racked.add(id); }
131
145
  } };
132
146
  });
133
147
  // Joined: a save made before this owner existed restores, and its items start fresh.
@@ -142,6 +156,11 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
142
156
  out.set(field.name, field.property === 'fuel' ? Math.round(runtime.remainingFuel * FUEL_STEPS) / FUEL_STEPS : Number(runtime.lightOn));
143
157
  }
144
158
  });
159
+ if (rackMelee.size > 0) publishOwned(host, 'items.declared-rack', (id, out) => {
160
+ const player = host.players.get(id); if (player === undefined) return;
161
+ const { racked } = seats.of(player);
162
+ for (const item of rackMelee) out.set(takenLine(item), Number(!racked.has(item)));
163
+ });
145
164
  if (levers.size > 0) publishOwned(host, 'items.declared-lever', (id, out) => {
146
165
  const player = host.players.get(id); if (player === undefined) return;
147
166
  for (const [item, seat] of seats.of(player).levers) {
@@ -150,7 +169,7 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
150
169
  out.set(lines.reloading, Number(seat.act.phase === 'reload')); out.set(lines.taken, Number(seat.taken));
151
170
  }
152
171
  });
153
- const held = (player: PlayerSim): ItemRuntime | undefined => { const id = weapons[player.held]; return id === undefined ? undefined : seats.of(player).runtimes.get(id); };
172
+ const held = (player: PlayerSim): ItemRuntime | undefined => { const id = weapons[player.held], seat = seats.of(player); return id === undefined || seat.racked.has(id) ? undefined : seat.runtimes.get(id); };
154
173
  const heldLever = (player: PlayerSim): { readonly seat: LeverSeat; readonly row: LeverRow; readonly profile: LeverProfile } | undefined => {
155
174
  const id = weapons[player.held], lever = id === undefined ? undefined : levers.get(id), seat = id === undefined ? undefined : seats.of(player).levers.get(id);
156
175
  return lever === undefined || seat === undefined ? undefined : { seat, row: lever.row, profile: lever.profile };
@@ -211,7 +230,7 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
211
230
  const player = host.players.get(id), want = weapons[slot];
212
231
  if (player === undefined || want === undefined) return false;
213
232
  // A lever still on its rack is no swap: the act is spent, and the hand stays where it is.
214
- if (seats.of(player).levers.get(want)?.taken === false) return true;
233
+ if (seats.of(player).levers.get(want)?.taken === false || seats.of(player).racked.has(want)) return true;
215
234
  const before = held(player), aim = eye(player, 0);
216
235
  if (before !== undefined) safely(() => { before.hold(false, aim, false); }); // a swap lets go of a charge without striking
217
236
  player.held = slot; return true;
@@ -223,12 +242,23 @@ export function installDeclaredKitItems(host: SimHost, shard: Pick<Shardfile, 'i
223
242
  if (!near(taker, scene)) return true;
224
243
  // 3 takes the lever off its rack and into hand; 4 reloads it.
225
244
  if (row.action === 3) {
245
+ // TC-E1d: a rack is a restock once its lever is in hand: its row's reserve again, up to the cap
246
+ if (lever.taken) { const profile = levers.get(row.item)?.profile; if (profile !== undefined) lever.store.reserve = Math.min(RESTOCK_CAP, lever.store.reserve + profile.reserve); return true; }
226
247
  const slot = weapons.indexOf(row.item), before = held(taker);
227
248
  if (before !== undefined) safely(() => { before.hold(false, eye(taker, 0), false); });
228
249
  lever.taken = true; if (slot !== -1) taker.held = slot;
229
250
  } else if (lever.taken) lever.act.beginReload();
230
251
  return true;
231
252
  }
253
+ // TC-E4: 3 takes a racked melee weapon into hand; once taken, its rack is spent
254
+ if (taker !== undefined && row.action === 3 && rackMelee.has(row.item)) {
255
+ const own = seats.of(taker).racked;
256
+ if (!own.has(row.item) || !near(taker, scene)) return true;
257
+ const slot = weapons.indexOf(row.item), before = held(taker);
258
+ if (before !== undefined) safely(() => { before.hold(false, eye(taker, 0), false); });
259
+ own.delete(row.item); if (slot !== -1) taker.held = slot;
260
+ return true;
261
+ }
232
262
  const player = taker, runtime = player === undefined ? undefined : seats.of(player).runtimes.get(row.item);
233
263
  if (runtime !== undefined) safely(() => { runtime.queue(row.action); });
234
264
  return true;
@@ -24,7 +24,6 @@ import { headlessSections } from '../../../shared/host/headlessSections';
24
24
  import { scriptAdmissionRows } from '@wildshard/format/scriptContract';
25
25
  import { validateShardfileAssets } from '@wildshard/format/assetAdmission';
26
26
  import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/shardfileAssets';
27
- import { leadCommands, leadPlayer } from '@wildshard/engine/sim/leadPlayer';
28
27
 
29
28
  await runTickWorker(async raw => {
30
29
  const payload = v.parse(v.strictObject({ shard: v.unknown(), assets: v.map(v.string(), v.instance(Uint8Array)), binary: v.string(), snapshot: v.optional(v.string()), sections: v.exactOptional(v.map(v.string(), v.unknown())), product: v.exactOptional(v.string()) }), raw);
@@ -85,8 +84,9 @@ await runTickWorker(async raw => {
85
84
  if (!sim.actors.has(command.actorId)) throw new Error('Unknown command actor'); numeric.set(command.actorId, command.value);
86
85
  } else { if (sim.lane === undefined) throw new Error('Event requires a script lane'); sim.lane.enqueue({ type: command.type, target: command.target, value: command.value }); }
87
86
  }
88
- commands = numeric; sim.host.step(leadCommands(sim.host, player));
89
- if (![leadPlayer(sim.host).position, ...[...sim.host.entities.values()].map(entity => entity.position)].every(point => [point.x, point.y, point.z].every(Number.isFinite))) throw new Error('Nonfinite headless simulation state');
87
+ commands = numeric; sim.host.step(player === undefined ? undefined : new Map([['actor.player', player]]));
88
+ for (const body of sim.host.players.values()) if (!Number.isFinite(body.position.x) || !Number.isFinite(body.position.y) || !Number.isFinite(body.position.z)) throw new Error('Nonfinite headless simulation state');
89
+ for (const body of sim.host.entities.values()) if (!Number.isFinite(body.position.x) || !Number.isFinite(body.position.y) || !Number.isFinite(body.position.z)) throw new Error('Nonfinite headless simulation state');
90
90
  const script=sim.lane?.host.checkpoint();
91
91
  if(script?.modules.some(module=>module.failures>0||module.disabled))throw new Error('Headless script call failed');
92
92
  if(sim.decisions?.host.metrics().some(row=>row.refusals>0||row.disabled))throw new Error('Headless decision call failed');
@@ -66,7 +66,7 @@ export interface CellHostOptions {
66
66
  /** QA 11-15 row 8 (G540): honour a Developer page's boost bit (on unless `WORLD_BOOST=off`, `cellWorker.ts`). */
67
67
  readonly developerBoost?: boolean;
68
68
  /**
69
- * GC15 (`WORLD_CROSSING=worker`): the grid pack's road strips. Given, this worker hosts the road between its cells, each of its grid
69
+ * J353: the grid pack's road strips. Given, this worker hosts the road between its cells, each of its grid
70
70
  * cells opens onto it instead of standing in lone walls, and a seat walks cell, road, cell on one socket. Left out, or no strips, every cell is lone.
71
71
  */
72
72
  readonly road?: () => Promise<readonly GridCollisionStrip[]>;
@@ -296,7 +296,7 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
296
296
  return;
297
297
  }
298
298
  if (!ready) { fail(new Error('A worker was told something before it booted')); return; }
299
- if (order.kind === 'drain') { drained = true; clock?.pause(); for (const { room } of cells.values()) room.drain(); road?.drain(); post({ kind: 'drained' }); return; }
299
+ if (order.kind === 'drain') { drained = true; clock?.pause(); for (const { room } of cells.values()) room.drain(order.leave); road?.drain(); post({ kind: 'drained' }); return; }
300
300
  if (order.kind === 'cross') { cross(order).catch(fail); return; }
301
301
  // GC15 (3): crossings between workers, and which cells on the others a walker can stand in
302
302
  if (order.kind === 'open') { road?.open(order.cells); return; }
@@ -27,7 +27,7 @@ export interface SeatEntry {
27
27
  export type CellOrder =
28
28
  | { readonly kind: 'find'; readonly id: number; readonly slug: string; readonly device: string }
29
29
  | ({ readonly kind: 'seat'; readonly slug: string; readonly port: MessagePort; readonly hello: ArrayBuffer } & SeatEntry)
30
- | { readonly kind: 'drain' }
30
+ | { readonly kind: 'drain'; readonly leave?: boolean }
31
31
  /** MP4.1: a `room` line said in cell `from`, for every other awake cell on this worker. */
32
32
  | { readonly kind: 'chat'; readonly from: string; readonly line: WorldLine }
33
33
  /** GC15: a seat in cell `from` walks into `to` on the same worker. The entry is the door's read of their save on `to`'s shard. */
@@ -12,19 +12,21 @@ import { readPackGrid, readPackProduct, type PackReads } from './packReader';
12
12
  import { runCells, type CellPort } from './cellHost';
13
13
  import { placeCell, placedHash, type PlacedCell } from './gridCells';
14
14
  import { loopLag } from './loopLag';
15
+ import type { LedgerCatalogueItem } from '@wildshard/engine/game/ledger';
15
16
 
16
17
  /** What the door boots a worker with. */
17
18
  export interface CellWorkerData { readonly slugs: readonly string[]; readonly build: string; readonly origin: string; readonly cache: string; readonly holdMs?: number;readonly playtest?:boolean;
19
+ readonly catalogue?: readonly LedgerCatalogueItem[];
18
20
  /** J107's start-over wait, a proof's override (`EMPTY_MS`): 5 minutes when absent. */
19
21
  readonly emptyMs?: number;
20
- /** GC15: `WORLD_CROSSING=worker`, this worker hosts the road between its cells. */
22
+ /** Every worker hosts its road; J353 removed the mode switch. */
21
23
  readonly crossing?: boolean;
22
24
  /** SA33: the cells the door had placed when it booted this worker; a worker's module state is its own. */
23
25
  readonly placed?: readonly PlacedCell[];
24
26
  /** SERVER-CELLS SC1: `METRICS_PORT` is set, so this worker measures its event-loop lag for `/metrics`. */
25
27
  readonly metrics?: boolean }
26
28
 
27
- const { slugs, build, origin, cache, holdMs, emptyMs, playtest, crossing, placed, metrics } = workerData as CellWorkerData, port = parentPort;
29
+ const { slugs, build, origin, cache, holdMs, emptyMs, playtest, crossing, placed, metrics, catalogue } = workerData as CellWorkerData, port = parentPort;
28
30
  if (port === null) throw new Error('A cell runs in a worker');
29
31
  for (const row of placed ?? []) placeCell(row);
30
32
  const reads: PackReads = { fetched: 0, fetchedBytes: 0, cached: 0, refused: 0 };
@@ -36,7 +38,7 @@ runCells(port as unknown as CellPort, { slugs, build, developerBoost: process.en
36
38
  return strips;
37
39
  } } : {}),
38
40
  load: async slug => {
39
- const input = await readPackProduct(slug, build, rapier, { origin, cache }, reads, placedHash(slug));
41
+ const input = await readPackProduct(slug, build, rapier, { origin, cache }, reads, placedHash(slug), catalogue);
40
42
  console.info(JSON.stringify({ at: 'cell.pack', slug, ...reads }));
41
43
  return input;
42
44
  } });
@@ -75,7 +75,7 @@ export interface DedicatedRoomOptions {
75
75
  /** GO3: the grid instance this room is, which names it everywhere else and numbers its frames. Left out, the shard's own grid cell. */
76
76
  readonly cell?: string;
77
77
  /**
78
- * GC15 (`WORLD_CROSSING=worker`): this worker's road, which the cell opens onto instead of standing lone. Its seam
78
+ * J353: this worker's road, which the cell opens onto. Its seam
79
79
  * strips are built into the cell's world, and a seat whose feet leave the cell asks the door to cross onto the road.
80
80
  */
81
81
  readonly road?: DedicatedRoomRoad;
@@ -465,8 +465,13 @@ export class DedicatedRoom implements CrossTarget {
465
465
  for (const [body, left] of this.departed) if (now - left >= FORGET_PAID_MS) { this.departed.delete(body); this.forgetPaid(body); }
466
466
  }
467
467
  /** Everyone goes, as at SIGTERM: their last checkpoint now, and a close that says a restart is why. */
468
- drain(): void {
469
- for (const seat of this.seats.values()) { this.write(seat, 'restart'); seat.holdEnds = null; const { transport } = seat; seat.transport = null; transport?.close('restart'); }
468
+ drain(leave = false): void {
469
+ for (const seat of this.seats.values()) {
470
+ this.write(seat, 'restart'); seat.holdEnds = null;
471
+ const { transport } = seat; seat.transport = null;
472
+ if (leave) this.release(seat);
473
+ transport?.close('restart');
474
+ }
470
475
  }
471
476
  dispose(): void { this.net.dispose(); this.cell.dispose(); }
472
477
  }
@@ -16,7 +16,9 @@ interface GridNames { readonly instances: readonly string[]; readonly frames: Re
16
16
  readonly spots: ReadonlyMap<string, string> }
17
17
  /** SA33: one cell a signed placement file names: the API's placement of a new slug (SA30), on a spot the catalogue leaves empty. SA47:
18
18
  * `hash` is its shardfile, for a pack the build's book lacks. */
19
- export interface PlacedCell { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number]; readonly hash?: string }
19
+ export interface PlacedCell { readonly instance: string; readonly slug: string; readonly cell: readonly [number, number]; readonly hash?: string;
20
+ /** The grid row's speed class, so the board's cap in a placed road-class cell matches the page's (QA 11-15 row 8). */
21
+ readonly speedClass?: 'road' }
20
22
  /** SA33: the cells placed on this running server, in the placement file's order, after the catalogue's. A restart forgets them; the
21
23
  * placement watch's first look places them again. */
22
24
  const placed: PlacedCell[] = [];
@@ -51,7 +53,7 @@ export function placeCell(row: PlacedCell): boolean {
51
53
  if (cells.has(row.instance)) throw new Error(`${row.instance} is a placed shard's name`);
52
54
  const taken = spots.get(spot);
53
55
  if (taken !== undefined) throw new Error(`${spot} is ${taken}'s`);
54
- placed.push({ instance: row.instance, slug: row.slug, cell: [x, z], ...(row.hash === undefined ? {} : { hash: row.hash }) });
56
+ placed.push({ instance: row.instance, slug: row.slug, cell: [x, z], ...(row.hash === undefined ? {} : { hash: row.hash }), ...(row.speedClass === undefined ? {} : { speedClass: row.speedClass }) });
55
57
  if (row.hash !== undefined) hashes.set(row.slug, row.hash);
56
58
  return true;
57
59
  }
@@ -65,7 +67,7 @@ let assembled: { readonly from: unknown; readonly placed: number; readonly assem
65
67
  export function gridAssembly(placedToo = true): GridAssembly {
66
68
  const { grid } = catalogueDocument(), count = placedToo ? placed.length : 0;
67
69
  if (assembled?.from === grid && assembled.placed === count) return assembled.assembly;
68
- const assembly = new GridAssembly({ developer: false, devserver: false }, count === 0 ? grid : { ...grid, cells: [...grid.cells, ...placed.map(({ instance, slug, cell }) => ({ instance, slug, cell: [...cell] }))] });
70
+ const assembly = new GridAssembly({ developer: false, devserver: false }, count === 0 ? grid : { ...grid, cells: [...grid.cells, ...placed.map(({ instance, slug, cell, speedClass }) => ({ instance, slug, cell: [...cell], ...(speedClass === undefined ? {} : { speedClass }) }))] });
69
71
  assembled = { from: grid, placed: count, assembly };
70
72
  return assembly;
71
73
  }
@@ -14,7 +14,7 @@ import { Worker } from 'node:worker_threads';
14
14
  import { loadRapier } from '@wildshard/engine/physics/rapier';
15
15
  import type { WorkerNews } from './cellProtocol';
16
16
  import type { CellWorkerData } from './cellWorker';
17
- import { readPackProduct, type PackReads } from './packReader';
17
+ import { readPackProduct, readReleaseItems, type PackReads } from './packReader';
18
18
  import { openPlayerSaves, memoryPlayerSaves } from './playerSaves';
19
19
  import type { ReleaseFile } from '../../../shared/host/releaseRows';
20
20
  import { fetchReleaseFile, servingRelease, ReleaseWatch } from './releaseFile';
@@ -25,7 +25,7 @@ import { sendSentryTest, serverSentry } from './serverSentry';
25
25
  import {PlaytestFile} from './playtest';
26
26
  import { World, type PlayerSaves, type WorkerLink } from './world';
27
27
  import { cloudflareTurn } from './voiceRelay';
28
- import { worldCrossing, worldSettings } from './workerTable';
28
+ import { worldSettings } from './workerTable';
29
29
  import { doorTrust } from './doorTrust';
30
30
  import { WHOLE_GRID, cellShard, placeCell, placedCells, worldCells } from './gridCells';
31
31
  import { PlacementWatch, fetchPlacementFile } from './placementFile';
@@ -56,6 +56,8 @@ async function installedRelease(): Promise<ReleaseFile> {
56
56
  return selected;
57
57
  }
58
58
  const release = await installedRelease();
59
+ const itemReads: PackReads = { fetched: 0, fetchedBytes: 0, cached: 0, refused: 0 };
60
+ const catalogue = await readReleaseItems(release.items, { origin, cache }, itemReads);
59
61
  // C5, C11, GO3: the cells, by grid instance, fixed at startup; a player with no save lands in the first. `grid` opens every grid cell
60
62
  // the release names, home first. A cell runs its shard's pack, and the release must name that shard.
61
63
  const listed = process.env['WORLD_CELLS'] ?? 'driftwood-isle', cells = worldCells(listed, release.shards.map(shard => shard.slug)), shards = [...new Set(cells.map(cellShard))];
@@ -67,8 +69,10 @@ const reports = new ServerReports({ build, channel: release.channel, telemetryUr
67
69
  const url = process.env['DATABASE_URL'] ?? savesUrl(release.channel), saves: PlayerSaves = url === 'memory:' ? memoryPlayerSaves() : await openPlayerSaves(url, new URL('migrations/', import.meta.url), release.saveEpoch, log, issue => { reports.contract(issue); });
68
70
  const recordTag=setting('RECORD_TAG');
69
71
  const turnKey = setting('WILDSHARD_TURN_KEY_ID'), turnToken = setting('WILDSHARD_TURN_KEY_TOKEN');
70
- // GC15, GC35: each worker opens its road and lets a seat walk between the cells it hosts; only `WORLD_CROSSING=off` keeps cells lone (J322).
71
- const crossing = worldCrossing(setting('WORLD_CROSSING'));
72
+ // J353: zone entry is the only implementation. Old box files may retain this row during rollout.
73
+ const legacyWorldCrossing = setting('WORLD_CROSSING');
74
+ if (legacyWorldCrossing !== undefined) log({ at: 'world.crossing.ignored', value: legacyWorldCrossing, reason: 'zone-entry' });
75
+ const crossing = true;
72
76
  // SA33: where the API's signed placement file is, and its own key's public half. Both or neither; only a whole-grid world grows.
73
77
  const placementAt = setting('PLACEMENT_URL'), placementKey = setting('PLACEMENT_PUBLIC_KEY');
74
78
  if ((placementAt === undefined) !== (placementKey === undefined)) throw new Error('PLACEMENT_URL and PLACEMENT_PUBLIC_KEY go together');
@@ -78,7 +82,7 @@ const playtest=process.env['PLAYTEST']==='1'?new PlaytestFile({directory:setting
78
82
 
79
83
  /** One row of the table is one worker thread, started once (J182). */
80
84
  function bootWorker(slugs: readonly string[]): WorkerLink {
81
- const data: CellWorkerData = { slugs, build, origin, cache, placed: placedCells(), ...(hold === undefined ? {} : { holdMs: Number(hold) }), ...(empty === undefined ? {} : { emptyMs: Number(empty) }), ...(crossing ? { crossing } : {}), ...(metrics === undefined ? {} : { metrics: true }),...(playtest===undefined?{}:{playtest:true}) };
85
+ const data: CellWorkerData = { slugs, build, origin, cache, catalogue, placed: placedCells(), ...(hold === undefined ? {} : { holdMs: Number(hold) }), ...(empty === undefined ? {} : { emptyMs: Number(empty) }), crossing: true, ...(metrics === undefined ? {} : { metrics: true }),...(playtest===undefined?{}:{playtest:true}) };
82
86
  const worker = new Worker(new URL('cellWorker.mjs', import.meta.url), { workerData: data });
83
87
  let stopped = false;
84
88
  return { send: (order, transfer = []) => { worker.postMessage(order, transfer as never); },
@@ -139,7 +143,8 @@ async function pullBundle(script: string): Promise<void> {
139
143
  const watch = new ReleaseWatch({ read: readRelease, serving: release, cells: shards, ...(poll === undefined ? {} : { everyMs: Number(poll) }), failed: error => { log({ at: 'release.failed', error: String(error) }); },
140
144
  changed: async next => {
141
145
  if (pullScript !== undefined) await pullBundle(pullScript);
142
- for (const slug of shards) await readPackProduct(slug, next.engineBuild, await rapier(), { origin, cache }, reads);
146
+ const nextCatalogue = await readReleaseItems(next.items, { origin, cache }, reads);
147
+ for (const slug of shards) await readPackProduct(slug, next.engineBuild, await rapier(), { origin, cache }, reads, undefined, nextCatalogue);
143
148
  world.beginGrace(next.engineBuild);
144
149
  } });
145
150
  // SA33: a cell the API placed opens on this running server within a look, on a worker of its own, with no grace and no restart. Its shard's
@@ -152,7 +157,7 @@ placements = placementAt === undefined || placementKey === undefined || listed.t
152
157
  const ready: string[] = [];
153
158
  for (const row of rows) {
154
159
  // SA34a: the pack first, so the door's placed list (and so every worker's frame numbers) holds only cells it opens.
155
- try { await readPackProduct(row.slug, build, await rapier(), { origin, cache }, reads, row.hash); placeCell(row); ready.push(row.instance); }
160
+ try { await readPackProduct(row.slug, build, await rapier(), { origin, cache }, reads, row.hash, catalogue); placeCell(row); ready.push(row.instance); }
156
161
  catch (error) { log({ at: 'placement.refused', instance: row.instance, slug: row.slug, error: String(error) }); }
157
162
  }
158
163
  return ready.length === 0 ? [] : world.openCells(ready);
@@ -10,6 +10,9 @@ import type { Rapier } from '@wildshard/engine/physics/rapier';
10
10
  import type { HeadlessRuntimeInput } from '../headlessRuntime';
11
11
  import type { GridCollisionStrip } from '@wildshard/engine/game/grid/gridCollision';
12
12
  import { readGridCollisionPack, readServerProduct, type ServerRead } from '../standalone/serverProduct';
13
+ import type { ReleaseFile } from '../../../shared/host/releaseRows';
14
+ import { readPlatformItemCatalogue, type PlatformItemCatalogue } from '@wildshard/engine/game/loot/platformCatalogue';
15
+ import { admitLedgerRewards, type LedgerCatalogueItem } from '@wildshard/engine/game/ledger';
13
16
 
14
17
  /** What a reader counts, so a boot can say where its bytes came from. */
15
18
  export interface PackReads { fetched: number; fetchedBytes: number; cached: number; refused: number }
@@ -63,6 +66,16 @@ export function readPackGrid(build: string, options: PackReaderOptions, reads: P
63
66
  return readGridCollisionPack(new URL('shards/', options.origin.endsWith('/') ? options.origin : `${options.origin}/`).href, build, packRead(options, reads));
64
67
  }
65
68
  /** One shard's server inputs, through its build's book, or for a placed slug the book lacks, the cook's index of `hash` (SA47). */
66
- export function readPackProduct(slug: string, build: string, rapier: Rapier, options: PackReaderOptions, reads: PackReads, hash?: string): Promise<HeadlessRuntimeInput> {
67
- return readServerProduct(new URL(`shards/${slug}/`, options.origin.endsWith('/') ? options.origin : `${options.origin}/`).href, () => build, packRead(options, reads), rapier, undefined, hash);
69
+ export async function readPackProduct(slug: string, build: string, rapier: Rapier, options: PackReaderOptions, reads: PackReads, hash?: string, catalogue: readonly LedgerCatalogueItem[] = []): Promise<HeadlessRuntimeInput> {
70
+ const input = await readServerProduct(new URL(`shards/${slug}/`, options.origin.endsWith('/') ? options.origin : `${options.origin}/`).href, () => build, packRead(options, reads), rapier, undefined, hash);
71
+ admitLedgerRewards(input.shard.ledger, catalogue);
72
+ return { ...input, catalogue };
73
+ }
74
+ /** Q37: the signed release selects these bytes; an old release has no catalogue grants. */
75
+ export async function readReleaseItems(reference: ReleaseFile['items'], options: PackReaderOptions, reads: PackReads): Promise<PlatformItemCatalogue['items']> {
76
+ if (reference === undefined) return [];
77
+ const root = options.origin.endsWith('/') ? options.origin : `${options.origin}/`;
78
+ const body = await packRead(options, reads)(new URL(reference.path, root), reference.path, reference.sha256);
79
+ if (body.byteLength !== reference.bytes) throw new Error('Item catalogue byte count mismatch');
80
+ return readPlatformItemCatalogue(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body))).items;
68
81
  }
@@ -50,7 +50,7 @@ export class PlayerStore {
50
50
  }
51
51
  /** This player's fact ledger on this shard. */
52
52
  facts(input: HeadlessRuntimeInput, instance: string): RuntimeFacts {
53
- this.ledger ??= createQuestLedger(this.saves, input.shard, instance);
53
+ this.ledger ??= createQuestLedger(this.saves, input.shard, instance, input.catalogue);
54
54
  return this.ledger;
55
55
  }
56
56
  /** Every document held, as its text. */
@@ -25,16 +25,6 @@ export function worldSettings(channel: string, env: Readonly<Record<string, stri
25
25
  return { workers: Number(env['WORLD_WORKERS'] ?? start.workers), seats: Number(env['WORLD_SEATS'] ?? start.seats) };
26
26
  }
27
27
 
28
- /**
29
- * GC35 (J322, Jake 11-13: "World crossing should be on by default. There should never be any walls"): each worker hosts the road between
30
- * its cells unless `WORLD_CROSSING=off` (a bench's lone cells). Unset, or blank, is `worker`.
31
- */
32
- export function worldCrossing(value: string | undefined): boolean {
33
- if (value === undefined || value === '' || value === 'worker') return true;
34
- if (value === 'off') return false;
35
- throw new Error(`WORLD_CROSSING=${value}: only worker (the default) or off`);
36
- }
37
-
38
28
  /** SC8: a cell's awake cost in ms per tick (measured, or an Open Plot's when it has none). */
39
29
  export function cellCost(slug: string): number { return COST.get(slug) ?? UNMEASURED; }
40
30