@hadoku/game-server 0.0.0-stage → 0.1.5

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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base-path.d.ts +29 -0
  3. package/dist/base-path.js +30 -0
  4. package/dist/busy.d.ts +40 -0
  5. package/dist/busy.js +23 -0
  6. package/dist/capacity.d.ts +9 -0
  7. package/dist/capacity.js +6 -0
  8. package/dist/config.d.ts +247 -0
  9. package/dist/config.js +271 -0
  10. package/dist/edge-auth.d.ts +43 -0
  11. package/dist/edge-auth.js +47 -0
  12. package/dist/erase/anonymise.d.ts +7 -0
  13. package/dist/erase/anonymise.js +7 -0
  14. package/dist/erase/index.d.ts +18 -0
  15. package/dist/erase/index.js +20 -0
  16. package/dist/erase/legacy-ids.d.ts +7 -0
  17. package/dist/erase/legacy-ids.js +24 -0
  18. package/dist/erase/recordings.d.ts +26 -0
  19. package/dist/erase/recordings.js +128 -0
  20. package/dist/erase/rooms.d.ts +63 -0
  21. package/dist/erase/rooms.js +67 -0
  22. package/dist/gate.d.ts +27 -0
  23. package/dist/gate.js +15 -0
  24. package/dist/http/client-events.d.ts +25 -0
  25. package/dist/http/client-events.js +15 -0
  26. package/dist/http/page.d.ts +26 -0
  27. package/dist/http/page.js +35 -0
  28. package/dist/http/prepared.d.ts +14 -0
  29. package/dist/http/prepared.js +16 -0
  30. package/dist/http/request.d.ts +59 -0
  31. package/dist/http/request.js +37 -0
  32. package/dist/http/room-core.d.ts +160 -0
  33. package/dist/http/room-core.js +278 -0
  34. package/dist/http/trim.d.ts +23 -0
  35. package/dist/http/trim.js +76 -0
  36. package/dist/http/usage.d.ts +22 -0
  37. package/dist/http/usage.js +16 -0
  38. package/dist/kernel.d.ts +4 -0
  39. package/dist/kernel.js +26 -0
  40. package/dist/log.d.ts +9 -0
  41. package/dist/log.js +9 -0
  42. package/dist/people.d.ts +105 -0
  43. package/dist/people.js +145 -0
  44. package/dist/play/clock.d.ts +39 -0
  45. package/dist/play/clock.js +81 -0
  46. package/dist/play/diagnostics.d.ts +21 -0
  47. package/dist/play/diagnostics.js +35 -0
  48. package/dist/play/engine-runtime.d.ts +200 -0
  49. package/dist/play/engine-runtime.js +309 -0
  50. package/dist/play/game-adapter.d.ts +158 -0
  51. package/dist/play/game-adapter.js +1 -0
  52. package/dist/play/host.d.ts +482 -0
  53. package/dist/play/host.js +950 -0
  54. package/dist/play/jvm-transport.d.ts +25 -0
  55. package/dist/play/jvm-transport.js +1 -0
  56. package/dist/play/local-jvm.d.ts +325 -0
  57. package/dist/play/local-jvm.js +829 -0
  58. package/dist/play/match/hosted.d.ts +92 -0
  59. package/dist/play/match/hosted.js +151 -0
  60. package/dist/play/match/outcome.d.ts +26 -0
  61. package/dist/play/match/outcome.js +21 -0
  62. package/dist/play/match/shell.d.ts +378 -0
  63. package/dist/play/match/shell.js +613 -0
  64. package/dist/play/recording/retention.d.ts +36 -0
  65. package/dist/play/recording/retention.js +89 -0
  66. package/dist/play/recording/writer.d.ts +185 -0
  67. package/dist/play/recording/writer.js +90 -0
  68. package/dist/play/relay-socket.d.ts +128 -0
  69. package/dist/play/relay-socket.js +194 -0
  70. package/dist/play/runtimes/in-process.d.ts +47 -0
  71. package/dist/play/runtimes/in-process.js +43 -0
  72. package/dist/play/runtimes/relay-match.d.ts +166 -0
  73. package/dist/play/runtimes/relay-match.js +240 -0
  74. package/dist/play/runtimes/relay.d.ts +128 -0
  75. package/dist/play/runtimes/relay.js +183 -0
  76. package/dist/play/runtimes/streamed.d.ts +116 -0
  77. package/dist/play/runtimes/streamed.js +148 -0
  78. package/dist/play/start-queue.d.ts +65 -0
  79. package/dist/play/start-queue.js +187 -0
  80. package/dist/room/avatar.d.ts +1 -0
  81. package/dist/room/avatar.js +28 -0
  82. package/dist/room/caller.d.ts +21 -0
  83. package/dist/room/caller.js +1 -0
  84. package/dist/room/constants.d.ts +27 -0
  85. package/dist/room/constants.js +27 -0
  86. package/dist/room/events.d.ts +59 -0
  87. package/dist/room/events.js +174 -0
  88. package/dist/room/identity.d.ts +89 -0
  89. package/dist/room/identity.js +98 -0
  90. package/dist/room/lobby.d.ts +426 -0
  91. package/dist/room/lobby.js +880 -0
  92. package/dist/room/membership.d.ts +64 -0
  93. package/dist/room/membership.js +76 -0
  94. package/dist/room/provisioning.d.ts +22 -0
  95. package/dist/room/provisioning.js +46 -0
  96. package/dist/room/record.d.ts +63 -0
  97. package/dist/room/record.js +39 -0
  98. package/dist/room/room-list.d.ts +67 -0
  99. package/dist/room/room-list.js +66 -0
  100. package/dist/room/seats.d.ts +39 -0
  101. package/dist/room/seats.js +58 -0
  102. package/dist/room/session.d.ts +91 -0
  103. package/dist/room/session.js +156 -0
  104. package/dist/room/socket-auth.d.ts +2 -0
  105. package/dist/room/socket-auth.js +10 -0
  106. package/dist/room/watching.d.ts +35 -0
  107. package/dist/room/watching.js +72 -0
  108. package/dist/room/watchparty-link.d.ts +1 -0
  109. package/dist/room/watchparty-link.js +17 -0
  110. package/dist/stream/alloc.d.ts +115 -0
  111. package/dist/stream/alloc.js +368 -0
  112. package/dist/stream/index.d.ts +66 -0
  113. package/dist/stream/index.js +293 -0
  114. package/dist/telemetry.d.ts +46 -0
  115. package/dist/telemetry.js +25 -0
  116. package/dist/testPort.d.ts +1 -0
  117. package/dist/testPort.js +28 -0
  118. package/package.json +36 -4
  119. package/README.md +0 -3
@@ -0,0 +1,613 @@
1
+ /**
2
+ * The platform half of a match (`play/match.ts`'s `Match` is this plus its game's {@link GameSession}):
3
+ * its lifecycle and its seats' holders, never what the game in it is. Who holds which seat and whether
4
+ * they are here, the grace a match nobody comes back to gets, the chess clock, the concede that
5
+ * always ends a game, the start queue's waiters, the record a restart re-attaches from, and the
6
+ * take-back ask between the two seats (restart the turn, or undo the last action). Every fact about the game itself — is a seat's own decision
7
+ * open, whose turn it is, what a seat's asks are — is asked of {@link MatchShell.game}.
8
+ *
9
+ * Nothing here imports Magic: a game that is not Forge runs under the same shell.
10
+ */
11
+ import { isDurableParticipantId } from '@wolffm/rooms-protocol';
12
+ import { report } from '../../telemetry.js';
13
+ import { ChessClock } from '../clock.js';
14
+ /** How far back {@link MatchShell.activity} counts the seconds in which the table changed. */
15
+ export const ACTIVITY_WINDOW_MS = 120_000;
16
+ /** How long a take-back ask (restart or undo) waits for the other seat before it counts as declined. */
17
+ export const RESTART_ASK_MS = 30_000;
18
+ /**
19
+ * How long Forge gets to end the game after a seat concedes before the concede is sent again, and
20
+ * again before the server ends the game itself. Forge ends a conceded game within the act's own
21
+ * turn at the gate (`ActGate`, at most 5 s); the monkey's matches met concedes Forge received, logged
22
+ * no error for, and never ended, each holding its place under the ceiling for good.
23
+ */
24
+ export const CONCEDE_ANSWER_MS = 10_000;
25
+ export class MatchShell {
26
+ id;
27
+ /** Minted per match-process start: a restart is a new epoch. */
28
+ epoch;
29
+ status = 'starting';
30
+ failure = null;
31
+ /** The seat whose concede Forge was sent, or null — the one end reason the board cannot show. */
32
+ concededBy = null;
33
+ /** The seat whose chess clock ran out, or null. The server conceded the game for it ({@link flag}). */
34
+ timedOut = null;
35
+ /**
36
+ * The chess clock (`clock.ts`), or null in a game without one (`MatchSpec.clockMs`). A seat's
37
+ * runs exactly while {@link waitingOnFor} names it — the same fact the other seat's banner
38
+ * reads — so a window the server answers for it never reaches it live and never costs it time.
39
+ * A disconnected seat's keeps running: being away answers nothing.
40
+ */
41
+ clock;
42
+ /** Fires when the running seat with the least time left runs out ({@link syncClock}). */
43
+ flagTimer = null;
44
+ /**
45
+ * When the match was started, in ms. A match taken back after a restart
46
+ * keeps the start its JVM's record has (`MatchRecord.startedAt`), so this is
47
+ * the same instant whichever process ends it.
48
+ */
49
+ startedAt;
50
+ spec;
51
+ host = null;
52
+ now;
53
+ runningWaiters = [];
54
+ /** `whenRunning` timeouts not yet started, because the match is waiting for a boot slot. */
55
+ bootWaiters = [];
56
+ /**
57
+ * This match's place among the starts waiting for a boot slot (`start-queue.ts`), 1-based, or
58
+ * null once its JVM is booting — and for a match that never waited.
59
+ */
60
+ queuePlace = null;
61
+ overTimer = null;
62
+ /** Waiting on Forge to end a conceded game: {@link watchConcede}. */
63
+ concedeWatch = null;
64
+ /**
65
+ * True while `resume` is feeding an earlier server's lines back in. Nothing
66
+ * may go OUT during that: every command in the stream was already sent by the
67
+ * server that read it, and sending it twice would act twice in Forge.
68
+ */
69
+ replaying = false;
70
+ /** Armed while no seat is here ({@link Match.armRejoinGrace}): a match nobody comes back to is stopped. */
71
+ rejoinTimer = null;
72
+ /** Whether {@link MatchDeps.ended} was told. */
73
+ endedTold = false;
74
+ /**
75
+ * The game at the start of its latest turn, from the bridge's `snapshot` line: what
76
+ * {@link MatchRegistry.restore} starts this match again from. Kept here and in the match's
77
+ * record on disk (`remember`), never only on the JVM's host.
78
+ */
79
+ latestSnapshot;
80
+ /**
81
+ * The newest `{ t: 'checkpoint' }` line `GameAdapter.classify` read, opaque to the shell —
82
+ * The generic twin of {@link latestSnapshot}, which stays Forge's own. Set by the composing
83
+ * match whenever its own `onLine` sees one (`fixtures/toy-game/match.ts`'s `ToyMatch` is the
84
+ * first caller; a generic `HostedMatch` reading `classify` directly is a later step), and
85
+ * written down with the record exactly like {@link latestSnapshot} ({@link remember}). A spec
86
+ * restored through `GameAdapter.restoreSpec` is what actually resumes the game from it; this
87
+ * field is only the shell's bookkeeping of what the last one was.
88
+ */
89
+ latestCheckpoint;
90
+ /**
91
+ * The open take-back ask: what it takes back, the asking seat, the turn it is about, for an undo the history it
92
+ * would rewind ({@link GameSession.takeBack}'s `version`), and its {@link RESTART_ASK_MS} expiry. One at a time.
93
+ */
94
+ takeBackAsk = null;
95
+ /** The turn a restart ask was declined in: no second ask until the next. */
96
+ restartDeclined = null;
97
+ /** Each seat's history an undo was declined at: no second ask until it moves. */
98
+ undoDeclined = new Map();
99
+ /** What {@link Match.restartState} last told, so a turn or snapshot that changes nothing tells no one. */
100
+ restartKey = '';
101
+ /**
102
+ * Why this server could not give the match a Forge at all (the host threw: a full
103
+ * disk, a JVM that could not be spawned), or null. The match is `failed` with it;
104
+ * `POST /play/matches` answers it as 503, since it says nothing about the match.
105
+ */
106
+ unstartable = null;
107
+ /**
108
+ * A match with no seat here is a JVM nobody is using: the seats have
109
+ * {@link MatchDeps.rejoinGraceMs} to come back before it is stopped for good. Armed when the
110
+ * match goes running or is taken back (its seats can join from then on, not while Forge boots)
111
+ * and when the last seat's departure grace runs out; {@link Match.seatConnected} disarms it. Before this covered every match, only a
112
+ * re-attached one had it, and a match both players had left held one of the server's two slots
113
+ * for ~2 h (2026-10-11: `seat-departing` for both seats, then nothing, then a refused rematch).
114
+ */
115
+ armRejoinGrace() {
116
+ const grace = this.deps.rejoinGraceMs ?? 0;
117
+ if (grace <= 0 || this.rejoinTimer !== null || this.anyoneHere())
118
+ return;
119
+ this.rejoinTimer = setTimeout(() => {
120
+ this.rejoinTimer = null;
121
+ if (this.anyoneHere())
122
+ return;
123
+ // A holder watching another match is still about: wait for them another grace.
124
+ if (this.seats.some((s) => s.owner !== null && this.deps.ownerOnline?.(s.owner) === true)) {
125
+ this.armRejoinGrace();
126
+ return;
127
+ }
128
+ this.deps.log({ evt: 'match-not-rejoined', matchId: this.id, status: this.status, afterMs: grace });
129
+ if (this.status === 'running')
130
+ this.deps.abandoned?.();
131
+ this.stop();
132
+ }, grace);
133
+ this.rejoinTimer.unref();
134
+ }
135
+ /** The host could not give this match a JVM, now or from the start queue: see {@link unstartable}. */
136
+ refuseStart(err) {
137
+ this.unstartable = `this server could not start a match just now (${err.message})`;
138
+ this.fail(this.unstartable);
139
+ }
140
+ /** seat → owner, for the on-disk record a re-attach reads and for a restore. */
141
+ owners() {
142
+ return this.seats.map((s) => s.owner);
143
+ }
144
+ /** What a re-attach or a restore of this match needs that only the match knows, onto its record on disk. */
145
+ /**
146
+ * Also the chess clock's time left: written at the start, at each turn's snapshot and when the
147
+ * server hands the match over, so a crash between two of those gives a seat back at most a turn.
148
+ */
149
+ remember() {
150
+ const clockMs = this.clockLeft();
151
+ this.host?.remember?.({
152
+ epoch: this.epoch,
153
+ owners: this.owners(),
154
+ checkpoint: this.latestCheckpoint,
155
+ snapshot: this.latestSnapshot,
156
+ ...(clockMs === null ? {} : { clockMs }),
157
+ });
158
+ }
159
+ /** Each seat's chess-clock time left, or null in a game without one. */
160
+ clockLeft() {
161
+ return this.clock?.left(this.now()) ?? null;
162
+ }
163
+ /**
164
+ * Run each seat's clock exactly while the game waits on it, and re-tell the roster when that
165
+ * changed — the clock rides on `forge:seats` ({@link seatIdentities}), so both screens and every
166
+ * watcher draw the same reading. Called wherever {@link waitingOnFor}'s inputs move: every
167
+ * {@link checkWaitingOn}, and every bar {@link send} puts on the wire.
168
+ */
169
+ syncClock() {
170
+ if (this.clock === null || this.replaying)
171
+ return;
172
+ const now = this.now();
173
+ const running = this.status === 'running' && this.timedOut === null;
174
+ const moved = this.clock.set([running && this.game.waitedOn(0), running && this.game.waitedOn(1)], now);
175
+ if (!moved)
176
+ return;
177
+ this.armFlag(now);
178
+ this.game.tellRoster();
179
+ }
180
+ /**
181
+ * Time the next flag: a timer for the running seat with the least time left. When it fires with time
182
+ * still on that seat's clock, it is armed again for what is left. Node fires a timer by the event
183
+ * loop's own clock, cut to the millisecond, and `now` reads the wall clock, so a timer armed for the
184
+ * 20 000 ms left can fire when the wall clock has moved 19 999: that seat then has 1 ms left, nothing
185
+ * about who runs has changed, and without the re-arm the seat sat at 0:00 and never lost.
186
+ */
187
+ armFlag(now) {
188
+ if (this.flagTimer !== null)
189
+ clearTimeout(this.flagTimer);
190
+ this.flagTimer = null;
191
+ const next = this.clock?.nextFlag(now) ?? null;
192
+ if (next === null)
193
+ return;
194
+ this.flagTimer = setTimeout(() => {
195
+ this.flagTimer = null;
196
+ const flagged = this.clock?.flagged(this.now()) ?? null;
197
+ if (flagged !== null) {
198
+ this.flag(flagged);
199
+ return;
200
+ }
201
+ this.syncClock();
202
+ if (this.flagTimer === null && !this.replaying)
203
+ this.armFlag(this.now());
204
+ }, next.inMs);
205
+ this.flagTimer.unref();
206
+ }
207
+ /** Nobody's time runs any more: the match is letting go of its game. */
208
+ stopClock() {
209
+ if (this.flagTimer !== null)
210
+ clearTimeout(this.flagTimer);
211
+ this.flagTimer = null;
212
+ this.clock?.stop(this.now());
213
+ }
214
+ /**
215
+ * A seat's chess clock reached zero: it loses (the operator, 2026-10-30: *"at zero, that player
216
+ * loses the match"*). The server concedes the game for it, exactly as its own Concede would, and
217
+ * {@link gameOutcome} marks the win `timedOut`, which the room logs; the game is lost like any other.
218
+ */
219
+ flag(seat) {
220
+ if (this.status !== 'running' || this.timedOut !== null)
221
+ return;
222
+ this.timedOut = seat;
223
+ this.concededBy = seat;
224
+ this.clock?.stop(this.now());
225
+ this.deps.log({ evt: 'clock-flag', matchId: this.id, seat, left: this.clockLeft() });
226
+ this.game.tellRoster();
227
+ this.game.command(this.concedeCommand(seat));
228
+ this.watchConcede(seat);
229
+ }
230
+ /**
231
+ * A concede always ends the game. If Forge has not ended it {@link CONCEDE_ANSWER_MS} after the
232
+ * concede, it is sent once more (Forge's concede is idempotent: an out player conceding again only
233
+ * re-runs the game-over check); if the game is still running after that, the server ends it as
234
+ * Forge would have, the conceding seat the loser, and Forge's game is stopped with the match.
235
+ */
236
+ watchConcede(seat, resent = false) {
237
+ if (this.concedeWatch !== null)
238
+ return;
239
+ const since = this.now();
240
+ this.concedeWatch = setTimeout(() => {
241
+ this.concedeWatch = null;
242
+ if (this.status !== 'running')
243
+ return;
244
+ if (!resent) {
245
+ this.deps.log({ evt: 'concede-unanswered', matchId: this.id, seat, waitedMs: this.now() - since });
246
+ this.game.command(this.concedeCommand(seat));
247
+ this.watchConcede(seat, true);
248
+ return;
249
+ }
250
+ const loser = this.seats[seat]?.playerId ?? null;
251
+ this.deps.log({ evt: 'concede-forced', matchId: this.id, seat, playerId: loser });
252
+ // A warning in telemetry, every time: how often Forge ignores a concede is the open question.
253
+ report('concede-forced', { matchId: this.id, seat, waitedMs: this.now() - since }, 'warn');
254
+ this.forceConcede(seat);
255
+ }, CONCEDE_ANSWER_MS);
256
+ this.concedeWatch.unref();
257
+ }
258
+ /* ── Seats ──────────────────────────────────────────────────────── */
259
+ /** The seat this participant holds, or null. */
260
+ seatOf(participantId) {
261
+ return this.seats.find((s) => s.owner === participantId)?.seat ?? null;
262
+ }
263
+ /**
264
+ * Bind a participant to a seat, or find the one they already hold.
265
+ * Idempotent, permanent, and refused to anyone who could not come back.
266
+ */
267
+ claim(participantId) {
268
+ const held = this.seatOf(participantId);
269
+ if (held !== null)
270
+ return { ok: true, seat: held, fresh: false };
271
+ if (!isDurableParticipantId(participantId)) {
272
+ return { ok: false, error: 'a seat needs a durable identity (account or device)' };
273
+ }
274
+ const free = this.seats.find((s) => !s.ai && s.owner === null);
275
+ if (free === undefined)
276
+ return { ok: false, error: 'match-full' };
277
+ free.owner = participantId;
278
+ // Written down beside the JVM: if this server is replaced mid-match, the
279
+ // next one must seat this person at THIS seat and no other.
280
+ this.remember();
281
+ this.deps.log({ evt: 'seat-claimed', matchId: this.id, seat: free.seat, participantId });
282
+ return { ok: true, seat: free.seat, fresh: true };
283
+ }
284
+ /**
285
+ * Resolves when every human seat knows its Forge player, or the match has failed. `timeoutMs`
286
+ * counts from when its JVM began booting: a start waiting its turn (`start-queue.ts`) is not
287
+ * Forge failing to start.
288
+ */
289
+ whenRunning(timeoutMs) {
290
+ if (this.status !== 'starting') {
291
+ return Promise.resolve(this.status === 'failed' ? { ok: false, error: this.failure ?? 'failed' } : { ok: true });
292
+ }
293
+ return new Promise((done) => {
294
+ let timer = null;
295
+ const arm = () => {
296
+ timer = setTimeout(() => {
297
+ const i = this.runningWaiters.indexOf(finish);
298
+ if (i >= 0)
299
+ this.runningWaiters.splice(i, 1);
300
+ done({ ok: false, error: 'match-starting' });
301
+ }, timeoutMs);
302
+ };
303
+ const finish = (outcome) => {
304
+ if (timer !== null)
305
+ clearTimeout(timer);
306
+ const i = this.bootWaiters.indexOf(arm);
307
+ if (i >= 0)
308
+ this.bootWaiters.splice(i, 1);
309
+ done(outcome);
310
+ };
311
+ this.runningWaiters.push(finish);
312
+ if (this.queuePlace === null)
313
+ arm();
314
+ else
315
+ this.bootWaiters.push(arm);
316
+ });
317
+ }
318
+ /**
319
+ * The seat's last connection is gone. It stops counting as at the table once
320
+ * it has stayed gone for `disconnectGraceMs` — at once when that is 0. Its
321
+ * asks stay open: they are re-sent when it comes back.
322
+ */
323
+ seatDisconnected(seat) {
324
+ const s = this.seats[seat];
325
+ if (s === undefined || s.departure !== null)
326
+ return;
327
+ const grace = this.deps.disconnectGraceMs ?? 0;
328
+ this.deps.log({ evt: 'seat-departing', matchId: this.id, seat, graceMs: grace, openAsks: this.game.openAsks(s.seat) });
329
+ const gone = () => {
330
+ s.here = false;
331
+ s.away = true;
332
+ this.game.tellRoster();
333
+ this.armRejoinGrace();
334
+ };
335
+ if (grace <= 0) {
336
+ gone();
337
+ return;
338
+ }
339
+ s.departure = setTimeout(() => {
340
+ s.departure = null;
341
+ gone();
342
+ }, grace);
343
+ s.departure.unref();
344
+ }
345
+ /**
346
+ * Somebody is at the table: a seat connected now, or gone for less than the grace.
347
+ * A running match nobody is at is not worth holding a deploy for — the deploy hands
348
+ * it over, and nobody's game is interrupted (`busy.ts`).
349
+ */
350
+ anyoneHere() {
351
+ return this.seats.some((s) => s.here);
352
+ }
353
+ /** A connection for this seat is back: whatever `seatDisconnected` armed is off. */
354
+ seatConnected(seat) {
355
+ const s = this.seats[seat];
356
+ if (s === undefined)
357
+ return;
358
+ s.here = true;
359
+ if (s.away) {
360
+ s.away = false;
361
+ this.game.tellRoster();
362
+ }
363
+ // Before the departure check, and not inside it: a seat that was never here at all (a new or
364
+ // re-attached match) disarms it too.
365
+ if (this.rejoinTimer !== null) {
366
+ clearTimeout(this.rejoinTimer);
367
+ this.rejoinTimer = null;
368
+ }
369
+ if (s.departure === null)
370
+ return;
371
+ clearTimeout(s.departure);
372
+ s.departure = null;
373
+ this.deps.log({ evt: 'seat-returned', matchId: this.id, seat, openAsks: this.game.openAsks(s.seat) });
374
+ }
375
+ /* ── The server is going down (Wave 22 §E) ──────────────────────── */
376
+ /**
377
+ * This process is stopping and this match is NOT: let go of the JVM without
378
+ * killing it, so the next process can take it back. False when the match
379
+ * cannot outlive us — the caller then owes its seats `serverStopping`.
380
+ *
381
+ * A FINISHED match (`over`, inside its `overGraceMs`) is handed over too: its
382
+ * players are on its result screen, and the board and the ending they are
383
+ * looking at are this match's to answer after a deploy exactly as a running
384
+ * game's are (the operator, 2026-10-17, prod m-e055472e0d6e: a deploy turned
385
+ * a result screen into "no longer running"). The next process's replay ends
386
+ * on the same `gameover`, which re-arms the grace from there.
387
+ *
388
+ * **Nothing is emitted here, on purpose.** A frame sent now would take a `seq`
389
+ * that the next server's replay cannot reproduce, and the seat's cursor would
390
+ * be one ahead of a stream that then reuses the number. The seats learn what
391
+ * happened from the reconnect, which is what the client is already built for.
392
+ */
393
+ handOver() {
394
+ if (this.status !== 'starting' && this.status !== 'running' && this.status !== 'over')
395
+ return false;
396
+ if (this.host?.handOver === undefined)
397
+ return false;
398
+ if (!this.host.handOver())
399
+ return false;
400
+ if (this.rejoinTimer !== null)
401
+ clearTimeout(this.rejoinTimer);
402
+ this.rejoinTimer = null;
403
+ if (this.overTimer !== null)
404
+ clearTimeout(this.overTimer);
405
+ this.overTimer = null;
406
+ this.stopClock();
407
+ this.remember();
408
+ this.deps.log({ evt: 'match-handed-over', matchId: this.id, epoch: this.epoch });
409
+ return true;
410
+ }
411
+ tellEnded() {
412
+ if (this.endedTold)
413
+ return;
414
+ this.endedTold = true;
415
+ this.deps.ended?.();
416
+ }
417
+ /**
418
+ * The whole seconds in which the table changed, oldest first, for the last {@link ACTIVITY_WINDOW_MS}.
419
+ * Stamped on every watcher-channel state frame, so one act's burst of frames is one second, and a
420
+ * game waiting on a player stamps nothing. `featured.ts` reads it through {@link activity}.
421
+ */
422
+ activeSeconds = [];
423
+ /** When the table last changed, and in how many of the last {@link ACTIVITY_WINDOW_MS}'s seconds. */
424
+ activity(now = this.now()) {
425
+ const from = Math.floor((now - ACTIVITY_WINDOW_MS) / 1000);
426
+ while (this.activeSeconds.length > 0 && this.activeSeconds[0] <= from)
427
+ this.activeSeconds.shift();
428
+ const last = this.activeSeconds.at(-1);
429
+ return { lastAt: last === undefined ? null : last * 1000, recent: this.activeSeconds.length };
430
+ }
431
+ noteActivity() {
432
+ const second = Math.floor(this.now() / 1000);
433
+ if (this.activeSeconds.at(-1) !== second)
434
+ this.activeSeconds.push(second);
435
+ this.activity();
436
+ }
437
+ /** Where a take-back stands, the same for every socket of the match. */
438
+ restartState() {
439
+ const turn = this.game.turn() ?? 0;
440
+ const ask = this.openAsk(turn);
441
+ return {
442
+ matchId: this.id,
443
+ turn,
444
+ ask: ask === null ? null : { from: ask.from, kind: ask.kind },
445
+ declined: this.restartDeclined === turn,
446
+ restorable: this.restorable(turn),
447
+ undoable: this.seats.filter((s) => this.undoable(s.seat) !== null).map((s) => s.seat),
448
+ };
449
+ }
450
+ /** The open ask, if it still stands: a restart ask is about one turn only. */
451
+ openAsk(turn) {
452
+ const ask = this.takeBackAsk;
453
+ return ask !== null && (ask.kind === 'undo' || ask.turn === turn) ? ask : null;
454
+ }
455
+ /** Whether `turn` can be played again from its start: the match holds that turn's snapshot, and it holds the whole game. */
456
+ restorable(turn) {
457
+ const snap = this.latestSnapshot;
458
+ return this.status === 'running' && snap !== null && snap.turn === turn && (snap.lossy?.length ?? 0) === 0;
459
+ }
460
+ /** The history `seat` may ask to undo, or null: its game says it can take an action back, and no undo of it was declined. */
461
+ undoable(seat) {
462
+ if (this.status !== 'running')
463
+ return null;
464
+ const at = this.game.takeBack?.(seat);
465
+ if (at === undefined || at === null || !at.can || this.undoDeclined.get(seat) === at.version)
466
+ return null;
467
+ return at.version;
468
+ }
469
+ /**
470
+ * A seat's take-back act (`docs/planning/restart-turn-plan.md`, `docs/planning/undo-plan.md`). `ask`: the seat
471
+ * wants its turn played again from its start (`restart`, only the seat whose turn it is) or its last action
472
+ * taken back (`undo`, when its game has one to take back); an AI opponent allows at once, a human one is asked,
473
+ * and no answer in {@link RESTART_ASK_MS} is a decline. `allow` / `decline`: the other seat's answer. `cancel`:
474
+ * the asker takes the ask back. One ask at a time, of either kind. The game is not paused while an ask is open:
475
+ * a restart undoes everything since the turn began anyway, and an undo ask lapses once the asker's history moves
476
+ * ({@link undoMoved}).
477
+ */
478
+ restartAct(seat, act, kind = 'restart') {
479
+ const s = this.seats[seat];
480
+ if (s === undefined || s.ai)
481
+ return { ok: false, error: 'no-such-seat' };
482
+ const turn = this.game.turn();
483
+ const open = this.openAsk(turn);
484
+ if (act === 'cancel') {
485
+ if (open === null || open.from !== seat)
486
+ return { ok: false, error: 'no-ask' };
487
+ this.deps.log({ evt: `${open.kind}-cancelled`, matchId: this.id, seat, turn });
488
+ this.closeTakeBack();
489
+ this.tellRestart(true);
490
+ return { ok: true };
491
+ }
492
+ if (act === 'allow' || act === 'decline') {
493
+ if (open === null || open.from === seat)
494
+ return { ok: false, error: 'no-ask' };
495
+ return this.answerTakeBack(seat, act === 'allow', 'player');
496
+ }
497
+ if (this.status !== 'running' || turn === null)
498
+ return { ok: false, error: 'not-running' };
499
+ if (open !== null)
500
+ return { ok: false, error: 'already-asked' };
501
+ let version = 0;
502
+ if (kind === 'restart') {
503
+ if (this.game.activeSeat()?.seat !== seat)
504
+ return { ok: false, error: 'not-your-turn' };
505
+ if (!this.restorable(turn))
506
+ return { ok: false, error: 'not-restorable' };
507
+ if (this.restartDeclined === turn)
508
+ return { ok: false, error: 'declined-this-turn' };
509
+ }
510
+ else {
511
+ const at = this.undoable(seat);
512
+ if (at === null)
513
+ return { ok: false, error: 'nothing-to-undo' };
514
+ version = at;
515
+ }
516
+ const other = this.seats.find((x) => x.seat !== seat);
517
+ if (other === undefined)
518
+ return { ok: false, error: 'no-opponent' };
519
+ this.deps.log({ evt: `${kind}-asked`, matchId: this.id, seat, turn, ai: other.ai, ...(kind === 'undo' ? { version } : {}) });
520
+ const ask = { kind, from: seat, turn, version };
521
+ if (other.ai)
522
+ return this.takeBackNow(ask, 'ai');
523
+ this.closeTakeBack();
524
+ const timer = setTimeout(() => this.answerTakeBack(other.seat, false, 'timeout'), RESTART_ASK_MS);
525
+ timer.unref();
526
+ this.takeBackAsk = { ...ask, timer };
527
+ this.tellRestart(true);
528
+ return { ok: true };
529
+ }
530
+ answerTakeBack(seat, allow, why) {
531
+ const ask = this.takeBackAsk;
532
+ if (ask === null)
533
+ return { ok: false, error: 'no-ask' };
534
+ this.closeTakeBack();
535
+ this.deps.log({ evt: `${ask.kind}-answered`, matchId: this.id, seat, turn: ask.turn, allow, why });
536
+ if (!allow) {
537
+ if (ask.kind === 'restart')
538
+ this.restartDeclined = ask.turn;
539
+ else
540
+ this.undoDeclined.set(ask.from, ask.version);
541
+ this.tellRestart(true);
542
+ return { ok: true };
543
+ }
544
+ const stands = ask.kind === 'restart' ? this.game.turn() === ask.turn && this.restorable(ask.turn) : this.undoable(ask.from) === ask.version;
545
+ if (!stands) {
546
+ this.tellRestart(true);
547
+ return { ok: false, error: ask.kind === 'restart' ? 'turn-moved-on' : 'history-moved' };
548
+ }
549
+ return this.takeBackNow(ask, 'opponent');
550
+ }
551
+ takeBackNow(ask, allowedBy) {
552
+ if (ask.kind === 'undo') {
553
+ if (this.game.rewind === undefined)
554
+ return { ok: false, error: 'cannot-undo' };
555
+ this.deps.log({ evt: 'undo', matchId: this.id, seat: ask.from, turn: ask.turn, version: ask.version, allowedBy });
556
+ this.game.rewind(ask.from, ask.version);
557
+ this.tellRestart(true);
558
+ return { ok: true };
559
+ }
560
+ if (this.deps.restartTurn === undefined)
561
+ return { ok: false, error: 'cannot-restart' };
562
+ this.deps.log({ evt: 'restart-turn', matchId: this.id, seat: ask.from, turn: ask.turn, allowedBy });
563
+ this.deps.restartTurn();
564
+ return { ok: true };
565
+ }
566
+ /**
567
+ * What `seat` could take back moved ({@link GameSession.takeBack}): it acted, or a barrier fell. Its open undo
568
+ * ask lapses, and a decline no longer holds once the history it was about is gone.
569
+ */
570
+ undoMoved(seat) {
571
+ const at = this.game.takeBack?.(seat) ?? null;
572
+ const ask = this.takeBackAsk;
573
+ if (ask !== null && ask.kind === 'undo' && ask.from === seat && (at === null || !at.can || at.version !== ask.version)) {
574
+ this.deps.log({ evt: 'undo-cancelled', matchId: this.id, seat, turn: ask.turn, why: 'history-moved' });
575
+ this.closeTakeBack();
576
+ }
577
+ const declined = this.undoDeclined.get(seat);
578
+ if (declined !== undefined && declined !== at?.version)
579
+ this.undoDeclined.delete(seat);
580
+ this.tellRestart();
581
+ }
582
+ closeTakeBack() {
583
+ if (this.takeBackAsk !== null)
584
+ clearTimeout(this.takeBackAsk.timer);
585
+ this.takeBackAsk = null;
586
+ }
587
+ /** Tell every socket where a restart stands, when it changed (or always, `force`: an act's own answer). */
588
+ tellRestart(force = false) {
589
+ const state = this.restartState();
590
+ const key = JSON.stringify(state);
591
+ if (!force && key === this.restartKey)
592
+ return;
593
+ this.restartKey = key;
594
+ this.deps.restartChanged?.(state);
595
+ }
596
+ /** The game this match plays: every fact about it the shell needs is asked of it. Set by the composing match, before anything can reach it. */
597
+ game;
598
+ deps;
599
+ constructor(id, spec, deps, restore) {
600
+ this.id = id;
601
+ this.spec = spec;
602
+ this.deps = deps;
603
+ this.now = deps.now ?? Date.now;
604
+ // A match taken back keeps the time its seats had left when it was last written down; the gap the
605
+ // server was down for is nobody's (`remember`'s callers say how stale that can be).
606
+ const clockMs = restore?.clockMs ?? spec.clockMs;
607
+ this.clock = clockMs === undefined ? null : new ChessClock(clockMs);
608
+ this.startedAt = restore?.startedAt ?? this.now();
609
+ this.epoch = restore?.epoch ?? `${id}:${this.startedAt}`;
610
+ this.latestSnapshot = restore?.snapshot ?? null;
611
+ this.latestCheckpoint = restore?.checkpoint ?? null;
612
+ }
613
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * What is kept of `CARDTABLE_RECORDINGS_DIR` and for how long
3
+ * (`docs/planning/wave77-2026-10-27.md` §C): the public stream for 7 days, the
4
+ * action log for 90, and the whole directory capped at 2 GB — the oldest
5
+ * PUBLIC streams go first under the cap, because they are the rebuildable
6
+ * half (`recording/rebuild.ts`, lane D) and the action logs are a few KB each
7
+ * either way. Age is the file's own mtime: both files are written exactly
8
+ * once, at the match's end, so mtime IS "when this match ended" with nothing
9
+ * else ever touching it.
10
+ *
11
+ * Swept hourly (`recorder.ts`'s `watchRecordings`) and once at boot, same
12
+ * discipline as `host.ts`'s own run-directory sweep. Never throws: one bad
13
+ * stat or unlink is logged and skipped, not a reason to stop sweeping the rest.
14
+ */
15
+ import type { JsonLog } from '@wolffm/service-kernel/log';
16
+ export declare const PUBLIC_RETENTION_MS: number;
17
+ export declare const ACTIONS_RETENTION_MS: number;
18
+ /** See the module header: the oldest public streams are dropped first when the directory is over this. */
19
+ export declare const RECORDINGS_CAP_BYTES: number;
20
+ export declare const ACTIONS_SUFFIX = ".actions.jsonl.gz";
21
+ export declare const PUBLIC_SUFFIX = ".public.jsonl.gz";
22
+ export interface SweepResult {
23
+ /** Files removed for being past their own retention window, by suffix. */
24
+ expiredActions: string[];
25
+ expiredPublic: string[];
26
+ /** Public streams removed to bring the directory back under {@link RECORDINGS_CAP_BYTES}. */
27
+ overCap: string[];
28
+ /** Directory size after the sweep, best-effort (0 if it could not be read at all). */
29
+ bytesAfter: number;
30
+ errors: {
31
+ file: string;
32
+ error: string;
33
+ }[];
34
+ }
35
+ /** One pass over `dir`: age-based expiry, then the size cap. See the module header. `capBytes` is overridable for a test; production never passes one. */
36
+ export declare function sweepRecordings(dir: string, now?: number, log?: JsonLog, capBytes?: number): SweepResult;