@wildshard/engine 0.1.20 → 0.1.22

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 (94) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lint/engine-sides.json +4 -0
  3. package/lint/shardfile-boundaries.mjs +4 -2
  4. package/lint/wildshard-plugin.js +1 -1
  5. package/package.json +3 -1
  6. package/scripts/audio-download-proof.mjs +1 -1
  7. package/scripts/chaos-proxy-core.mjs +14 -1
  8. package/scripts/chaos-proxy-proof.mjs +22 -0
  9. package/scripts/check-spelled-paths.mjs +6 -3
  10. package/scripts/committed-fast-checks.mjs +2 -2
  11. package/scripts/failmode-cases.d.mts +8 -0
  12. package/scripts/failmode-cases.mjs +97 -0
  13. package/scripts/failmode-proof.mjs +556 -0
  14. package/scripts/grid-crossing-nightly.mjs +5 -4
  15. package/scripts/grid-crossing-report.mjs +5 -2
  16. package/scripts/grid-crossing-tour.mjs +25 -8
  17. package/scripts/grid-crossing-walk-proof.mjs +3 -3
  18. package/scripts/hover-speed-probe.mjs +136 -0
  19. package/scripts/mmo-bots.mjs +7 -3
  20. package/scripts/net-lag-proof.mjs +4 -3
  21. package/scripts/online-rig.mjs +11 -9
  22. package/scripts/parity/boot-smoke.mjs +1 -1
  23. package/scripts/release-cook.mjs +113 -0
  24. package/scripts/test-products.json +0 -21
  25. package/scripts/vps/cook-follow.d.mts +6 -0
  26. package/scripts/vps/cook-follow.mjs +45 -0
  27. package/scripts/vps/harden-apply.sh +10 -1
  28. package/scripts/vps/rebuild.sh +120 -26
  29. package/scripts/vps/wildshard-apply.mjs +5 -1
  30. package/scripts/vps/wildshard-config +117 -3
  31. package/src/client/app/entry.ts +2 -3
  32. package/src/client/engine/boot/contentRead.ts +78 -9
  33. package/src/client/engine/boot/downloadGiveUp.ts +34 -0
  34. package/src/client/engine/boot/gpuFiles.ts +3 -3
  35. package/src/client/engine/boot/leaveAfterPaint.ts +4 -1
  36. package/src/client/engine/combat/EquipmentService.ts +2 -0
  37. package/src/client/engine/core/Game.ts +6 -2
  38. package/src/client/engine/core/shadowLayer.ts +18 -0
  39. package/src/client/engine/explore/pick.ts +13 -1
  40. package/src/client/engine/net/predictor.ts +12 -4
  41. package/src/client/engine/player/TouchControls.ts +3 -2
  42. package/src/client/engine/render/families/sceneSurface.ts +3 -1
  43. package/src/client/engine/telemetry/browserErrors.ts +3 -1
  44. package/src/client/engine/ui/ErrorModal.ts +1 -1
  45. package/src/client/engine/ui/Loading.ts +14 -2
  46. package/src/client/engine/ui/downloadFailed.ts +54 -0
  47. package/src/client/engine/ui/errorScreen.ts +51 -9
  48. package/src/client/engine/ui/hoverBoost.ts +31 -4
  49. package/src/client/engine/ui/styles/touch.css +6 -0
  50. package/src/client/game/boot/spawnDownload.ts +56 -7
  51. package/src/client/game/grid/copyPrompts.ts +3 -4
  52. package/src/client/game/grid/dataCellKit.ts +91 -0
  53. package/src/client/game/grid/enteredEquipment.ts +11 -2
  54. package/src/client/game/grid/live.ts +11 -301
  55. package/src/client/game/grid/liveSession.ts +33 -10
  56. package/src/client/game/grid/neighbourLife.ts +50 -32
  57. package/src/client/game/grid/reveal.ts +7 -2
  58. package/src/client/game/grid/session.ts +6 -70
  59. package/src/client/game/grid/shardfileFar.ts +13 -2
  60. package/src/client/game/plugin/weaponFamily.ts +6 -0
  61. package/src/client/game/shardfile/clientSource.ts +7 -3
  62. package/src/client/game/shardfile/clientWorker.ts +17 -7
  63. package/src/client/game/shardfile/groundMerge.ts +5 -3
  64. package/src/client/host/online/linkScreens.ts +12 -6
  65. package/src/client/host/online/reconnectStrip.ts +3 -2
  66. package/src/client/host/online/release.ts +87 -16
  67. package/src/client/host/online/releaseScreens.ts +108 -0
  68. package/src/client/host/online/shell.ts +46 -12
  69. package/src/client/host/online/voice.ts +45 -1
  70. package/src/client/host/online/voiceUi.ts +24 -6
  71. package/src/server/engine/sim/playerSim.ts +1 -1
  72. package/src/server/game/grid/room.ts +2 -38
  73. package/src/server/game/grid/simulation.ts +12 -6
  74. package/src/server/game/shardfile/declaredKitItems.ts +8 -2
  75. package/src/server/host/dedicated/cellHost.ts +9 -2
  76. package/src/server/host/dedicated/cellProtocol.ts +1 -1
  77. package/src/server/host/dedicated/cellWorker.ts +2 -2
  78. package/src/server/host/dedicated/dedicatedRoom.ts +22 -4
  79. package/src/server/host/dedicated/gridCells.ts +5 -3
  80. package/src/server/host/dedicated/main.ts +6 -4
  81. package/src/server/host/dedicated/roadRoom.ts +3 -0
  82. package/src/server/host/dedicated/workerTable.ts +0 -10
  83. package/src/server/host/dedicated/world.ts +39 -5
  84. package/src/server/host/standalone/cellWorld.ts +1 -1
  85. package/src/server/host/standalone/gridServer.ts +1 -1
  86. package/src/shared/engine/boot/loadingWaits.ts +10 -2
  87. package/src/shared/engine/core/config.ts +3 -0
  88. package/src/shared/engine/player/hoverSpeed.ts +3 -3
  89. package/src/shared/engine/saves/shape.ts +17 -2
  90. package/src/shared/engine/strings.ts +22 -1
  91. package/src/shared/game/grid/placementRows.ts +4 -3
  92. package/src/shared/game/grid/rules.ts +12 -0
  93. package/src/client/game/grid/cellLoading.ts +0 -110
  94. package/src/client/game/grid/cellScreens.ts +0 -48
@@ -3,7 +3,7 @@ import { prepareFrameMotors, type FrameMember } from '@wildshard/engine/physics/
3
3
  import type { Physics } from '@wildshard/engine/physics/Physics';
4
4
  import { TraversalReadiness, readinessModel, type ReadinessBundle, type ReadinessLink, type ReadinessTicket } from '@wildshard/engine/sim/readiness';
5
5
  import type { ReadinessWalls } from '@wildshard/engine/physics/readinessWalls';
6
- import { CHUNK_HALF, CONTENT_CAPS, ENTRY_WIDTH } from '@wildshard/engine/core/config';
6
+ import { CHUNK_HALF } from '@wildshard/engine/core/config';
7
7
  import { diagnosticNow } from '@wildshard/engine/core/clock';
8
8
  import { GhostWorlds, type GhostRegion } from '../../../shared/game/grid/ghosts';
9
9
  import { WORK_SLICE_MS, workSlice } from '@wildshard/engine/core/workSlice';
@@ -15,7 +15,6 @@ import type { HomeResidencyClaim } from './pageResidency';
15
15
  import { ApproachInputsDeferredError } from './productInputs';
16
16
  import { PRODUCT_DEFERRED } from './productLeases';
17
17
  import { clientPreparationBatch } from '../shardfile/preparationTiming';
18
- import { tileOf, type CellTile } from '../../../shared/game/shardfile/tileOrder';
19
18
  import type { RegionShell } from './regionShell';
20
19
 
21
20
  /** A region on a page: the world its traveller's motor walks in. The server runs it and keeps its save. */
@@ -59,19 +58,11 @@ export interface LiveGridPorts {
59
58
  admit: (cell: GridCell, required?: boolean) => Promise<LiveGridAdmission>;
60
59
  /** Actual world construction or a verified render approach outranks product-only prefetch until its finite preparation drains. */
61
60
  prioritize?: (cell: GridCell) => () => void;
62
- /** Render-only approach: the signal owns the pin, including after preparation completes. */
63
- prepareNeighbour?: (cell: GridCell, start: { readonly x: number; readonly z: number }, signal: AbortSignal) => Promise<void>;
64
- /** Verified, charged inputs for one named source-exit approach, held until
65
- * abort. No regional world/readiness may publish from this IO-only port. */
66
- prepareTransport?: (cell: GridCell, signal: AbortSignal) => Promise<void>;
67
61
  /** Browser presentation boundary between admission batches; absent leaves the standalone Node scheduler unchanged. */
68
62
  pause?: () => Promise<void>;
69
63
  /** Metadata-only prefetch eligibility. Unsupported far proxies do not consume cold request slots; explicit transfers
70
64
  * still run normal admission and readiness. Absent: every cell is a candidate, as in standalone Node drivers. */
71
65
  prefetchable?: (cell: GridCell) => boolean;
72
- /** GC5 / GC36 (J322: no hold at the line): on the road, build the world of the cell the traveller heads into, ahead of
73
- * its line, so its entry finds it resident. Absent (standalone drivers): only actual entry builds a world (T7). */
74
- buildAhead?: boolean;
75
66
  /** Product-only prefetch waits while this is false (T10: the page's spawn settle); required entry never waits. Absent: always. */
76
67
  backgroundReady?: () => boolean;
77
68
  bindFrame: (frame: LiveGridFrame) => void;
@@ -115,50 +106,6 @@ interface RetiringRegion { readonly instance: string; readonly resident: Residen
115
106
  readonly finished: Promise<void>; readonly settle: () => void }
116
107
  interface Resident { region: LiveGridRegion; lease: ResidencyLease; reservations: number; evicting: boolean; retainable: boolean; evictionBound?: boolean; disposalFailed?: boolean }
117
108
 
118
- // Contact corrections at a closed readiness wall are not a U-turn. Accumulate real horizontal travel
119
- // before selecting another approach, so sub-centimetre capsule recoil cannot evict the world just prepared.
120
- const APPROACH_TRAVEL_METRES = 0.1;
121
- // GC5: the page pre-warms a neighbour's world from inside the source, at the distance the traveller covers at its speed in that
122
- // world's last measured build time (2 s at least; before it is measured, the slowest build so far or 14 s, capped at 16 s), times a margin. Kept while the traveller stays within
123
- // WARM_KEEP_METRES of it; the lead is capped below that, so a pre-warm never starts where it would be dropped.
124
- const DEMAND_METRES = 80, HELD_RETRY_MS = 5000, HEADING_HOLD_MS = 600, FIXED_HZ = 60, WARM_DEFAULT_SECONDS = 14, WARM_MIN_SECONDS = 2, WARM_MAX_SECONDS = 16, WARM_MARGIN = 1.25, WARM_LEAD_METRES = 8, WARM_LEAD_CAP_METRES = 200, WARM_KEEP_METRES = 240;
125
- const entryAxes = [['x', 'z'], ['z', 'x']] as const;
126
- // Distance can decrease while passing parallel to a cell. Only a ray into its first boundary's midpoint mouth
127
- // predicts entry; product downloads remain radial, but an unrelated native world must not block the real turn-in.
128
- function headsToEntry(cell: GridCell, feet: GridPoint, previous: GridPoint): boolean {
129
- const delta = { x: feet.x - previous.x, z: feet.z - previous.z };
130
- let first = Infinity, offset = Infinity;
131
- for (const [axis, other] of entryAxes) for (const side of [-1, 1]) {
132
- const direction = delta[axis]; if (direction === 0) continue;
133
- const time = (cell.origin[axis] + side * CHUNK_HALF - feet[axis]) / direction;
134
- if (time < 0 || time >= first) continue;
135
- const lateral = Math.abs(feet[other] + time * delta[other] - cell.origin[other]);
136
- if (lateral <= CHUNK_HALF) { first = time; offset = lateral; }
137
- }
138
- return offset <= ENTRY_WIDTH / 2;
139
- }
140
-
141
- // A boulevard predicts its next midpoint turn, before the player aims at the perpendicular mouth.
142
- // A small lateral turn names its side before the ray reaches the narrow mouth.
143
- // Straight travel retains both sides, so an undecided junction remains ambiguous.
144
- function boulevardApproachDistance(cell: GridCell, feet: GridPoint, previous: GridPoint, pitch: number): number | undefined {
145
- const delta = { x: feet.x - previous.x, z: feet.z - previous.z };
146
- for (const [axis, other] of entryAxes) for (const side of [-1, 1]) {
147
- const road = cell.origin[axis] + side * pitch / 2, lateral = cell.origin[other] - feet[other];
148
- if (Math.abs(feet[axis] - road) > ENTRY_WIDTH / 2 || Math.abs(delta[axis]) > Math.abs(delta[other]) / 4
149
- || delta[other] * lateral <= 0 || delta[axis] * side > Math.abs(delta[other]) / 20) continue;
150
- return Math.abs(lateral) + pitch / 2 - CHUNK_HALF;
151
- }
152
- return undefined;
153
- }
154
-
155
- /** Real background failures stay closed until retry. Expected optional headroom
156
- * deferrals remain retryable after cost changes and never report a load failure. */
157
- async function background(instance: string, admission: Promise<unknown>, alive: () => boolean): Promise<void> {
158
- try { await admission; }
159
- catch (error) { if (alive() && !(error instanceof ApproachInputsDeferredError)) console.error(`[grid] ${instance}: admission failed; it stays closed until a retry`, error); }
160
- }
161
-
162
109
  /** One page traveller with frozen owned regions. Borrowed homes keep the existing standalone composition;
163
110
  * owned homes begin on neutral page physics and transfer the sole preallocation claim to their first runtime. */
164
111
  export class LiveGridHost {
@@ -187,25 +134,9 @@ export class LiveGridHost {
187
134
  private frameGeneration = 0;
188
135
  private readonly transitions: { from: string | null; to: string | null }[] = [];
189
136
  private crossings = 0;
190
- private warms = 0;
191
- /** QA row 43: when a traveller held at a cell's wall may next retry its failed build */
192
- private readonly heldRetryAt = new Map<string, number>();
193
- /** the other mouth the traveller inside the source turned to, and since when (HEADING_HOLD_MS) */
194
- private turnedSince: { instance: string; at: number } | null = null;
195
- /** GC5: why the last pre-warm the heading asked for did not start (its product still reading, an exclusive runtime, or the budget) */
196
- private warmRefusal: string | null = null;
197
137
  /** GC6: the neighbour whose product is read as demand (the nearest edge's, or the heading's) and not yet admitted: radial
198
138
  * reads of other cells wait while it is missing, so they don't take back the headroom its read needs. */
199
139
  private demanded: string | null = null;
200
- private previousFeet: GridPoint | undefined;
201
- /** fixed steps since `previousFeet` moved, for the traveller's speed (GC5) */
202
- private stepsSincePrevious = 0;
203
- /** GC5: each cell's last measured world build, in seconds (product to colliders and sim ready) */
204
- private readonly builtSeconds = new Map<string, number>();
205
- private readonly candidateDistances = new Map<GridCell,number>();
206
- private readonly approachWork:{candidates:GridCell[];boulevard:GridCell[]}[]=[];
207
- /** This host already owns the assembly and its frozen cells for its whole lifetime. */
208
- private targetCells: readonly GridCell[] | undefined;
209
140
  private initialHomePending: boolean;
210
141
  private readonly highwayLease: ResidencyLease;
211
142
  private readonly highway: LiveGridHighway;
@@ -250,13 +181,13 @@ export class LiveGridHost {
250
181
  }
251
182
  /** Render/global coordinates are derived, never written into an authored regional host. */
252
183
  worldFeet(): GridPoint { const p = this.ports.player.position, origin = this.origin(this.active); return { x: p.x + origin.x, y: p.y, z: p.z + origin.z }; }
253
- /** Pure 6 m enter / 10 m leave selection; calling it does not change the live page frame. */
184
+ /** Gate selects only the home and road. Worker retains the parked 6 m enter / 10 m leave selection. */
254
185
  target(feet: Readonly<GridPoint>): string | null {
255
186
  if (![feet.x, feet.y, feet.z].every(Number.isFinite)) throw new RangeError('Invalid live grid feet');
256
187
  const distance = (cell: GridCell): number => Math.max(Math.abs(feet.x - cell.origin.x), Math.abs(feet.z - cell.origin.z)) - CHUNK_HALF;
257
188
  if (this.active !== null && distance(this.assembly.cell(this.active)) <= 10) return this.active;
258
- const cells = this.targetCells ??= [...this.assembly.cells].sort((a, b) => a.instance.localeCompare(b.instance));
259
- return cells.find((cell) => distance(cell) <= 6)?.instance ?? null;
189
+ const home = this.assembly.cell(this.ports.home.instance);
190
+ return distance(home) <= 6 ? home.instance : null;
260
191
  }
261
192
  /** Admission includes colliders, initialized sim and parsed runtime module; entered hooks are a separate gameplay fence. */
262
193
  ready(instance: string | null): boolean {
@@ -298,7 +229,6 @@ export class LiveGridHost {
298
229
  this.deferredProducts.delete(instance); this.deferredDemand.delete(instance); this.products.set(instance, admission); return admission;
299
230
  } catch (error) {
300
231
  this.tileMetadata.delete(instance);
301
- if (this.tileApproach?.instance === instance) { this.tileApproach.controller.abort(); this.tileApproach = null; }
302
232
  const refused = error instanceof ApproachInputsDeferredError || (error instanceof Error && error.message.includes(PRODUCT_DEFERRED));
303
233
  // GC6 (QA 11-14 row 6): inside Driftwood the page held 3 to 5 neighbours' radial products (1199 of 1200 MB), pinned
304
234
  // while held, so Nalati's demand read was refused the whole approach and its world was built only on the road. A
@@ -318,7 +248,7 @@ export class LiveGridHost {
318
248
  private releaseSpeculative(kept: string): number {
319
249
  const feet = this.worldFeet(), keep = (id: string): boolean => id === kept || id === this.active || id === this.ahead
320
250
  || this.constructing.has(id) || this.requests.has(id) || this.residents.has(id)
321
- || id === this.tileApproach?.instance || id === this.transportApproach?.instance;
251
+ || id === this.transportApproach?.instance;
322
252
  const idle = [...this.products.keys()].filter(id => !keep(id))
323
253
  .sort((a, b) => this.distance(this.assembly.cell(b), feet) - this.distance(this.assembly.cell(a), feet));
324
254
  for (const id of idle) {
@@ -333,9 +263,6 @@ export class LiveGridHost {
333
263
  /** GC5 / GC36: the cell whose world the road is building or built ahead of its line (`buildAhead`), kept until the
334
264
  * traveller enters a cell or heads into another's mouth. */
335
265
  private ahead: string | null = null;
336
- /** GC9: the optional read last raised to demand, so a pending radial read is raised once, not every tick */
337
- private raised: Promise<LiveGridAdmission> | null = null;
338
- private tileApproach: { instance: string; tile: CellTile; controller: AbortController } | null = null;
339
266
  private transportApproach: { instance: string; controller: AbortController; work: Promise<void> } | null = null;
340
267
  private retiredTransport: Promise<void> = Promise.resolve();
341
268
  private stopApproachTransport(): void {
@@ -343,40 +270,6 @@ export class LiveGridHost {
343
270
  this.transportApproach = null; previous.controller.abort();
344
271
  this.retiredTransport = this.settle(previous.work);
345
272
  }
346
- private prepareApproachTransport(cell: GridCell): void {
347
- const prepare = this.ports.prepareTransport;
348
- if (prepare === undefined || this.transportApproach?.instance === cell.instance) return;
349
- this.stopApproachTransport();
350
- const controller = new AbortController(), previous = this.retiredTransport;
351
- // Acquire priority synchronously, before this tick's speculative IO runs.
352
- // The old key keeps its own priority until its already-started reads drain.
353
- const releasePriority = this.ports.prioritize?.(cell);
354
- const work = (async (): Promise<void> => {
355
- try { await previous; if (!this.disposed && !controller.signal.aborted) await prepare(cell, controller.signal); }
356
- finally { releasePriority?.(); }
357
- })();
358
- const approach = { instance: cell.instance, controller, work }; this.transportApproach = approach;
359
- void background(cell.instance, work, () => !this.disposed && !controller.signal.aborted);
360
- }
361
- private prepareNeighbour(cell: GridCell, feet: GridPoint): void {
362
- const start = { x: Math.max(-CHUNK_HALF, Math.min(CHUNK_HALF, feet.x - cell.origin.x)),
363
- z: Math.max(-CHUNK_HALF, Math.min(CHUNK_HALF, feet.z - cell.origin.z)) };
364
- const tile = tileOf(start.x, start.z), prior = this.tileApproach;
365
- if (prior?.instance === cell.instance && prior.tile.i === tile.i && prior.tile.j === tile.j) return;
366
- // A diagonal approach can reach another mouth of the same destination.
367
- // Retarget only across tile boundaries; keep exactly one speculative pin.
368
- prior?.controller.abort();
369
- const controller = new AbortController();
370
- this.tileApproach = { instance: cell.instance, tile, controller };
371
- const prepare = this.ports.prepareNeighbour;
372
- if (prepare === undefined) return;
373
- const pending = (async (): Promise<void> => {
374
- const releasePriority = this.ports.prioritize?.(cell);
375
- try { await prepare(cell, start, controller.signal); }
376
- finally { releasePriority?.(); }
377
- })();
378
- void background(cell.instance, pending, () => !this.disposed && !controller.signal.aborted);
379
- }
380
273
  private ensure(instance: string): Promise<void> {
381
274
  if (this.disposed) return Promise.reject(new Error('Live grid is disposed'));
382
275
  const cell = this.assembly.cell(instance);
@@ -403,7 +296,6 @@ export class LiveGridHost {
403
296
  await (timing === undefined ? previous : timing.run('queue', () => previous));
404
297
  await this.retiredTransport;
405
298
  this.assertAlive();
406
- const buildStart = diagnosticNow();
407
299
  const admitted = timing === undefined ? await this.prefetchProduct(instance, true) : await timing.run('metadata', () => this.prefetchProduct(instance, true));
408
300
  admission = admitted;
409
301
  this.assertAlive();
@@ -438,7 +330,6 @@ export class LiveGridHost {
438
330
  this.assertAlive();
439
331
  this.residents.set(instance, { region, lease, reservations: 0, evicting: false, retainable: admitted.isolatedPreparation === true });
440
332
  this.readiness.complete(ticket, 'colliders'); this.readiness.complete(ticket, 'sim');
441
- this.builtSeconds.set(instance, (diagnosticNow() - buildStart) / 1000);
442
333
  lease.update({ needed: false, distance: this.distance(cell) });
443
334
  } catch (error) {
444
335
  try { region?.dispose(); }
@@ -466,7 +357,7 @@ export class LiveGridHost {
466
357
  }
467
358
  private retainedFits(instance: string): boolean {
468
359
  const policy = this.ports.lastCell;
469
- return policy !== undefined && this.ports.allocator.ownerCost(instance).playing <= Math.min(CONTENT_CAPS.playing, policy.playingBytes);
360
+ return policy !== undefined && this.ports.allocator.ownerCost(instance).playing <= Math.min(this.ports.allocator.envelope(), policy.playingBytes);
470
361
  }
471
362
  /** Call only after entered leave hooks finish. Keep the same ready world,
472
363
  * without a second claim, snapshot, physics host or shader preparation. */
@@ -510,13 +401,6 @@ export class LiveGridHost {
510
401
  resident.lease.update({ needed: false, distance: this.distance(this.assembly.cell(instance)) });
511
402
  return this.lastCell === last;
512
403
  }
513
- /** GC5: how far from a neighbour's square its world starts building at `speed` (m/s): its measured build time, or the
514
- * slowest measured so far or the default, at least WARM_MIN_SECONDS, with a margin; capped below the keep distance. */
515
- private warmLead(instance: string, speed: number): number {
516
- const measured = this.builtSeconds.get(instance) ?? Math.max(WARM_DEFAULT_SECONDS, ...this.builtSeconds.values());
517
- const seconds = Math.min(WARM_MAX_SECONDS, Math.max(WARM_MIN_SECONDS, measured));
518
- return Math.min(WARM_LEAD_CAP_METRES, WARM_LEAD_METRES + speed * seconds * WARM_MARGIN);
519
- }
520
404
  private distance(cell: GridCell, p = this.worldFeet()): number { return Math.hypot(Math.max(0, Math.abs(p.x - cell.origin.x) - CHUNK_HALF), Math.max(0, Math.abs(p.z - cell.origin.z) - CHUNK_HALF)); }
521
405
  /** Only the active/reserved world and one bounded departed world can remain.
522
406
  * A different actual entry retires the departure before any new allocation. */
@@ -550,183 +434,11 @@ export class LiveGridHost {
550
434
  /** Before the existing page physics/player step: radial requests are U-turn safe, and current-world walls synchronize first. */
551
435
  beforeFixed(): void {
552
436
  if (this.disposed) return;
553
- const work=this.approachWork.pop()??{candidates:[],boulevard:[]};
554
- try{this.beforeFixedWithWork(work);}
555
- finally{work.candidates.length=0;work.boulevard.length=0;if(!this.disposed)this.approachWork.push(work);}
437
+ this.beforeFixedWithWork();
556
438
  }
557
- private beforeFixedWithWork(work:{candidates:GridCell[];boulevard:GridCell[]}):void{
558
- if (this.tileApproach?.instance === this.active && this.ports.gameplayReady(this.tileApproach.instance)) {
559
- this.tileApproach.controller.abort(); this.tileApproach = null;
560
- }
561
- const feet = this.worldFeet(), previous = this.previousFeet;
562
- const travelledDistance = previous === undefined ? 0 : Math.hypot(feet.x - previous.x, feet.z - previous.z);
563
- // More than a second of modeled travel between fixed samples is a pose/portal jump.
564
- // Establish a new origin instead of spending a constructor on its accidental direction.
565
- const travelled = previous !== undefined && travelledDistance >= APPROACH_TRAVEL_METRES && travelledDistance <= this.ports.readiness.link.speed;
566
- const steps = ++this.stepsSincePrevious, speed = travelled ? travelledDistance * FIXED_HZ / steps : 0;
567
- if (previous === undefined || travelledDistance >= APPROACH_TRAVEL_METRES) { this.previousFeet = feet; this.stepsSincePrevious = 0; }
568
- // Prefetch the closest cells' products (never their worlds: G663). Unsupported far proxies do not consume the count
569
- // before enterable cells inside the cold readiness bound.
570
- const candidates=work.candidates,cells=this.assembly.cells;
571
- for(let i=0,length=cells.length;i<length;i++){
572
- const cell=cells[i];if(cell!==undefined&&cell.instance!==this.active&&(this.ports.prefetchable?.(cell)??true))candidates.push(cell);
573
- }
574
- // Fixed cell poses and this tick's captured feet: avoid repeating hypot inside every sort comparison.
575
- for (const cell of candidates) this.candidateDistances.set(cell,this.distance(cell,feet));
576
- candidates.sort((a,b) => (this.candidateDistances.get(a) ?? Infinity) - (this.candidateDistances.get(b) ?? Infinity) || a.instance.localeCompare(b.instance));
577
- // Immutable products are selected by distance, without a whole-world count cap.
578
- const nearby = candidates;
579
- // The frame-transfer reservation protects an actual entry; inactive whole worlds retire in steps. A world built ahead
580
- // (`buildAhead`) stays while the traveller is on the road and has not turned into another mouth (below); one pre-warmed
581
- // from inside the source (GC5) stays while the traveller is within WARM_KEEP_METRES of it.
582
- if (this.active !== null && this.ahead !== null && (this.ahead === this.active
583
- || this.distance(this.assembly.cell(this.ahead), feet) > WARM_KEEP_METRES)) this.ahead = null;
439
+ private beforeFixedWithWork():void{
440
+ // J353: the road and placeholders remain, but a page never reads, prepares or admits a second cell.
584
441
  this.retireInactiveRegions();
585
- // GC6: the demanded neighbour stays demanded until its product is in, it is entered, or the traveller is far from it
586
- const demanded = this.demanded;
587
- if (demanded !== null && (this.products.has(demanded) || this.residents.has(demanded) || demanded === this.active || this.issues.has(demanded)
588
- || this.distance(this.assembly.cell(demanded), feet) > DEMAND_METRES + WARM_LEAD_METRES * 4)) this.demanded = null;
589
- for (const cell of nearby) {
590
- const estimate = readinessModel(this.ports.readiness.bundle(cell), this.ports.readiness.link), distance = this.distance(cell, feet);
591
- if (this.demanded !== null && this.demanded !== cell.instance) continue;
592
- if (this.assembly.approaching(distance, estimate.distance) && !this.issues.has(cell.instance) && this.ports.backgroundReady?.() !== false) void background(cell.instance, this.prefetch([cell.instance], 'radial'), () => !this.disposed);
593
- }
594
- // GC5: the neighbour across the source's nearest edge, within DEMAND_METRES, has its product read as demand, standing or
595
- // moving: a player at a cell's edge reaches it in seconds at a boost, and the radial read above is only a guess the shared
596
- // budget declines while every neighbour competes for it (Pine's read alone is 6 to 8 s). One at a time, the nearest.
597
- if (this.active !== null && this.ports.buildAhead === true) {
598
- const near = candidates[0];
599
- // GC9: a radial read already pending for it is raised to demand once (the budget declined Pine's radial read again and
600
- // again while it stood pending, so the demand read never started inside Driftwood and Pine's world was built on the road)
601
- const pending = near === undefined ? undefined : this.productRequests.get(near.instance);
602
- if (near !== undefined && this.distance(near, feet) <= DEMAND_METRES && !this.products.has(near.instance) && !this.residents.has(near.instance)
603
- && (pending === undefined || !pending.required && this.raised !== pending.work) && !this.issues.has(near.instance) && !this.constructing.has(near.instance)
604
- && this.deferredDemand.get(near.instance) !== this.ports.allocator.revision && this.ports.backgroundReady?.() !== false) {
605
- if (pending !== undefined) this.raised = pending.work;
606
- this.demanded = near.instance;
607
- void background(near.instance, this.prefetchProduct(near.instance, true, 'explicit', true), () => !this.disposed);
608
- }
609
- }
610
- // Approach preparation owns render tiles only, never a regional world or gameplay hooks.
611
- const moving = !travelled ? undefined : candidates.find(cell => headsToEntry(cell, feet, previous)
612
- && this.distance(cell, feet) < this.distance(cell, previous) - 0.000001);
613
- const source = this.active === null ? undefined : this.assembly.cell(this.active);
614
- const sourceDistance = source === undefined ? Infinity : Math.max(Math.abs(feet.x - source.origin.x), Math.abs(feet.z - source.origin.z));
615
- const transportApproach = this.transportApproach;
616
- if (transportApproach !== null) {
617
- const cell = this.assembly.cell(transportApproach.instance);
618
- if (moving !== undefined && moving.instance !== cell.instance
619
- || this.distance(cell, feet) >= this.assembly.pitch
620
- || source !== undefined && source.instance !== cell.instance && sourceDistance < CHUNK_HALF - 1) this.stopApproachTransport();
621
- }
622
- const tileApproach = this.tileApproach;
623
- if (tileApproach !== null) {
624
- const cell = this.assembly.cell(tileApproach.instance);
625
- if (moving !== undefined && moving.instance !== cell.instance
626
- || this.distance(cell, feet) > readinessModel(this.ports.readiness.bundle(cell), this.ports.readiness.link).distance) {
627
- tileApproach.controller.abort(); this.tileApproach = null;
628
- }
629
- }
630
- // The world built ahead goes once the traveller is a pitch from it, or heads from the road into another mouth (a stop
631
- // keeps it). Checked while a build runs too, which the gate below skips.
632
- const wallReach = 6 + this.ports.player.motor.opts.radius + 0.5 + this.ports.readiness.link.speed / 60;
633
- const departed = this.transitions.at(-1)?.from;
634
- // QA 11-13 row 43: on the road within a cell's wall reach the traveller is at that cell's wall, whatever the heading: a
635
- // jump or a recoil off the wall reads as a heading back into the cell just left, which let the world built ahead go.
636
- const held = this.ports.buildAhead === true && this.active === null && this.assembly.at(feet.x, feet.z) === undefined
637
- ? nearby.find(cell => cell.instance !== departed && this.distance(cell, feet) <= wallReach) : undefined;
638
- // Inside the source a new heading must hold HEADING_HOLD_MS before it retires the world built ahead: steering that
639
- // wobbles near a corner would otherwise build and dispose a whole world per flip.
640
- const turned = moving !== undefined && moving.instance !== this.ahead;
641
- if (!turned || this.active === null) this.turnedSince = null;
642
- else if (this.turnedSince?.instance !== moving.instance) this.turnedSince = { instance: moving.instance, at: diagnosticNow() };
643
- const settledTurn = turned && (this.active === null || diagnosticNow() - (this.turnedSince?.at ?? 0) >= HEADING_HOLD_MS);
644
- if (this.ahead !== null && (this.distance(this.assembly.cell(this.ahead), feet) >= this.assembly.pitch
645
- || held === undefined && settledTurn && (this.assembly.at(feet.x, feet.z) === undefined || this.active !== null))) this.ahead = null;
646
- if (this.requests.size === 0) {
647
- const boulevard=work.boulevard;
648
- if(travelled&&moving===undefined)for(let i=0,length=candidates.length;i<length;i++){
649
- const cell=candidates[i];if(cell!==undefined&&cell.instance!==departed
650
- &&(boulevardApproachDistance(cell,feet,previous,this.assembly.pitch)??Infinity)
651
- <=readinessModel(this.ports.readiness.bundle(cell),this.ports.readiness.link).distance)boulevard.push(cell);
652
- }
653
- // Product metadata identifies bounded native alternatives even when the nearer opaque product filled
654
- // the radial prefetch count. This admits immutable products/modules, never their foundations.
655
- for (const cell of boulevard) if (!this.issues.has(cell.instance)) void background(cell.instance, this.prefetch([cell.instance], 'boulevard'), () => !this.disposed);
656
- // A unique next junction can prepare tiles. Equidistant sides wait for a turn.
657
- let predicted: GridCell | undefined, nextDistance = Infinity;
658
- for (const cell of boulevard) {
659
- const distance = boulevardApproachDistance(cell, feet, previous ?? feet, this.assembly.pitch);
660
- if (distance === undefined) continue;
661
- if (distance < nextDistance - 0.000001) { predicted = cell; nextDistance = distance; }
662
- else if (Math.abs(distance - nextDistance) <= 0.000001) predicted = undefined;
663
- }
664
- // A stationary sample is not a redirect. Keep the verified render owner
665
- // until a named heading or the distance fence replaces it; the cell just
666
- // left must not steal that pin merely because its wall is still nearest.
667
- const heldApproach = this.tileApproach === null ? undefined : this.assembly.cell(this.tileApproach.instance);
668
- const approach = moving ?? predicted ?? heldApproach
669
- ?? nearby.find(cell => cell.instance !== departed && this.distance(cell, feet) <= wallReach);
670
- const named = moving ?? predicted, outsideSource = sourceDistance >= CHUNK_HALF;
671
- if (named !== undefined && outsideSource && !this.residents.has(named.instance) && !this.issues.has(named.instance)
672
- && this.distance(named, feet) < this.assembly.pitch) this.prepareApproachTransport(named);
673
- // GC5 / GC36 (J322: no walls, no hold at the line): on the road, a traveller heading into a cell's mouth builds that
674
- // cell's world now, not at the line. Built on demand there, the walk stood 2 to 5 s at the neighbour's closed edge
675
- // while its world was made (2 to 4 s in Chromium). The entry's own preparation then finds it resident. The departed
676
- // cell retires first, as the entry would retire it; a U-turn builds it again, as any entry does.
677
- // Only from the road itself: past a cell's line (inside its square, before the 6 m entry) the heading names the cell
678
- // beyond it, which would retire the world just built for the one underfoot.
679
- // QA 11-13 row 43 (Jake on staging: 11 s at Template's wall, "saved state and its systems", no progress): a traveller
680
- // standing at a neighbour's closed wall makes no heading (under 0.1 m a sample), so a world built ahead and then let go
681
- // was never asked for again, and online the server crosses only past the line the wall holds them short of. Held at
682
- // a closed wall on the road, that cell's world is always building.
683
- // A failed build is tried again while they stand there, at most every HELD_RETRY_MS (never on a cleanup failure).
684
- if (held !== undefined && this.issues.has(held.instance) && !this.residents.has(held.instance) && !this.requests.has(held.instance) && !this.productRequests.has(held.instance)
685
- && diagnosticNow() >= (this.heldRetryAt.get(held.instance) ?? 0)) { this.heldRetryAt.set(held.instance, diagnosticNow() + HELD_RETRY_MS); this.retry(held.instance); }
686
- if (held !== undefined && !this.residents.has(held.instance) && !this.issues.has(held.instance)) {
687
- this.ahead = held.instance;
688
- if (this.retireInactiveRegions(held.instance)) void background(held.instance, this.ensure(held.instance), () => !this.disposed);
689
- }
690
- else if (held === undefined && this.ports.buildAhead === true && moving !== undefined && this.active === null && this.assembly.at(feet.x, feet.z) === undefined
691
- && !this.residents.has(moving.instance) && !this.issues.has(moving.instance)
692
- && this.distance(moving, feet) < this.assembly.pitch && this.retireInactiveRegions(moving.instance)) {
693
- this.ahead = moving.instance;
694
- void background(moving.instance, this.ensure(moving.instance), () => !this.disposed);
695
- }
696
- // GC5 (QA 11-13 row 39: boosts held 4 to 7.6 s at the neighbour's loading wall, the road being under 3 s at 18 m/s):
697
- // inside the source, heading into a neighbour's mouth, its world is built once the traveller is its measured build
698
- // time away at this speed. Only beside an isolated source and for an isolated product (opaque runtimes stay exclusive,
699
- // built only on the road), and only when both fit beside each other (G723); else the road builds it as before.
700
- if (this.ports.buildAhead === true && moving !== undefined && this.active !== null && this.ahead === null
701
- && this.residents.get(this.active)?.retainable === true && !this.residents.has(moving.instance) && !this.issues.has(moving.instance)
702
- && this.distance(moving, feet) <= this.warmLead(moving.instance, speed)) {
703
- const product = this.products.get(moving.instance);
704
- // The heading names it: its product is read as demand (it may evict speculative neighbours' products), not as a radial
705
- // guess, which the shared budget declines while the page's other neighbours compete for the same headroom.
706
- if (product === undefined) {
707
- this.warmRefusal = 'product';
708
- this.demanded = moving.instance;
709
- if (!this.productRequests.has(moving.instance) && this.deferredDemand.get(moving.instance) !== this.ports.allocator.revision)
710
- void background(moving.instance, this.prefetchProduct(moving.instance, true, 'explicit', true), () => !this.disposed);
711
- }
712
- else if (product.isolatedPreparation !== true) this.warmRefusal = 'exclusive';
713
- else if (!this.ports.allocator.canPrepareAlongside(this.active, moving.instance, product.bytes,
714
- { playing: this.ports.allocator.envelope(), loading: CONTENT_CAPS.loading })) this.warmRefusal = 'budget';
715
- else {
716
- this.ahead = moving.instance; this.warms++; this.warmRefusal = null;
717
- void background(moving.instance, this.ensure(moving.instance), () => !this.disposed);
718
- }
719
- }
720
- if (approach !== undefined && this.ports.prepareNeighbour !== undefined && this.tileMetadata.has(approach.instance)
721
- && !this.residents.has(approach.instance) && !this.issues.has(approach.instance)
722
- && (this.active === null || moving === approach)
723
- // A held owner survives a stationary/teleported sample without moving
724
- // its entry tile. Only a real named approach may retarget that pin.
725
- && (heldApproach === undefined || moving === approach || predicted === approach)
726
- && this.assembly.approaching(this.distance(approach, feet), readinessModel(this.ports.readiness.bundle(approach), this.ports.readiness.link).distance)) {
727
- this.prepareNeighbour(approach, feet);
728
- }
729
- }
730
442
  const walls = this.active === null ? this.highway.walls : this.region(this.active)?.walls;
731
443
  walls?.sync(this.readiness);
732
444
  }
@@ -887,7 +599,6 @@ export class LiveGridHost {
887
599
  motors.commit();
888
600
  this.ports.player.motor = rider.motor; this.active = to;
889
601
  if (to !== null) this.forgetLastCell();
890
- this.previousFeet = this.worldFeet(); // A committed spawn/frame placement is not the traveller's heading.
891
602
  this.ports.bindFrame({ instance: to, physics: this.physics(to), motor: rider.motor, origin });
892
603
  this.residents.get(to ?? '')?.lease.update({ needed: true }); this.residents.get(from ?? '')?.lease.update({ needed: to === null });
893
604
  this.crossings++; this.transitions.push({ from, to }); if (this.transitions.length > 256) this.transitions.shift(); finish();
@@ -897,10 +608,10 @@ export class LiveGridHost {
897
608
  private retainedState(): Exclude<LiveGridState['retainedCell'], undefined> {
898
609
  const last = this.lastCell, policy = this.ports.lastCell;
899
610
  return last === null || policy === undefined ? null : { instance: last.instance, remainingMs: Math.max(0, last.until - diagnosticNow()),
900
- playingBytes: this.ports.allocator.ownerCost(last.instance).playing, capBytes: Math.min(CONTENT_CAPS.playing, policy.playingBytes) };
611
+ playingBytes: this.ports.allocator.ownerCost(last.instance).playing, capBytes: Math.min(this.ports.allocator.envelope(), policy.playingBytes) };
901
612
  }
902
613
  /** Read-only crossing evidence and failures for the real grid physics harness. */
903
- state(): LiveGridState { return { current: this.active, worldFeet: this.worldFeet(), crossings: this.crossings, ahead: { instance: this.ahead, warms: this.warms, refused: this.warmRefusal, deferred: [...new Set([...this.deferredProducts.keys(), ...this.deferredDemand.keys()])], demanded: this.demanded, released: this.released }, transitions: this.transitions.map((row) => ({ ...row })), residents: [...this.residents.keys()].sort(), pending: [...new Set([...this.requests.keys(), ...this.productRequests.keys()])].sort(), pendingWork: [
614
+ state(): LiveGridState { return { current: this.active, worldFeet: this.worldFeet(), crossings: this.crossings, transitions: this.transitions.map((row) => ({ ...row })), residents: [...this.residents.keys()].sort(), pending: [...new Set([...this.requests.keys(), ...this.productRequests.keys()])].sort(), pendingWork: [
904
615
  ...[...this.requests.keys()].sort().map(instance => ({ instance, kind: 'world' as const, trigger: 'entry' as const })),
905
616
  ...[...this.productRequests].sort(([a], [b]) => a.localeCompare(b)).map(([instance, request]) => ({ instance, kind: request.required ? 'required-metadata' as const : 'optional-metadata' as const, trigger: request.trigger })),
906
617
  ], issues: Object.fromEntries(this.issues), gameplayReady: this.active === null || this.ports.gameplayReady(this.active), ...(this.ports.lastCell === undefined ? {} : { retainedCell: this.retainedState() }), retirements: this.retirements.map(row => ({ ...row })), retiring: [...this.retiring.keys()], ghosts: { count: this.ghosts.count(), regions: this.ghosts.regions() } }; }
@@ -910,7 +621,6 @@ export class LiveGridHost {
910
621
  this.disposed = true;
911
622
  this.forgetLastCell();
912
623
  this.stopApproachTransport();
913
- this.tileApproach?.controller.abort(); this.tileApproach = null;
914
624
  this.tileMetadata.clear();
915
625
  for (const cancel of this.frames) cancel();
916
626
  // Return the still-live page traveller before freeing a world that contains its current controller.
@@ -27,7 +27,7 @@ import { Vector3, type PerspectiveCamera } from 'three';
27
27
  import { createProgramKeeper, RETAINED_PROGRAM_BYTES, RETAINED_PROGRAM_LIMIT, type ProgramKeeper } from '@wildshard/engine/render/programRetention';
28
28
  import { diagnosticNow } from '@wildshard/engine/core/clock';
29
29
  import { WORK_SLICE_MS, workSlice } from '@wildshard/engine/core/workSlice';
30
- import { CHUNK_HALF, CONTENT_CAPS, ENTRY_ASPHALT } from '@wildshard/engine/core/config';
30
+ import { CHUNK_HALF, ENTRY_ASPHALT } from '@wildshard/engine/core/config';
31
31
  import type { DisposeStep, Scope } from '@wildshard/engine/app/scope';
32
32
  import type { Events } from '@wildshard/engine/events/events';
33
33
  import type { Physics } from '@wildshard/engine/physics/Physics';
@@ -49,7 +49,6 @@ import type { NeighbourRegion } from './neighbourLife';
49
49
  import type { ResidencyAllocator } from '../../../shared/game/grid/allocator';
50
50
  import type { HomeResidencyClaim } from './pageResidency';
51
51
  import { LiveGridHost, type LiveGridAdmission, type LiveGridFrame, type LiveGridRegion, type LiveGridState } from './live';
52
- import { prepareApproachProductInputs } from './approachProductInputs';
53
52
  import { installGridCrossing, type GridCheckpointResult, type GridCrossingSession, type GridCrossingState } from '../../../shared/game/grid/crossing';
54
53
  import { GridWallet, stowGridMount } from '../../../shared/game/grid/wallet';
55
54
  import type { LedgerCatalogueItem } from '../../../shared/game/ledger';
@@ -78,6 +77,7 @@ import { copyPrompts, enteredCopy } from './copyPrompts';
78
77
  import { yieldGridAdmission, yieldGridConstruction } from './admissionYield';
79
78
  import { HybridRuntimeSession, type HybridResident } from '../shardfile/hybrid';
80
79
 
80
+ import { enterDataCellKit, holdsItems } from './dataCellKit';
81
81
  import { enterPlotAudio, pagePlotAudioPorts, plotAudioScene, type PlotAudioPorts, type PlotAudioScene } from './plotAudio';
82
82
  import { shardProductFromAdmission } from '../shardfile/runtimeProduct';
83
83
  import { createRegionalRuntimeFactory, regionalRuntimeAccountedBytes, type PreparedRegionalRuntime, type RegionalRuntimePage, type RegionalRuntimeTextures } from './regionalRuntime';
@@ -235,9 +235,13 @@ export class LiveGridSession {
235
235
  private readonly applied = new Vector3();
236
236
  private readonly roadWallet: GridWallet;
237
237
  /** each admitted region's authored spawn (its level's player start) and its ground / water queries, local */
238
- private readonly regions = new Map<string, { readonly spawn: LiveGridSpawn; readonly items: Shardfile['items']['rows']; readonly queries: PlayerFrameQueries; readonly colliders: PanelRegion['colliders']; readonly prompts: ReturnType<typeof copyPrompts>; readonly audio: PlotAudioScene | null }>();
238
+ private readonly regions = new Map<string, { readonly spawn: LiveGridSpawn; readonly items: Shardfile['items']['rows']; readonly queries: PlayerFrameQueries; readonly colliders: PanelRegion['colliders']; readonly prompts: ReturnType<typeof copyPrompts>; readonly audio: PlotAudioScene | null;
239
+ /** TC-E1b: the copy's admitted source and assets, its declared kit built from them on entry */
240
+ readonly kit: { readonly source: Shardfile; readonly assets: ReadonlyMap<string, Uint8Array> } | null }>();
239
241
  /** AU20: the entered data cell's own audio scene (an Open Plot's score, bed and loops), live while the feet are in it. */
240
242
  private plotAudio: { readonly instance: string; readonly scope: Scope } | null = null;
243
+ /** TC-E1b: the entered data cell's held kit, disposed when the feet leave it */
244
+ private dataKit: { readonly instance: string; readonly scope: Scope } | null = null;
241
245
  private readonly plotBanks = new Map<string, ReturnType<PlotAudioPorts['bank']>>();
242
246
  private readonly runtimeScope: Scope;
243
247
  private readonly runtimeRegions = new Map<string, PreparedRegionalRuntime>();
@@ -273,9 +277,9 @@ export class LiveGridSession {
273
277
  this.runtimeScope = scope.child('grid.runtime.residents');
274
278
  this.hybrid = new HybridRuntimeSession(this.runtimeResidents, scope, { pause: yieldGridConstruction });
275
279
  scope.onDispose(gridCells.onLeave(() => { this.hybrid.leave(); this.prepareDeferredEntries(); }));
276
- scope.onDispose(gridCells.onLeave(() => { this.leavePlotAudio(); }));
280
+ scope.onDispose(gridCells.onLeave(() => { this.leavePlotAudio(); this.leaveDataKit(); }));
277
281
  scope.onDispose(gridCells.onEnter(cell => {
278
- if (!this.runtimeResidents.has(cell.instance)) { this.enterPlotAudio(cell.instance); ports.lightingSettled?.(); return; }
282
+ if (!this.runtimeResidents.has(cell.instance)) { this.enterPlotAudio(cell.instance); this.enterDataKit(cell.instance); ports.lightingSettled?.(); return; }
279
283
  this.startedRuntimes.add(cell.instance);
280
284
  const activation = this.hybrid.enter(cell);
281
285
  this.activation = activation;
@@ -293,7 +297,7 @@ export class LiveGridSession {
293
297
  const highwayBytes = (ports.initialStripBytes ?? ports.strips.reduce((sum, strip) => sum + strip.mesh.positions.byteLength + strip.mesh.indices.byteLength, 0))
294
298
  + assembly.cells.length * TRANSFER_WALL_BYTES;
295
299
  try { this.live = new LiveGridHost(assembly, {
296
- lastCell: { windowMs: 30_000, playingBytes: CONTENT_CAPS.playing, schedule: (expire, ms) => {
300
+ lastCell: { windowMs: 30_000, playingBytes: ports.allocator.envelope(), schedule: (expire, ms) => {
297
301
  const timer = scope.child('grid.last-cell-expiry');
298
302
  timer.timeout(ms, () => { timer.dispose(); scope.run(expire); });
299
303
  return () => { timer.dispose(); };
@@ -309,8 +313,6 @@ export class LiveGridSession {
309
313
  return { physics: ports.physics, walls: ports.walls, dispose: () => { highwayScope.dispose(); } };
310
314
  } },
311
315
  admit: (cell, required) => this.admit(cell, required),
312
- buildAhead: true, // GC5 / GC36: the road builds the world ahead of its line
313
- prepareTransport: (cell, signal) => prepareApproachProductInputs(cell.slug, { allocator: ports.allocator, scope }, signal, assembly.local(traveller.position, cell)),
314
316
  ...(ports.prepareNeighbourTiles === undefined ? {} : { prepareNeighbour: ports.prepareNeighbourTiles }),
315
317
  prioritize: (cell) => prioritizeGridProduct(cell.slug, { allocator: ports.allocator, scope }),
316
318
  pause: () => yieldGridAdmission(scope),
@@ -711,10 +713,12 @@ export class LiveGridSession {
711
713
  transfer.sync(); this.transferWalls.set(cell.instance, transfer);
712
714
  this.regions.set(cell.instance, { spawn: { x: start.at.x, y: undefined, z: start.at.z, yaw: start.yaw },
713
715
  // the admitted terrain inside the cell (one source of truth); its strips are road level (the terrain tile ends at the cell edge)
714
- queries: { heightAt: (x, z) => (Math.max(Math.abs(x), Math.abs(z)) <= CHUNK_HALF ? heightAt(x, z) : 0), waterSurfaceAt: (x, z) => water.restAt(x, z), platforms: [] }, colliders, items: copySource.items.rows, prompts: copyPrompts(copySource),
716
+ queries: { heightAt: (x, z) => (Math.max(Math.abs(x), Math.abs(z)) <= CHUNK_HALF ? heightAt(x, z) : 0), waterSurfaceAt: (x, z) => water.restAt(x, z), platforms: [] }, colliders, items: copySource.items.rows, prompts: copyPrompts(copySource), kit: holdsItems(copySource) ? { source: copySource, assets } : null,
715
717
  // AU20: the cell's declared audio scene, bound only while the feet stand in it (no entered hooks run here)
716
718
  audio: source.runtime === null && source.audio.scene !== undefined ? plotAudioScene(source, ((plot) => plot.has('client/plan') ? plot.section('client/plan') : undefined)(shardProductFromAdmission(retained.admitted, shell.scope))) : null });
717
719
  this.respawnCells.set(cell.instance, { instance: cell.instance, origin: cell.origin, entryways: source.entryways });
720
+ // TC-E1b: feet that entered before this admission finished get the cell's kit now
721
+ if (gridCells.cell?.instance === cell.instance && this.dataKit === null) this.enterDataKit(cell.instance);
718
722
  // G321: its own sky inside its cell (its data look's dome and light), laid while it is resident
719
723
  {
720
724
  const request = { instance: cell.instance, slug: cell.slug, look: copySource.look, assets, page: this.page.runtimePage?.() ?? null, allocator: this.ports.allocator, scope: shell.scope };
@@ -722,7 +726,7 @@ export class LiveGridSession {
722
726
  try { await hangCellDataSky(request); } catch (error) { console.warn(`[region sky] ${cell.instance}`, error); }
723
727
  })();
724
728
  }
725
- const unlist = (): void => { if (this.plotAudio?.instance === cell.instance) this.leavePlotAudio(); this.plotBanks.delete(cell.instance); this.regions.delete(cell.instance); this.transferWalls.delete(cell.instance); };
729
+ const unlist = (): void => { if (this.plotAudio?.instance === cell.instance) this.leavePlotAudio(); if (this.dataKit?.instance === cell.instance) this.leaveDataKit(); this.plotBanks.delete(cell.instance); this.regions.delete(cell.instance); this.transferWalls.delete(cell.instance); };
726
730
  return { host: shell, shell, dispose: () => {
727
731
  unlist();
728
732
  try { shell.dispose(); } finally { retained.release(); }
@@ -856,6 +860,25 @@ export class LiveGridSession {
856
860
  try { enterPlotAudio(scene, owner, ports); }
857
861
  catch (error) { this.leavePlotAudio(); ports.fault(error); }
858
862
  }
863
+ /** TC-E1b: the feet entered a data cell; its declared items are the page's held kit until they leave. */
864
+ private enterDataKit(instance: string): void {
865
+ this.leaveDataKit();
866
+ const kit = this.regions.get(instance)?.kit ?? null, page = this.page.runtimePage?.() ?? null;
867
+ if (kit === null || page === null) return;
868
+ const entry = this.ports.scope.child(`grid.data-kit.${instance}`);
869
+ this.dataKit = { instance, scope: entry };
870
+ const enter = async (): Promise<void> => {
871
+ try { await enterDataCellKit(kit.source, kit.assets, page, entry, () => this.wire === null || this.wire.site() === instance); } catch (error: unknown) {
872
+ if (this.dataKit?.scope === entry) this.leaveDataKit();
873
+ console.error(`[grid] ${instance}'s declared kit refused`, error);
874
+ }
875
+ };
876
+ void enter();
877
+ }
878
+ private leaveDataKit(): void {
879
+ const entered = this.dataKit; this.dataKit = null;
880
+ entered?.scope.dispose();
881
+ }
859
882
  private leavePlotAudio(): void {
860
883
  const entered = this.plotAudio; this.plotAudio = null;
861
884
  entered?.scope.dispose();