@wildshard/engine 0.1.19 → 0.1.20

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 (79) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lint/engine-sides.json +4 -0
  3. package/package.json +4 -2
  4. package/scripts/app-build/gen.ts +11 -0
  5. package/scripts/cell-mem-bench.mjs +2 -0
  6. package/scripts/check-devserver.mjs +1 -1
  7. package/scripts/grid-crossing-tour.mjs +11 -4
  8. package/scripts/grid-crossing-walk-proof.mjs +4 -2
  9. package/scripts/land.mjs +2 -1
  10. package/scripts/loading-flow/benchmax.mjs +34 -11
  11. package/scripts/loading-flow/deskbench.mjs +276 -0
  12. package/scripts/loading-flow/stalls.d.mts +17 -3
  13. package/scripts/loading-flow/stalls.mjs +82 -3
  14. package/scripts/nightly-model.ts +9 -6
  15. package/scripts/offline-proof.mjs +7 -1
  16. package/scripts/parity/boot-smoke.mjs +13 -2
  17. package/scripts/pin-format.ts +5 -2
  18. package/scripts/pins-reuse.d.mts +1 -0
  19. package/scripts/pins-reuse.mjs +22 -0
  20. package/scripts/scratch-dir.mjs +95 -0
  21. package/scripts/scratch-sweep.mjs +182 -0
  22. package/scripts/tsconfig.json +2 -12
  23. package/scripts/vps/harden-prometheus.sh +3 -0
  24. package/scripts/worktree-reap.mjs +54 -8
  25. package/scripts/worktree.mjs +19 -5
  26. package/src/client/engine/anim/rigParser.ts +2 -2
  27. package/src/client/engine/core/Game.ts +63 -19
  28. package/src/client/engine/core/gpuOnly.ts +10 -0
  29. package/src/client/engine/core/renderBudget.ts +134 -0
  30. package/src/client/engine/net/redial.ts +40 -5
  31. package/src/client/engine/render/dataLook.ts +70 -7
  32. package/src/client/engine/render/families/pbr.ts +2 -0
  33. package/src/client/engine/render/families/registry.ts +11 -2
  34. package/src/client/engine/render/families/sceneSurface.ts +116 -0
  35. package/src/client/engine/render/look.ts +7 -1
  36. package/src/client/engine/render/precompile.ts +4 -2
  37. package/src/client/engine/render/tiers.ts +4 -1
  38. package/src/client/engine/world/declaredProps.ts +5 -1
  39. package/src/client/engine/world/skyRig.ts +4 -1
  40. package/src/client/engine/world/terrainTileView.ts +64 -23
  41. package/src/client/game/devScene/hook.ts +149 -12
  42. package/src/client/game/devScene/liveLook.ts +21 -0
  43. package/src/client/game/grid/live.ts +45 -8
  44. package/src/client/game/grid/liveSession.ts +23 -4
  45. package/src/client/game/grid/pageEntry.ts +12 -1
  46. package/src/client/game/grid/productInputs.ts +22 -11
  47. package/src/client/game/grid/session.ts +13 -4
  48. package/src/client/game/session/finish.ts +4 -1
  49. package/src/client/game/shardfile/client.ts +24 -7
  50. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  51. package/src/client/game/shardfile/clientViews.ts +36 -8
  52. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  53. package/src/client/game/shardfile/groundMerge.ts +57 -5
  54. package/src/client/game/shardfile/hybrid.ts +2 -0
  55. package/src/client/game/shardfile/look.ts +1 -1
  56. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  57. package/src/client/game/shardfile/tileContent.ts +1 -1
  58. package/src/client/game/shardfile/tileDriver.ts +38 -11
  59. package/src/client/game/shardfile/wirePage.ts +7 -3
  60. package/src/client/game/shardfile/worldScenes.ts +17 -10
  61. package/src/client/host/online/doctor.ts +20 -7
  62. package/src/client/host/online/doctorView.ts +2 -0
  63. package/src/client/host/online/linkScreens.ts +83 -5
  64. package/src/client/host/online/shell.ts +13 -4
  65. package/src/client/host/standalone/shell.ts +37 -1
  66. package/src/server/game/quest/eliteDrops.ts +7 -3
  67. package/src/server/game/riding/nativeTaming.ts +13 -2
  68. package/src/server/host/dedicated/cellHost.ts +14 -2
  69. package/src/server/host/dedicated/cellProtocol.ts +2 -0
  70. package/src/server/host/dedicated/dedicatedRoom.ts +24 -7
  71. package/src/server/host/dedicated/serverMetrics.ts +9 -0
  72. package/src/server/host/dedicated/workerTable.ts +31 -24
  73. package/src/server/host/standalone/serverHost.ts +56 -10
  74. package/src/server/host/standalone/serverProduct.ts +9 -7
  75. package/src/server/host/standalone/serverRuntime.ts +1 -1
  76. package/src/shared/engine/core/framePacing.ts +12 -1
  77. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  78. package/src/shared/game/devColliders.ts +60 -0
  79. package/src/shared/game/devGameplay.ts +41 -0
@@ -111,6 +111,8 @@ export function openDoctor(config: DoctorConfig, exit: DoctorExit | null, earlie
111
111
  const view = rows.get(row.id);
112
112
  if (view === undefined || scope.disposed) return;
113
113
  view.row.dataset['state'] = row.state; view.glyph.textContent = GLYPH[row.state];
114
+ // FM4b mode 42: a warning that stands for a catalogued failure carries its id (`clock-skew`), as the link's cards do
115
+ if (row.failmode === undefined) delete view.row.dataset['failmode']; else view.row.dataset['failmode'] = row.failmode;
114
116
  view.value.textContent = row.state === 'run' ? 'checking…' : row.value;
115
117
  view.hint.textContent = row.hint; view.ms.textContent = row.state === 'run' ? '' : `${String(row.ms)} ms`;
116
118
  };
@@ -5,8 +5,9 @@
5
5
  // turned the link away) and its **hold card** (the banner's sibling: what was tapped, the dial's live progress, what happens by itself).
6
6
  // The look is the Developer prototypes' (src/client/app/failScreens.ts, FM1b); each root carries the catalogue's `data-failmode` ids.
7
7
  import type { Scope } from '@wildshard/engine/app/scope';
8
- import type { LinkCause, LinkProgress, LinkState } from '@wildshard/engine/net/redial';
8
+ import type { LinkAway, LinkCause, LinkProgress, LinkState } from '@wildshard/engine/net/redial';
9
9
  import type { Countdown } from '@wildshard/engine/net/socketFrames';
10
+ import type { TransportStats } from '@wildshard/engine/net/transport';
10
11
  import { diagnosticNow } from '@wildshard/engine/core/clock';
11
12
  import { captureBrowserError } from '@wildshard/engine/telemetry/browserErrors';
12
13
 
@@ -24,6 +25,12 @@ function reportStop(screen: 'link-lost' | 'link-refused', detail: string, report
24
25
  const GIVE_UP_S = 120;
25
26
  /** The Reconnected notice stays this long. */
26
27
  const NOTICE_MS = 2500;
28
+ /** FM4b modes 21 and 22, sampled once a second while live: a pong RTT over this is slow; five in a row spanning this much are unstable. */
29
+ const SLOW_RTT_MS = 250, UNSTABLE_SPAN_MS = 250;
30
+ /** Mode 22: the share of frames the server says it skipped for this client (`lossPct`), not measured TCP loss. */
31
+ const UNSTABLE_LOSS_PCT = 5;
32
+ /** A quality chip shows after this many bad seconds in a row, clears after this many good ones, and shows at most once a minute. */
33
+ const QUALITY_SUSTAIN_S = 5, QUALITY_CLEAR_S = 10, QUALITY_GAP_S = 60;
27
34
  /** After Keep waiting, a blocked tap pulses the banner instead of opening the card again, for this long. */
28
35
  const QUIET_MS = 10_000;
29
36
 
@@ -88,6 +95,8 @@ export interface LinkScreenHooks {
88
95
  readonly doctor?: (from: string) => void;
89
96
  /** Reload this page into the world, taking the seat back (another tab, a turned-away link). */
90
97
  readonly reload: () => void;
98
+ /** FM4b modes 21 and 22: the link's measured pong RTT and the server's reported frame skips (`NetClient.stats`) */
99
+ readonly stats?: () => TransportStats | undefined;
91
100
  /** S13: where a failed link's stop card reports (the browser error tracker; a test observes its own) */
92
101
  readonly report?: typeof captureBrowserError;
93
102
  }
@@ -116,6 +125,8 @@ function bannerFor(state: LinkState, cause: LinkCause, dials: number): { ids: st
116
125
  if (cause === 'silent') return { ids: 'half-open', tone: 'warn', title: 'Reconnecting', line: dials > 0 ? `try ${String(dials + 1)}` : 'no word from the world' };
117
126
  return { ids: 'drop reset', tone: 'warn', title: 'Reconnecting', line: dials > 0 ? `try ${String(dials + 1)}` : 'one moment' };
118
127
  }
128
+ /** How long the page was away, in the card's words. */
129
+ const awayFor = (ms: number): string => ms < 90_000 ? `${String(Math.round(ms / 1000))} s` : `${String(Math.round(ms / 60_000))} min`;
119
130
  const blockedIds = (ids: string): string => ids.split(' ').map(id => `${id}-blocked`).join(' ');
120
131
 
121
132
  /** A card's frame: the scrim, the box, a tag and a title. The caller fills the rest. */
@@ -169,7 +180,7 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
169
180
  parent.append(banner, deploy);
170
181
 
171
182
  let state: LinkState = 'live', reason: string | undefined, wasDown = false, quietUntil = 0, deployLeft = 0, deployTicking = false;
172
- let open: { scope: Scope; root: HTMLElement; kind: 'hold' | 'stop' | 'offline'; paint: () => void; what?: string; chat?: boolean; key?: string } | null = null;
183
+ let open: { scope: Scope; root: HTMLElement; kind: 'hold' | 'stop' | 'offline' | 'away'; paint: () => void; what?: string; chat?: boolean; key?: string } | null = null;
173
184
  const held: { text: string; send: (text: string) => void; drop: () => void }[] = [];
174
185
  const down = (): boolean => state === 'reconnecting' || state === 'resuming';
175
186
 
@@ -180,8 +191,8 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
180
191
  // a card takes the pointer back from the game (desktop pointer lock), so its buttons can be clicked
181
192
  const freePointer = (): void => { if ('exitPointerLock' in document && document.pointerLockElement instanceof Element) document.exitPointerLock(); };
182
193
  const paintBanner = (): void => {
183
- // offline, the card is the screen (FM4b mode 2): no banner under it
184
- const shown = down() && hooks.why() !== 'offline';
194
+ // offline (FM4b mode 2) or back from away (modes 4 and 45), the card is the screen: no banner under it
195
+ const shown = down() && hooks.why() !== 'offline' && hooks.progress().away === undefined;
185
196
  banner.hidden = !shown;
186
197
  // a link that is down takes the top band from the deploy countdown; the countdown comes back with the link
187
198
  deploy.hidden = down() || deployLeft <= 0;
@@ -203,7 +214,7 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
203
214
  /** The hold card: the banner opened up, on a tap it can't carry. It repaints each second from the dial's progress. */
204
215
  const hold = (what: string, chat: boolean): void => {
205
216
  // the offline card already says why nothing goes out; a held chat line still waits for the link
206
- if (open?.kind === 'stop' || open?.kind === 'offline') return;
217
+ if (open?.kind === 'stop' || open?.kind === 'offline' || open?.kind === 'away') return;
207
218
  remember(); open?.scope.dispose(); open = null;
208
219
  const own = scope.child('online.hold'), said = bannerFor(state, hooks.why(), hooks.progress().dials);
209
220
  const title = chat ? 'Your message will send when you\'re back' : state === 'resuming' ? 'Still reconnecting' : hooks.why() === 'restart' ? 'The world is restarting' : 'Not connected yet';
@@ -273,8 +284,72 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
273
284
  root.querySelector('button')?.focus();
274
285
  };
275
286
 
287
+ /**
288
+ * FM4b modes 4 (`background-long`) and 45 (`sleep-wake`): the page was away for over 30 s (out of view, or its clock stopped ticking)
289
+ * and came back to a quiet link. The card says how long the page measured itself away and that the link is being checked; it closes
290
+ * by itself when the link is back. J229: no lost seat or last-save resume is claimed, since the page can't know the world's hold.
291
+ */
292
+ const awayCard = (away: LinkAway): void => {
293
+ if (open?.kind === 'away') { open.paint(); return; }
294
+ remember(); open?.scope.dispose(); open = null;
295
+ const asleep = away.how === 'asleep', own = scope.child('online.away');
296
+ const { root, box } = card(own, asleep ? 'background-long sleep-wake' : 'background-long', 'info', 'Away', 'Welcome back');
297
+ box.append(make('p', 'ws-link-body', `You were away for ${awayFor(away.ms)}, and the link to the world went quiet. We're checking your connection now.`));
298
+ const status = make('ul', 'ws-link-facts'), tries = make('li'), next = make('li');
299
+ status.setAttribute('role', 'status'); status.append(tries, next);
300
+ const paint = (): void => {
301
+ const { dials, nextDialMs } = hooks.progress();
302
+ tries.replaceChildren(ring(), dials > 0 ? `Try ${String(dials + 1)}` : 'Checking your connection');
303
+ next.textContent = nextDialMs !== null ? `Next dial in ${String(Math.ceil(nextDialMs / 1000))} s` : 'Dialling now';
304
+ };
305
+ paint(); own.interval(1000, paint);
306
+ box.append(status, make('p', 'ws-link-auto', 'This closes by itself when you\'re back in. Game taps wait here; we never send one late.'),
307
+ buttons(own, [{ label: 'Try now', primary: true, busy: 'Dialling…', act: () => { hooks.dialNow(); } }, ...doctor(asleep ? 'sleep-wake' : 'background-long')]));
308
+ const details = make('details');
309
+ details.append(make('summary', '', 'Details'), make('p', '', `${asleep ? 'no page clock tick' : 'hidden'} ${awayFor(away.ms)} · link quiet on return · redialling`));
310
+ box.append(details);
311
+ parent.append(root); freePointer();
312
+ open = { scope: own, root, kind: 'away', paint };
313
+ root.querySelector('button')?.focus();
314
+ };
315
+
316
+ /**
317
+ * FM4b modes 21 (`slow`) and 22 (`lossy`): a notice chip in the top band while the link is live and measurably slow or unstable.
318
+ * Only what the page measured: the pong RTT, the spread of the last five, the server's `lossPct`. Never a guessed cause or a made-up
319
+ * percentage. A chip waits while a banner is up (it is the bottom layer) and comes back, if still due, with the link.
320
+ */
321
+ const rtts: number[] = [];
322
+ let slowRun = 0, unstableRun = 0, goodRun = 0, sinceChip = QUALITY_GAP_S, qualityScope: Scope | null = null, qualityKind: 'slow' | 'lossy' | null = null, qualityLine: HTMLElement | null = null;
323
+ const hideQuality = (): void => { qualityScope?.dispose(); qualityScope = null; qualityKind = null; qualityLine = null; };
324
+ const showQuality = (kind: 'slow' | 'lossy', rtt: number): void => {
325
+ if (qualityKind !== kind) {
326
+ hideQuality(); unnotice();
327
+ const own = qualityScope = scope.child('online.quality'), chip = own.ownNode(make('div', 'ws-link ws-link-notice'));
328
+ chip.dataset['failmode'] = kind; chip.dataset['tone'] = 'warn'; chip.setAttribute('role', 'status');
329
+ qualityLine = make('span');
330
+ chip.append(make('b', '', kind === 'slow' ? 'Slow connection' : 'Unstable connection'), qualityLine);
331
+ parent.append(chip);
332
+ qualityKind = kind; sinceChip = 0;
333
+ }
334
+ if (qualityLine !== null) qualityLine.textContent = kind === 'slow' ? `${String(Math.round(rtt))} ms` : 'others may jump';
335
+ };
336
+ const sampleQuality = (): void => {
337
+ sinceChip++;
338
+ const stats = hooks.stats?.();
339
+ if (stats === undefined || state !== 'live') { hideQuality(); slowRun = unstableRun = goodRun = 0; rtts.length = 0; return; }
340
+ const rtt = stats.rttMs;
341
+ if (Number.isFinite(rtt) && rtt > 0) { rtts.push(rtt); if (rtts.length > 5) rtts.shift(); }
342
+ const slow = Number.isFinite(rtt) && rtt > SLOW_RTT_MS;
343
+ const unstable = (rtts.length === 5 && Math.max(...rtts) - Math.min(...rtts) >= UNSTABLE_SPAN_MS) || stats.lossPct >= UNSTABLE_LOSS_PCT;
344
+ slowRun = slow ? slowRun + 1 : 0; unstableRun = unstable ? unstableRun + 1 : 0; goodRun = slow || unstable ? 0 : goodRun + 1;
345
+ const due = slowRun >= QUALITY_SUSTAIN_S ? 'slow' : unstableRun >= QUALITY_SUSTAIN_S ? 'lossy' : null;
346
+ if (qualityKind !== null) { if (goodRun >= QUALITY_CLEAR_S) hideQuality(); else showQuality(due ?? qualityKind, rtt); return; }
347
+ if (due !== null && sinceChip >= QUALITY_GAP_S) showQuality(due, rtt);
348
+ };
349
+ scope.interval(1000, sampleQuality);
276
350
  const link = (next: LinkState, why?: string): void => {
277
351
  state = next; reason = why;
352
+ if (state !== 'live') hideQuality();
278
353
  paintBanner();
279
354
  // down again: the notice goes, and a stop card (lost, after Try again) gives way to the banner
280
355
  if (down()) {
@@ -282,6 +357,9 @@ export function linkScreens(scope: Scope, hooks: LinkScreenHooks, parent: HTMLEl
282
357
  if (open?.kind === 'stop') close();
283
358
  if (hooks.why() === 'offline') { offlineCard(); return; }
284
359
  if (open?.kind === 'offline') close();
360
+ const away = hooks.progress().away;
361
+ if (away !== undefined) { awayCard(away); return; }
362
+ if (open?.kind === 'away') close();
285
363
  // a hold card follows its banner: a new cause (silent to restart) or 35 s down redraws it, else it just ticks
286
364
  if (open?.kind === 'hold' && open.key !== `${state}:${hooks.why()}` && open.what !== undefined) hold(open.what, open.chat === true); else open?.paint();
287
365
  return;
@@ -20,6 +20,7 @@ import { voiceUi } from './voiceUi';
20
20
  import { fetchSignedRelease, releaseToDial, type ReleaseKeep } from './release';
21
21
  import { newBuildPanel } from './reconnectStrip';
22
22
  import { linkScreens } from './linkScreens';
23
+ import { diagnosticNow } from '@wildshard/engine/core/clock';
23
24
 
24
25
  /** `ready` with this byte is a clean quit: the door drops the body at once instead of holding it (server `socketPump.ts` `LEAVE_FLAG`). */
25
26
  const LEAVE_FLAG = 1;
@@ -71,8 +72,8 @@ export interface OnlineShell {
71
72
  readonly booted: Promise<{ readonly tick: number; readonly restored: boolean }>;
72
73
  /** The page has loaded: the door may seat the body (E7.2's step 4). */
73
74
  ready: () => void;
74
- /** The page came back into view: check the link now. */
75
- visible: () => void;
75
+ /** The page came back into view after `hiddenMs` out of it (FM4b mode 4): check the link now. */
76
+ visible: (hiddenMs?: number) => void;
76
77
  retry: () => void;
77
78
  /** FM4: the dial's progress and why the link is down, for the screens that show them; dial now, from a hold card. */
78
79
  progress: () => LinkProgress;
@@ -153,7 +154,7 @@ export function connectOnline(config: OnlineConfig, view: OnlineView): OnlineShe
153
154
  client.hello(config.build, config.identity);
154
155
  const tickOf = (): number => client.latest?.tick ?? 0, idle = (): void => undefined;
155
156
  return { client, voice, redials: true, booted, ready: () => { loaded = true; unseated?.control('ready'); unseated = null; },
156
- visible: () => { redial.check(); }, retry: () => { redial.retry(); }, progress: () => redial.progress, why: () => redial.why, dialNow: () => { redial.dialNow(); },
157
+ visible: hiddenMs => { redial.check(hiddenMs); }, retry: () => { redial.retry(); }, progress: () => redial.progress, why: () => redial.why, dialNow: () => { redial.dialNow(); },
157
158
  pause: idle, resume: idle, hold: idle, bossGod: idle, hardHits: idle, place: idle, raise: idle,
158
159
  // The door hears a quit on any link of this build: seated, still admitted, or handed a held body back. A link that is down (a redial's
159
160
  // wait) gets a fresh one to say it on, so a held body goes too. No redial follows: the page is going.
@@ -312,6 +313,8 @@ export async function startOnline(config: StartOnline): Promise<OnlineShell> {
312
313
  // Play here / Play again reload into the world: the tap that brought the player here comes along (QA row 16)
313
314
  reload: () => { entering(link.loaded); void reloadByHand(); },
314
315
  progress: () => shellNow?.progress() ?? { dials: 0, nextDialMs: null, downMs: 0 }, why: () => shellNow?.why() ?? 'closed',
316
+ // FM4b modes 21 and 22: the Slow and Unstable chips read the link's own measurements
317
+ stats: () => shellNow?.client.stats,
315
318
  });
316
319
  // `reload` is the one ending a screen doesn't answer: the page reloads into the world's build, once (J174)
317
320
  const ended = async (): Promise<void> => { if (!await stale()) newBuildPanel(scope, stale, () => { entering(link.loaded); void reloadByHand(); }); };
@@ -342,6 +345,12 @@ export async function startOnline(config: StartOnline): Promise<OnlineShell> {
342
345
  const chat = chatLines(scope, shell.client, document.body, screens.holdChat);
343
346
  voiceUi(scope, new VoiceChat(scope, shell.voice), chat);
344
347
  scope.listen(window,'pagehide',()=>{shell.flushRecords();});
345
- scope.listen(document, 'visibilitychange', () => { if (document.visibilityState === 'visible') { shell.visible(); screens.visible(); } });
348
+ // FM4b mode 4: how long the page was out of view rides the check, so a long absence back to a quiet link opens Welcome back
349
+ let hiddenAt: number | null = document.visibilityState === 'hidden' ? diagnosticNow() : null;
350
+ scope.listen(document, 'visibilitychange', () => {
351
+ if (document.visibilityState !== 'visible') { hiddenAt ??= diagnosticNow(); return; }
352
+ const hiddenMs = hiddenAt === null ? 0 : diagnosticNow() - hiddenAt;
353
+ hiddenAt = null; shell.visible(hiddenMs); screens.visible();
354
+ });
346
355
  return { ...shell, dispose: () => { scope.dispose(); shell.dispose(); } };
347
356
  }
@@ -12,10 +12,17 @@ import type { SaveStorage } from '@wildshard/engine/saves/store';
12
12
  import { ServerMessageSchema, ShellMessageSchema, type ProbedRow, type ServerMessage, type ShellMessage } from '@wildshard/format/standaloneControl';
13
13
  import { answerHeldReads, type HeldRead } from '../../../shared/host/standalone/heldReads';
14
14
  import type { HarnessFlag, HarnessGod, HarnessHits, HarnessJoin, HarnessMove, HarnessPlace } from '../../../shared/host/standalone/harnessPlace';
15
- import type { DevBox, DevCollidersMessage } from '@wildshard/engine/game/devColliders';
15
+ import type { DevBox, DevCollidersMessage, DevGround, DevGroundMessage } from '@wildshard/engine/game/devColliders';
16
+ import { isDevRestart, type DevGameplay, type DevPlace, type DevRestarted, type DevRestartMessage } from '@wildshard/engine/game/devGameplay';
16
17
  import type { ServerWorkerStart } from '../../../server/host/standalone/serverRuntime';
17
18
  import { WorkerLoopback } from '../../../shared/host/standalone/workerLoopback';
18
19
 
20
+ declare global { interface Window {
21
+ /** SHARD-SOURCE AP18 (DEVSERVER): the dev hook's ground for the in-page server */ __workerClientDevGround?: (ground: DevGround) => void;
22
+ /** SHARD-SOURCE AP19 (DEVSERVER): the dev hook's soft restart of the in-page server, on a new link this page's client rejoins */
23
+ __workerClientDevRestart?: (gameplay: DevGameplay, at: DevPlace | null) => Promise<DevRestarted>;
24
+ } }
25
+
19
26
  /** What the server should run and where the page keeps saves. */
20
27
  export interface StandaloneConfig {
21
28
  readonly slug: string;
@@ -69,6 +76,8 @@ export interface StandaloneShell {
69
76
  join: (id: string, x: number, y: number, z: number) => { readonly client: NetClient; readonly move: (x: number, y: number, z: number) => void };
70
77
  /** SHARD-SOURCE AP5: a watched part's solid boxes for the server's world (DEVSERVER pages only; elsewhere it does nothing). */
71
78
  devColliders: (name: string, boxes: readonly DevBox[]) => void;
79
+ /** SHARD-SOURCE AP19: restart the in-page server's world on new gameplay rows, its player at `at`; this client rejoins it (DEVSERVER pages only). */
80
+ devRestart: (gameplay: DevGameplay, at: DevPlace | null) => Promise<DevRestarted>;
72
81
  dispose: () => void;
73
82
  }
74
83
 
@@ -76,6 +85,8 @@ function applyWrite(storage: SaveStorage, key: string, value: string | null): bo
76
85
  try { if (value === null) storage.removeItem(key); else storage.setItem(key, value); return true; } catch { return false; }
77
86
  }
78
87
 
88
+ /** AP19: how long the page waits for the in-page server's answer to a soft restart before it counts as refused. */
89
+ const DEV_RESTART_TIMEOUT_MS = 20_000;
79
90
  const SaveDocument = v.object({ keys: v.record(v.string(), v.unknown()), reset: v.optional(v.number()) });
80
91
  /** Apply only entries the worker changed since its last document. The page owns discovery and cosmetic wear;
81
92
  * a server pack/pending-drop write must leave those newer entries standing. Resets still replace the document. */
@@ -129,6 +140,30 @@ export function connectStandalone(config: StandaloneConfig, control: MessagePort
129
140
  const visibility = (): void => { if (!held) post({ kind: document.visibilityState === 'hidden' ? 'pause' : 'resume' }); };
130
141
  const scope = new Scope('standalone.shell');
131
142
  if (typeof document !== 'undefined') scope.listen(document, 'visibilitychange', visibility);
143
+ // SHARD-SOURCE AP18: `wildshard watch`'s ground for this server, from the page's dev hook (DEVSERVER pages only)
144
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && harness !== undefined && typeof window !== 'undefined')
145
+ scope.expose(window, '__workerClientDevGround', (ground: DevGround) => { harness.postMessage({ wildshardDevGround: ground } satisfies DevGroundMessage, []); });
146
+ // SHARD-SOURCE AP19: the soft restart. The server takes a new link with the restart; this page's client rejoins on it at once
147
+ // (its hello waits in the port until the new world listens), as an online page does when its server comes back.
148
+ // One at a time, and only a message the worker takes: anything else answers `ok: false` before the client leaves its link, so
149
+ // the page reloads instead of sitting on a link nothing serves. A worker that never answers counts as a refusal too.
150
+ let restarting = false;
151
+ const devRestart = (gameplay: DevGameplay, at: DevPlace | null): Promise<DevRestarted> => new Promise<DevRestarted>(resolve => {
152
+ if (!(typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__) || harness === undefined) { resolve({ ok: false, ms: 0, reason: 'not a DEVSERVER page with an in-page server' }); return; }
153
+ const message: DevRestartMessage = { wildshardDevRestart: gameplay, at };
154
+ if (!isDevRestart(message)) { resolve({ ok: false, ms: 0, reason: 'the worker takes only the dev gameplay sections and a finite place' }); return; }
155
+ if (restarting) { resolve({ ok: false, ms: 0, reason: 'a restart is already running' }); return; }
156
+ restarting = true;
157
+ const line = new MessageChannel(), reply = new MessageChannel(), waiting: { timer?: ReturnType<typeof scope.timeout> } = {};
158
+ const settle = (answer: DevRestarted): void => { if (!restarting) return; restarting = false; scope.cancelTimer(waiting.timer); reply.port1.close(); resolve(answer); };
159
+ waiting.timer = scope.timeout(DEV_RESTART_TIMEOUT_MS, () => { settle({ ok: false, ms: DEV_RESTART_TIMEOUT_MS, reason: 'the in-page server did not answer the restart' }); });
160
+ reply.port1.onmessage = (event: MessageEvent<DevRestarted>): void => { settle(event.data); };
161
+ const link = new WorkerLoopback(line.port1);
162
+ link.onClose(reason => { if (reason === 'reload') config.refused?.(); });
163
+ client.rejoin(link);
164
+ harness.postMessage(message, [line.port2, reply.port2]);
165
+ });
166
+ if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__ && harness !== undefined && typeof window !== 'undefined') scope.expose(window, '__workerClientDevRestart', devRestart);
132
167
  post({ kind: 'boot', slug: config.slug, base: config.base, build: config.serverBuild ?? config.build, savePrefix: config.savePrefix, saves: documents, ...(config.lone === true ? { lone: true } : {}) });
133
168
  return { client, transport, booted: bootPromise,
134
169
  ready: () => { post({ kind: 'ready' }); }, pause: () => { post({ kind: 'pause' }); }, resume: () => { post({ kind: 'resume' }); },
@@ -140,6 +175,7 @@ export function connectStandalone(config: StandaloneConfig, control: MessagePort
140
175
  bossGod: () => { harness?.postMessage({ god: true } satisfies HarnessGod, []); },
141
176
  raise: flag => { harness?.postMessage({ flag } satisfies HarnessFlag, []); },
142
177
  devColliders: (name, boxes) => { if (typeof __DEVSERVER__ === 'boolean' && __DEVSERVER__) harness?.postMessage({ wildshardDevColliders: name, boxes } satisfies DevCollidersMessage, []); },
178
+ devRestart,
143
179
  join: (id, x, y, z) => {
144
180
  const line = new MessageChannel(), second = new NetClient(new WorkerLoopback(line.port1));
145
181
  harness?.postMessage({ join: id, x, y, z } satisfies HarnessJoin, [line.port2]);
@@ -21,7 +21,7 @@ export const eliteSkinFlag = (id: string): string => `elite.${id}.skin`;
21
21
  *
22
22
  * SERVER-CELLS SC10 (J328): a served world is never rebuilt, so there the skin is each player's own: a kill lays the orb out while a
23
23
  * player present has not taken it, a press takes it for the presser (a flag in their own book, which goes with their save), and an
24
- * owner's press is refused. The lair's world record (`skinTaken`) is a page's or a tape's alone.
24
+ * owner's press is refused. The orb stays until every player present has taken theirs. The lair's world record (`skinTaken`) is a page's or a tape's alone.
25
25
  */
26
26
  export function eliteDrops<S extends EliteCoreScript<Body>>(host: SimHost): { readonly hooks: EliteCoreHooks<S>; readonly bind: (core: EliteCore<S>) => void } {
27
27
  const routes = actRoutes(host);
@@ -35,10 +35,14 @@ export function eliteDrops<S extends EliteCoreScript<Body>>(host: SimHost): { re
35
35
  entry.drop = { x: at.x, y: at.y + ITEM_PICKUP_HOVER, z: at.z };
36
36
  routes.claims.set(`${def.id}.reward`, player => {
37
37
  const feet = host.players.get(player)?.position, { drop } = entry;
38
- if (feet === undefined || drop === null || (served && owns(player, def.id))) return;
38
+ if (feet === undefined || drop === null) return;
39
+ // an owner's press takes nothing; once nobody present lacks the skin, it clears the orb (review SHOULD: no orb left standing)
40
+ if (served && owns(player, def.id)) { if (!lacking(def.id)) entry.drop = null; return; }
39
41
  if (pickPrompt([{ position: { x: drop.x, y: drop.y + PROMPT_ABOVE, z: drop.z }, radius: PROMPT_RADIUS }], { x: feet.x, y: feet.y + REACH_EYE, z: feet.z }, host.physics) === undefined) return;
42
+ // SC10 review: in a served world the orb stays while anyone present still lacks the skin, so the first press takes it for the
43
+ // presser only, not for everyone who shared the kill
44
+ if (served) { questBooks(host).of(player).flags.set(eliteSkinFlag(def.id)); if (!lacking(def.id)) entry.drop = null; return; }
40
45
  entry.drop = null;
41
- if (served) { questBooks(host).of(player).flags.set(eliteSkinFlag(def.id)); return; }
42
46
  const saved = core?.record(def.id);
43
47
  if (saved !== undefined) saved.skinTaken = true;
44
48
  core?.save();
@@ -46,6 +46,8 @@ export interface NativeTamingControls {
46
46
  readonly press: (id: string, press: NativeTamingPress) => void;
47
47
  /** A player's own session, once they have one. */
48
48
  readonly sessionOf: (id: string) => NativeTamingOwner | undefined;
49
+ /** SC10 review: this player's seat emptied (a served world's lead seat, parked): its bonded horses go and its session starts wild. */
50
+ readonly release: (id: string) => void;
49
51
  }
50
52
  export interface NativeTamingOwner {
51
53
  readonly scope: SimHost['scope'];
@@ -161,7 +163,9 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
161
163
  };
162
164
  const originalUpdate = law.update.bind(law);
163
165
  const session: TamingSeat = { player, law, get shake() { return shake; }, get roll() { return roll; }, holdOffer: held => { heldOffer = held; },
164
- release: () => { for (const id of mine) { const a = poseRows.find(row => row.entityId === id); if (a === undefined) mine.delete(id); else retireBonded(a); } }, whistle: () => {
166
+ // SC10 review: a bonded horse is a mountable too (`addMountable` on adoption); it leaves the mounted owner's rows before it retires,
167
+ // or the next mounted step finds its pose with no body ("Missing mounted pose actor") and fails the worker
168
+ release: () => { for (const id of mine) { const a = poseRows.find(row => row.entityId === id); if (a === undefined) { mine.delete(id); continue; } if (mounted.mountables.includes(a)) mounted.removeMountable(id); retireBonded(a); } }, whistle: () => {
165
169
  const horse = law.companion;
166
170
  if (!mounted.mounted && horse !== null && horse.mem['whistle'] === 1 && mounted.canRide(horse.entityId) && horse.position.distanceTo(player.position) < 150) calling = 30;
167
171
  }, tick: (dt, read) => {
@@ -202,6 +206,8 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
202
206
  sessions.set(player.id, session); return session;
203
207
  };
204
208
  const first = sessionFor(firstSeat.player), { law } = first;
209
+ // SC10 review: the lead seat's session as a fresh world gives it, for when its player leaves a served world (the seat is parked)
210
+ const fresh = first.save();
205
211
  const others = (): TamingSeat[] => [...sessions.values()].filter(session => session !== first);
206
212
  host.events.on('creature.signal', ({ name, x, z }) => { for (const session of sessions.values()) session.law.noteEvent(name, x, z); }, host.scope);
207
213
  host.events.on('weapon.impact', ({ point }) => {
@@ -264,7 +270,12 @@ export function installNativeTaming(host: SimHost, context: NativeTamingContext,
264
270
  },
265
271
  }, 'afterBodies');
266
272
  host.scope.onDispose(() => { for (let i = 0; i < 64; i++) { const actor = poseRows[i]; if (actor === undefined) break; poses.delete(actor.entityId); } poseRows.length = 0; installed.delete(host); });
267
- controls.set(host, { sessionOf: id => sessions.get(id)?.law, press: (id, press) => {
273
+ controls.set(host, { sessionOf: id => sessions.get(id)?.law, release: id => {
274
+ // an emptied seat keeps no one's taming: its horses go as any leaver's do, and the lead's own session starts wild again
275
+ const session = sessions.get(id); if (session === undefined) return;
276
+ session.release(); pending.delete(id);
277
+ if (session === first) first.load(fresh, []); else sessions.delete(id);
278
+ }, press: (id, press) => {
268
279
  if (!host.players.has(id)) throw new RangeError(`Unknown taming player ${id}`);
269
280
  pending.set(id, { ...pending.get(id), ...press });
270
281
  } });
@@ -84,6 +84,8 @@ function installCellIdentity(): void {
84
84
  export function runCells(port: CellPort, options: CellHostOptions): { dispose: () => void } {
85
85
  const scope = new Scope('dedicated.worker'), started = diagnosticNow(), cells = new Map<string, Cell>();
86
86
  let clock: ServerClock | undefined, disposed = false, ready = false, ticks: number[] = [], ticked = 0, readAt = started, dropsAt = 0;
87
+ /** SC8: each awake cell's own tick time since the last reading (ms summed, ticks counted), so a bench can weigh cells by awake cost. */
88
+ let spent = new Map<string, { ms: number; ticks: number }>();
87
89
  const post = (news: WorkerNews): void => { port.postMessage(news); };
88
90
  const fail = (error: unknown): void => { clock?.pause(); post({ kind: 'failed', reason: error instanceof Error ? error.message : String(error) }); };
89
91
  // GC15: the road this worker hosts, once its cells are open, and what its cells need of it.
@@ -144,7 +146,16 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
144
146
  };
145
147
  const step = (): void => {
146
148
  const begun = diagnosticNow();
147
- try { for (const { room } of cells.values()) if (room.taken > 0) room.tick(); if (road !== undefined && road.taken > 0) road.tick(); } catch (error) { fail(error); return; }
149
+ try {
150
+ for (const { slug, room } of cells.values()) {
151
+ if (room.taken === 0) continue;
152
+ const at = diagnosticNow();
153
+ room.tick();
154
+ const own = spent.get(slug) ?? { ms: 0, ticks: 0 };
155
+ own.ms += diagnosticNow() - at; own.ticks++; spent.set(slug, own);
156
+ }
157
+ if (road !== undefined && road.taken > 0) road.tick();
158
+ } catch (error) { fail(error); return; }
148
159
  ticks.push(diagnosticNow() - begun); ticked++;
149
160
  if (ticks.length > TICKS_KEPT) ticks.shift();
150
161
  };
@@ -156,8 +167,9 @@ export function runCells(port: CellPort, options: CellHostOptions): { dispose: (
156
167
  const row: WorkerReading = { cells: rooms.length, awake: rooms.filter(room => room.taken > 0).length, players: sum(room => room.taken - room.holding) + onRoad, held: sum(room => room.holding) + heldOnRoad, ticks: ticked, ticksPerSecond: ticks.length / ((now - readAt) / 1000),
157
168
  p50: percentile(sorted, 0.5), p95: percentile(sorted, 0.95), p99: percentile(sorted, 0.99), max: sorted.at(-1) ?? 0, drops: (clock?.drops ?? 0) - dropsAt, rss: memory.rss, heap: memory.heapUsed,
158
169
  refused: sum(room => room.net.stats.refused), dropped: sum(room => room.net.stats.dropped), frameBytes: sum(room => room.net.stats.frameBytes), eventBytes: sum(room => room.net.stats.eventBytes),
170
+ ...(spent.size === 0 ? {} : { cellMs: Object.fromEntries([...spent].map(([slug, own]) => [slug, own.ms / own.ticks])) }),
159
171
  ...(memory.external === undefined ? {} : { external: memory.external }), ...(memory.arrayBuffers === undefined ? {} : { arrayBuffers: memory.arrayBuffers }), ...(options.lag === undefined ? {} : { lag: options.lag() }) };
160
- readAt = now; dropsAt = clock?.drops ?? 0; ticks = [];
172
+ readAt = now; dropsAt = clock?.drops ?? 0; ticks = []; spent = new Map();
161
173
  post({ kind: 'reading', reading: row });
162
174
  };
163
175
  /** One start-over at a time on this worker: each boot stalls the clock of every other cell here, so they never pile up. */
@@ -56,6 +56,8 @@ export interface WorkerReading {
56
56
  /** SERVER-CELLS SC1: this worker thread's own memory beyond its heap, and its event-loop lag in ms (`loopLag`), when it measures them. */
57
57
  readonly external?: number; readonly arrayBuffers?: number;
58
58
  readonly lag?: { readonly p50: number; readonly p99: number; readonly max: number };
59
+ /** SERVER-CELLS SC8: each cell that ticked in this reading, its mean ms per tick (its awake cost; `workerTable`'s weights come from these). */
60
+ readonly cellMs?: Readonly<Record<string, number>>;
59
61
  }
60
62
  /** What a cell tells the worker it runs on. */
61
63
  export type RoomNews =
@@ -18,6 +18,7 @@ import type { FallFloor } from '../standalone/fallFloor';
18
18
  import { ledgerFilings } from '../standalone/ledgerFilings';
19
19
  import { questBooks } from '@wildshard/engine/quest/players';
20
20
  import { mountedPlayerOf } from '@wildshard/engine/game/riding/native';
21
+ import { nativeTamingControls } from '@wildshard/engine/game/riding/nativeTaming';
21
22
  import { carryDoc, exportPlayer, importPlayer, parseDoc, PLAYER_DOC_VERSION, type PlayerDoc } from './playerDoc';
22
23
  import { PlayerStore, recoverPlayer } from './playerStore';
23
24
  import { ShopGate } from './shopGate';
@@ -44,6 +45,8 @@ const DEBOUNCE_MS = 1000, EVERY_MS = 60_000;
44
45
  /** A player who holds a seat, with or without a live link. */
45
46
  interface Seat {
46
47
  readonly device: string; readonly name: string; readonly body: string; readonly store: PlayerStore; readonly fall: FallFloor;
48
+ /** SC10: this device's own body id (`entry.body`), which `body` is unless it holds the lead seat: what it was paid here is kept under it. */
49
+ readonly own: string;
47
50
  transport: Transport | null;
48
51
  /** The link's client in this room's `NetRoom`, and how to stop hearing its close, while it stands. */
49
52
  client: number | null; closeOff: (() => void) | null;
@@ -216,9 +219,11 @@ export class DedicatedRoom implements CrossTarget {
216
219
  } }
217
220
  catch (error) { return `recovery: ${String(error)}`; }
218
221
  const store = new PlayerStore(doc?.store ?? {}, () => { const own = this.seats.get(entry.device); if (own !== undefined) this.dirty(own); });
219
- const seat: Seat = { device: entry.device, name: entry.name, read: entry.doc, body, store, fall: this.cell.fallFloor(), transport, client: null, closeOff: null, holdEnds: null, seq: entry.seq, receipted: doc?.ledger.serial ?? 0, dirtyAt: null, savedAt: now, stand: null, version: 0 };
222
+ const seat: Seat = { device: entry.device, name: entry.name, read: entry.doc, body, own: entry.body, store, fall: this.cell.fallFloor(), transport, client: null, closeOff: null, holdEnds: null, seq: entry.seq, receipted: doc?.ledger.serial ?? 0, dirtyAt: null, savedAt: now, stand: null, version: 0 };
220
223
  this.seats.set(entry.device, seat); this.bodies.set(body, seat); this.departed.delete(body);
221
- if (lead) this.unparkLead();
224
+ // SC10 review: the lead seat takes back what this device was paid here when it last left (kept under its own id)
225
+ const away = this.departed.get(entry.body);
226
+ if (lead) { this.departed.delete(entry.body); this.movePaid(entry.body, LEAD_SEAT); this.unparkLead(); }
222
227
  // Two who join together would otherwise stand inside each other.
223
228
  const aside = SPAWN_ASIDE[(this.joined++) % SPAWN_ASIDE.length] ?? 0, stand = { ...spawn, x: spawn.x + aside };
224
229
  const player = lead ? this.lead : host.addPlayer(body, at ?? doc?.at ?? stand, at?.yaw ?? doc?.at.yaw ?? spawn.yaw);
@@ -230,7 +235,8 @@ export class DedicatedRoom implements CrossTarget {
230
235
  catch (error) {
231
236
  // No save or live link is installed on a failed continuation. Keep the durable copies intact.
232
237
  this.seats.delete(entry.device); this.bodies.delete(body); this.cell.owned.drop(body); book.drop(body);
233
- if (lead) this.clearLead(); else host.removePlayer(body);
238
+ // review MUST: a failed continuation keeps what this device was paid here, on the clock it left on
239
+ if (lead) this.clearLead(entry.body, away ?? now); else host.removePlayer(body);
234
240
  return `doc: ${String(error)}`;
235
241
  }
236
242
  return seat;
@@ -339,7 +345,7 @@ export class DedicatedRoom implements CrossTarget {
339
345
  this.playerRefusals.delete(seat.body);
340
346
  actRoutes(this.host).identities.delete(seat.body);
341
347
  this.seats.delete(seat.device); this.bodies.delete(seat.body); this.cell.owned.drop(seat.body); this.book.drop(seat.body);
342
- if (seat.body === LEAD_SEAT) this.clearLead(); else { this.host.removePlayer(seat.body); this.departed.set(seat.body, this.options.now()); }
348
+ if (seat.body === LEAD_SEAT) this.clearLead(seat.own, this.options.now()); else { this.host.removePlayer(seat.body); this.departed.set(seat.body, this.options.now()); }
343
349
  this.options.post({ kind: 'left', device: seat.device, seats: this.seats.size });
344
350
  }
345
351
  private flushRefusals(): void {
@@ -353,12 +359,23 @@ export class DedicatedRoom implements CrossTarget {
353
359
  transport?.close('refused');
354
360
  }
355
361
  }
356
- /** The seat goes back to how boot left it, and what it was paid goes with who earned it: the next player's bounty is their own (J105). */
357
- private clearLead(): void {
362
+ /**
363
+ * The seat goes back to how boot left it, and what it was paid goes with who earned it: the next player's bounty is their own (J105).
364
+ * SC10 review: it goes under the leaver's own id, as any other body's stays, so a lead who bounces across an edge cannot re-farm a
365
+ * bounty; it is forgotten `FORGET_PAID_MS` after `left`. The seat's taming session goes too: the next lead starts wild.
366
+ */
367
+ private clearLead(own: string, left: number): void {
358
368
  actRoutes(this.host).identities.delete(LEAD_SEAT);
359
- this.forgetPaid(LEAD_SEAT);
369
+ this.movePaid(LEAD_SEAT, own);
370
+ this.departed.set(own, left);
371
+ nativeTamingControls(this.host)?.release(LEAD_SEAT);
360
372
  importPlayer(this.host, this.lead, this.blank); this.parkLead();
361
373
  }
374
+ /** What `from` was paid here is `to`'s now. */
375
+ private movePaid(from: string, to: string): void {
376
+ const { ledgerDedupe } = this.host.slots, paid = `${LOOT_ROW}${from}:`;
377
+ for (let index = 0; index < ledgerDedupe.length; index++) { const row = ledgerDedupe[index]; if (row?.startsWith(paid) === true) ledgerDedupe[index] = `${LOOT_ROW}${to}:${row.slice(paid.length)}`; }
378
+ }
362
379
  /** What a body was paid here goes: the next one to hold it, or its own return after a long while, earns afresh (J105, SC10). */
363
380
  private forgetPaid(body: string): void {
364
381
  const { ledgerDedupe } = this.host.slots, paid = `${LOOT_ROW}${body}:`;
@@ -40,6 +40,9 @@ export class ServerMetrics {
40
40
  private readonly lag: Gauge<'thread' | 'quantile'>;
41
41
  private readonly memory: Gauge<'thread' | 'kind'>;
42
42
  private readonly tick: Gauge<'worker' | 'quantile'>;
43
+ private readonly cellTick: Gauge<'cell'>;
44
+ /** Each worker's cells awake in its last reading. */
45
+ private readonly ticking = new Map<number, ReadonlySet<string>>();
43
46
  private readonly rate: Gauge<'worker'>;
44
47
  private readonly drops: Counter<'worker'>;
45
48
  private readonly awake: Gauge<'worker'>;
@@ -60,6 +63,7 @@ export class ServerMetrics {
60
63
  this.memory = new Gauge({ name: 'wildshard_thread_memory_bytes', help: 'Each thread\'s own heap, external and array-buffer bytes (a worker\'s from its last reading).', labelNames: ['thread', 'kind'], registers,
61
64
  collect() { const own = process.memoryUsage(); this.set({ thread: 'main', kind: 'heap' }, own.heapUsed); this.set({ thread: 'main', kind: 'external' }, own.external); this.set({ thread: 'main', kind: 'arrayBuffers' }, own.arrayBuffers); } });
62
65
  this.tick = new Gauge({ name: 'wildshard_tick_seconds', help: 'Tick time per worker over its last 10 s reading.', labelNames: ['worker', 'quantile'], registers });
66
+ this.cellTick = new Gauge({ name: 'wildshard_cell_tick_seconds', help: 'SC8: each awake cell\'s mean tick time over its worker\'s last 10 s reading (its awake cost).', labelNames: ['cell'], registers });
63
67
  this.rate = new Gauge({ name: 'wildshard_ticks_per_second', help: 'Ticks per second per worker over its last 10 s reading.', labelNames: ['worker'], registers });
64
68
  this.drops = new Counter({ name: 'wildshard_tick_drops_total', help: 'Ticks a worker\'s clock dropped to catch up.', labelNames: ['worker'], registers });
65
69
  this.registry.registerMetric(new Gauge({ name: 'wildshard_cells_resident', help: 'Cells open in memory, per worker (from /health\'s table).', labelNames: ['worker'], registers: [],
@@ -83,6 +87,11 @@ export class ServerMetrics {
83
87
  const worker = String(index);
84
88
  for (const [quantile, ms] of [['0.5', row.p50], ['0.95', row.p95], ['0.99', row.p99], ['1', row.max]] as const) this.tick.set({ worker, quantile }, ms / 1000);
85
89
  this.rate.set({ worker }, row.ticksPerSecond);
90
+ // a cell gone back to sleep stops reporting its last awake cost (review SHOULD)
91
+ const awake = new Set(Object.keys(row.cellMs ?? {}));
92
+ for (const cell of this.ticking.get(index) ?? []) if (!awake.has(cell)) this.cellTick.remove({ cell });
93
+ this.ticking.set(index, awake);
94
+ for (const [cell, ms] of Object.entries(row.cellMs ?? {})) this.cellTick.set({ cell }, ms / 1000);
86
95
  this.drops.inc({ worker }, Math.max(0, row.drops));
87
96
  this.awake.set({ worker }, row.awake);
88
97
  this.players.set({ worker }, row.players);
@@ -1,10 +1,20 @@
1
1
  // J182, J185: which worker runs which cell. Fixed at startup, never by load, and a cell never moves. How many workers, and how many cells fit
2
2
  // one, is a startup setting a bench decides (E7.3e), so nothing here is a promise about the number.
3
+ // SERVER-CELLS SC8: the table is weighed by each cell's measured awake cost (its mean tick ms with a player in it), not by name.
3
4
 
4
- /** Each of these has a worker to itself while the count allows. */
5
- const DEDICATED: readonly string[] = ['nalati-grasslands', 'nine-dragon-stack', 'pine-hollow', 'driftwood-isle'];
6
- /** These share one. */
7
- const SHARED: readonly (readonly string[])[] = [['sunscar-dunes', 'far-reach']];
5
+ /**
6
+ * SC8: each cell's awake cost, ms per tick with one player in it: `cell-mem-bench.mjs`'s `cellMs` (the worker readings' per-cell
7
+ * tick time; `/metrics` serves the same as `wildshard_cell_tick_seconds{cell}`), COSTS_MEASURED. Re-measure when a shard grows.
8
+ */
9
+ const COST: ReadonlyMap<string, number> = new Map<string, number>([
10
+ ['nalati-grasslands', 2.741], ['driftwood-isle', 1.755], ['pine-hollow', 1.594], ['blender-template', 1.311], ['far-reach', 0.866], ['template-2', 0.746], ['sunscar-dunes', 0.682], ['nine-dragon-stack', 0.63], ['pastel-plain', 0.608], ['open-plot-0-3', 0.606], ['ink-cel-valley', 0.576], ['open-plot-0-4', 0.374], ['open-plot-4-2', 0.281], ['open-plot-4-4', 0.269], ['open-plot-4-3', 0.244], ['open-plot-4-0', 0.221], ['open-plot-0-0', 0.211], ['open-plot-4-1', 0.206], ['open-plot-2-4', 0.202], ['open-plot-2-0', 0.195], ['open-plot-0-2', 0.186], ['open-plot-3-4', 0.184], ['open-plot-3-0', 0.183], ['open-plot-1-0', 0.18], ['open-plot-0-1', 0.175],
11
+ ]);
12
+ /** SC8: the measurement the costs come from. */
13
+ export const COSTS_MEASURED = 'opus-cells3, 2026-11-14 ~02:00 Cancún: cell-mem-bench --remote wildshard-agent --counts 25, release 7251ca24 (v0.1.19) packs, a bot in every cell';
14
+ /** A cell with no measured cost (a new Open Plot) weighs as a measured Open Plot does. */
15
+ const UNMEASURED = 0.206;
16
+ /** Cells that always share a worker. */
17
+ const TOGETHER: readonly (readonly string[])[] = [['sunscar-dunes', 'far-reach']];
8
18
  /** What each channel starts on (J185). Production tries 4 and goes to 8 only if the bench says it doesn't fit. Staging runs on pinned CPUs. The cap is per grid (J182). */
9
19
  const SETTINGS: Readonly<Record<string, { readonly workers: number; readonly seats: number }>> = { production: { workers: 4, seats: 32 }, staging: { workers: 2, seats: 16 } };
10
20
 
@@ -25,28 +35,25 @@ export function worldCrossing(value: string | undefined): boolean {
25
35
  throw new Error(`WORLD_CROSSING=${value}: only worker (the default) or off`);
26
36
  }
27
37
 
38
+ /** SC8: a cell's awake cost in ms per tick (measured, or an Open Plot's when it has none). */
39
+ export function cellCost(slug: string): number { return COST.get(slug) ?? UNMEASURED; }
40
+
28
41
  /**
29
- * The table for the cells this server opens: one row a worker, at most `workers` rows. Only an open cell takes a row, so one cell is one
30
- * worker. Named rows go first; the rest are shared, and if the count runs out the last row takes the named cells left over.
31
- * GC13: the unnamed cells then move from that last row to the rows holding fewest, so no worker holds more than its share plus one.
32
- * (Before, the last row kept them all: staging's 2 workers held Nalati alone and the other 25 cells together.) A named cell stays
33
- * where it was, so Driftwood's crossings to Sunscar and Sky Reach stay on one worker; a crossing between workers is GC15's move.
42
+ * The table for the cells this server opens: one row a worker, at most `workers` rows, no empty row. SC8: heaviest first, each cell (or
43
+ * group that shares a worker) goes to the row whose awake cost is lowest so far (fewest cells on a tie, then the first row), so the
44
+ * busiest worker carries as little awake cost as the cells allow. One cell is one worker; GC31: one worker holds every cell. A crossing
45
+ * between workers is GC15's move, so no cell needs a neighbour's worker.
34
46
  */
35
47
  export function workerTable(cells: readonly string[], workers: number): readonly (readonly string[])[] {
36
- const open = new Set(cells), named = new Set([...DEDICATED, ...SHARED.flat()]), rest = cells.filter(slug => !named.has(slug)).sort();
37
- const rows = [...DEDICATED.map(slug => [slug]), ...SHARED].map(row => row.filter(slug => open.has(slug))).filter(row => row.length > 0);
38
- const room = Math.max(1, workers - rows.length), share = Array.from({ length: room }, (): string[] => []);
39
- rest.forEach((slug, index) => { share[index % room]?.push(slug); });
40
- const table = [...rows, ...share.filter(row => row.length > 0)];
41
- if (table.length <= workers) return table;
42
- // GC31: one worker is one row, so a crossing reaches every cell.
43
- if (workers <= 1) return [table.flat()];
44
- const kept = rows.slice(0, workers - 1).map(row => row.slice()), over = [...rows.slice(workers - 1).flat(), ...rest];
45
- // the unnamed cells sit at the end of `over`, so the last cell is the one to move while it is unnamed
46
- for (let moving = over.at(-1); moving !== undefined && !named.has(moving); moving = over.at(-1)) {
47
- const lightest = kept.reduce((best, row) => (row.length < best.length ? row : best));
48
- if (over.length <= lightest.length + 1) break;
49
- over.pop(); lightest.push(moving);
48
+ const open = [...new Set(cells)].sort(), grouped = new Set(TOGETHER.flat());
49
+ const units = [...TOGETHER.map(group => group.filter(slug => open.includes(slug))).filter(group => group.length > 0), ...open.filter(slug => !grouped.has(slug)).map(slug => [slug])];
50
+ const weight = (unit: readonly string[]): number => unit.reduce((total, slug) => total + cellCost(slug), 0);
51
+ if (units.length === 0) return [];
52
+ units.sort((a, b) => weight(b) - weight(a) || (a[0] ?? '').localeCompare(b[0] ?? ''));
53
+ const rows = Array.from({ length: Math.max(1, Math.min(workers, units.length)) }, () => ({ cells: [] as string[], cost: 0 }));
54
+ for (const unit of units) {
55
+ const row = rows.reduce((best, next) => (next.cost < best.cost || (next.cost === best.cost && next.cells.length < best.cells.length) ? next : best));
56
+ row.cells.push(...unit); row.cost += weight(unit);
50
57
  }
51
- return [...kept, over];
58
+ return rows.map(row => row.cells);
52
59
  }