@eigeninteractive/testkit 0.5.2 → 0.6.0

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.
@@ -0,0 +1,638 @@
1
+ /**
2
+ * Read a Worker's LOCAL `.wrangler` state directly: the D1 index and the
3
+ * per-game Durable Object databases, opened as plain SQLite files.
4
+ *
5
+ * This is a development and debugging surface, never a runtime one. Nothing here
6
+ * runs on Workers: it is Node reading files that `wrangler dev` left on disk,
7
+ * which is why it lives in the testkit (a `devDependency`) behind its own
8
+ * subpath, and why it reads them through Node's built-in `node:sqlite` rather
9
+ * than a driver package. `better-sqlite3` would work and was tried first, but
10
+ * `drizzle-orm` declares it as an OPTIONAL PEER: installing it anywhere in the
11
+ * workspace re-resolves drizzle's peer set for every importer, which changed the
12
+ * types `packages/server` compiles against and broke its `dts` build. A
13
+ * debugging tool is not worth perturbing the engine's own dependency graph, and
14
+ * the built-in module costs nothing: no native build, no `allowBuilds` opt-in,
15
+ * and no dependency at all.
16
+ *
17
+ * Two stores, two different questions, and the reason a game-shaped reader
18
+ * exists at all:
19
+ *
20
+ * - **D1 is the index.** Discovery, history, ratings, identity. Its `games` row
21
+ * is a display read-model written by the DO as a fire-and-forget mirror.
22
+ * - **The game's DO is the session.** One SQLite database per game, holding the
23
+ * authoritative status, roster and the append-only transition log.
24
+ *
25
+ * A question like "why is this game not starting" therefore cannot be answered
26
+ * from either store alone, and answering it from a generic table browser means
27
+ * knowing which of the two to distrust. {@link LocalStore.game} joins them and
28
+ * reports the disagreement as a value, so a stale mirror reads as a stale
29
+ * mirror rather than as a mystery.
30
+ *
31
+ * Every open is read-only, so this is safe to run against a live `wrangler dev`.
32
+ *
33
+ * @module @eigeninteractive/testkit/local-state
34
+ */
35
+
36
+ import { existsSync, readdirSync, statSync } from "node:fs";
37
+ import { dirname, join, resolve } from "node:path";
38
+ import { DatabaseSync } from "node:sqlite";
39
+
40
+ /** Where `wrangler dev` persists local resources, relative to a Worker root. */
41
+ const STATE_SUFFIX = join(".wrangler", "state", "v3");
42
+
43
+ /** Miniflare's own bookkeeping database, present in every resource directory
44
+ * alongside the real ones. It holds `_cf_ALARM`, not user data. */
45
+ const METADATA_FILE = "metadata.sqlite";
46
+
47
+ /** The table Miniflare writes into every Durable Object database, holding the
48
+ * `idFromName` name the object was addressed by. It is what makes the hashed
49
+ * filename reversible: the engine names a game's DO by its `gameId`, and the
50
+ * hash is one-way, so this row is the only local file-to-game map there is. */
51
+ const DO_NAME_TABLE = "__miniflare_do_name";
52
+
53
+ /** A local Durable Object database: one game's whole session. */
54
+ export interface LocalDurableObject {
55
+ /** The Durable Object class, parsed from the directory Miniflare names
56
+ * `<worker>-<ClassName>`. */
57
+ className: string;
58
+ /** The hex `DurableObjectId`, which is the filename: `idFromName(name)`
59
+ * hashed. Not the game id, and not reversible without {@link name}. */
60
+ id: string;
61
+ /** The name the object was addressed by, which for a game DO is its
62
+ * `gameId`. Null only if the object was created by unique id rather than by
63
+ * name, which the engine never does. */
64
+ name: string | null;
65
+ /** Absolute path to the SQLite file. */
66
+ file: string;
67
+ }
68
+
69
+ /** What a bound parameter may be: SQLite's own value domain, spelled out here
70
+ * rather than re-exported from `node:sqlite` so the public signature does not
71
+ * depend on a built-in module's type names. */
72
+ export type LocalQueryParam = string | number | bigint | null | Uint8Array;
73
+
74
+ /** A row of Miniflare's alarm table: the DO's armed alarm, which for a game is
75
+ * its turn deadline plus grace. An absent row means no timer is armed, which is
76
+ * correct for an untimed game and a bug for a timed one mid-turn. */
77
+ export interface LocalAlarm {
78
+ actorId: string;
79
+ actorName: string | null;
80
+ scheduledTime: number | null;
81
+ }
82
+
83
+ /** The engine's `games` row: the D1 index entry, a display mirror of the DO. */
84
+ export interface LocalGameRow {
85
+ id: string;
86
+ createdBy: string | null;
87
+ status: string;
88
+ access: string;
89
+ schemaVersion: number;
90
+ config: unknown;
91
+ turnSeconds: number | null;
92
+ budgetSeconds: number | null;
93
+ incrementSeconds: number | null;
94
+ rated: boolean;
95
+ ratingPool: string | null;
96
+ minPlayers: number;
97
+ maxPlayers: number;
98
+ shortCode: string;
99
+ pendingPlayers: number[] | null;
100
+ turnDeadline: number | null;
101
+ outcomes: unknown;
102
+ finishId: string | null;
103
+ finishedAt: number | null;
104
+ archivedAt: number | null;
105
+ createdAt: number;
106
+ updatedAt: number;
107
+ }
108
+
109
+ /** One seat, from either store. `username` is filled in from D1's `users` and
110
+ * `bots` tables when the reader has an index to join against. */
111
+ export interface LocalSeat {
112
+ playerIndex: number;
113
+ userId: string | null;
114
+ botId: string | null;
115
+ type: string;
116
+ username: string | null;
117
+ displayName: string | null;
118
+ }
119
+
120
+ /** The DO's single `meta` row: the authoritative session header. */
121
+ export interface LocalGameMeta {
122
+ gameId: string;
123
+ status: string;
124
+ access: string;
125
+ schemaVersion: number;
126
+ config: unknown;
127
+ turnSeconds: number | null;
128
+ budgetSeconds: number | null;
129
+ incrementSeconds: number | null;
130
+ rated: boolean;
131
+ ratingPool: string | null;
132
+ minPlayers: number;
133
+ maxPlayers: number;
134
+ createdBy: string | null;
135
+ rngSeed: string | null;
136
+ }
137
+
138
+ /** One committed transition, decoded. `action` is null at v0 (the start). */
139
+ export interface LocalTransition {
140
+ version: number;
141
+ state: unknown;
142
+ action: { type: string; kind: string; playerIndex: number | null; data: unknown } | null;
143
+ pending: number[];
144
+ deadline: number | null;
145
+ playerTimes: number[] | null;
146
+ /** Non-null only while this transition's pending turn consumes a budget
147
+ * bank. Per-action and hook-override deadlines do not set it. */
148
+ turnStartedAt: number | null;
149
+ /** Which seats hold a stored frame at this version. Empty after the finish
150
+ * compaction, which empties `frames` and leaves replay to re-projection. */
151
+ frameSeats: number[];
152
+ }
153
+
154
+ /** Why the game is where it is, and what would move it. Derived rather than
155
+ * stored: this is the sentence a developer actually wants, and every input to
156
+ * it is already on screen above it. */
157
+ export interface LocalGameDiagnosis {
158
+ /** One line naming the next expected event, or the reason there is none. */
159
+ summary: string;
160
+ /** Disagreements between the D1 mirror and the DO's own truth. A non-empty
161
+ * list means a mirror write was lost, since the DO is authoritative. */
162
+ mirrorDrift: string[];
163
+ }
164
+
165
+ /** Everything both stores know about one game. */
166
+ export interface LocalGameView {
167
+ gameId: string;
168
+ /** The D1 index row, or null when D1 has no such game: either the id came
169
+ * from a DO name and the index was wiped, or the create write never landed. */
170
+ index: LocalGameRow | null;
171
+ /** D1's `participants`, which mirror the DO's roster for display. */
172
+ indexSeats: LocalSeat[];
173
+ /** The DO file, or null when no Durable Object exists for this game yet.
174
+ * That is the normal state of a created-but-never-touched lobby: the DO is
175
+ * created lazily by the first command or socket. */
176
+ durableObject: LocalDurableObject | null;
177
+ meta: LocalGameMeta | null;
178
+ roster: LocalSeat[];
179
+ transitions: LocalTransition[];
180
+ /** Unapplied finish rows: a surviving row means the D1 finish apply has not
181
+ * succeeded and the admin re-poke is the recovery. */
182
+ outbox: { finishId: string; createdAt: number; outcomes: unknown }[];
183
+ alarm: LocalAlarm | null;
184
+ diagnosis: LocalGameDiagnosis;
185
+ }
186
+
187
+ /**
188
+ * Walk up from `from` to the nearest directory holding `.wrangler/state/v3`.
189
+ *
190
+ * Walking rather than requiring the Worker root means this works from anywhere
191
+ * inside a game repository, including the app half of a two-package layout,
192
+ * where the state lives a directory or two above the shell's cwd.
193
+ */
194
+ export function findWranglerState(from: string = process.cwd()): string | null {
195
+ let dir = resolve(from);
196
+ for (;;) {
197
+ const candidate = join(dir, STATE_SUFFIX);
198
+ if (existsSync(candidate)) return candidate;
199
+ const parent = dirname(dir);
200
+ if (parent === dir) return null;
201
+ dir = parent;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Open a SQLite file for reading only.
207
+ *
208
+ * Read-only is what makes this safe to point at a running `wrangler dev`: no
209
+ * writer lock is taken and no journal is touched. The fallback matters because
210
+ * these databases are in WAL mode, and a read-only connection cannot recover a
211
+ * hot journal or create the `-shm` file it needs; when `wrangler dev` is not
212
+ * running and left one behind, the first open fails and a writable handle is
213
+ * the only way in. Nothing here issues anything but `SELECT`, so the widened
214
+ * handle stays as harmless as the narrow one. The existence check comes first
215
+ * because that fallback would otherwise CREATE a database rather than report a
216
+ * missing one.
217
+ */
218
+ export function openSqlite(file: string): DatabaseSync {
219
+ if (!existsSync(file)) throw new Error(`no SQLite database at ${file}`);
220
+ try {
221
+ return new DatabaseSync(file, { readOnly: true });
222
+ } catch {
223
+ return new DatabaseSync(file);
224
+ }
225
+ }
226
+
227
+ function sqliteFilesIn(dir: string): string[] {
228
+ if (!existsSync(dir)) return [];
229
+ return readdirSync(dir)
230
+ .filter((entry) => entry.endsWith(".sqlite") && entry !== METADATA_FILE)
231
+ .map((entry) => join(dir, entry));
232
+ }
233
+
234
+ function tableExists(db: DatabaseSync, table: string): boolean {
235
+ const row = db.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(table);
236
+ return row !== undefined;
237
+ }
238
+
239
+ /** Parse a JSON text column, tolerating a value some other writer left
240
+ * un-encoded. A debugging reader that throws on one malformed cell is useless
241
+ * precisely when it is needed. */
242
+ function json(value: unknown): unknown {
243
+ if (typeof value !== "string") return value ?? null;
244
+ try {
245
+ return JSON.parse(value);
246
+ } catch {
247
+ return value;
248
+ }
249
+ }
250
+
251
+ function numbers(value: unknown): number[] {
252
+ const parsed = json(value);
253
+ return Array.isArray(parsed) ? parsed.filter((n): n is number => typeof n === "number") : [];
254
+ }
255
+
256
+ function bool(value: unknown): boolean {
257
+ return value === 1 || value === true;
258
+ }
259
+
260
+ /**
261
+ * A Worker's local state, with its databases opened lazily and held open.
262
+ *
263
+ * Stateful because it owns file handles: construct one, ask it questions, and
264
+ * {@link close} it. A single instance is the unit both the CLI and a test use,
265
+ * so neither has to know which file backs which resource.
266
+ */
267
+ export class LocalStore {
268
+ /** Absolute path to `.wrangler/state/v3`. */
269
+ readonly root: string;
270
+
271
+ #d1: { file: string; db: DatabaseSync } | null | undefined;
272
+ readonly #open = new Map<string, DatabaseSync>();
273
+
274
+ private constructor(root: string) {
275
+ this.root = root;
276
+ }
277
+
278
+ /**
279
+ * Locate and open the state under `from`, or throw with the one thing the
280
+ * caller can act on: that no Worker has been run here yet.
281
+ */
282
+ static open(from?: string): LocalStore {
283
+ const root = findWranglerState(from);
284
+ if (root === null) {
285
+ throw new Error(`no .wrangler/state/v3 found at or above ${resolve(from ?? process.cwd())}. Run the Worker once (\`pnpm dev\`) so it has local state to read.`);
286
+ }
287
+ return new LocalStore(root);
288
+ }
289
+
290
+ #handle(file: string): DatabaseSync {
291
+ const existing = this.#open.get(file);
292
+ if (existing !== undefined) return existing;
293
+ const db = openSqlite(file);
294
+ this.#open.set(file, db);
295
+ return db;
296
+ }
297
+
298
+ /**
299
+ * The engine's D1 database, identified by its schema rather than its name.
300
+ *
301
+ * Miniflare names the file after a hash of the database, so there is no
302
+ * mapping back to the binding. Recognising the engine's own `games` table
303
+ * instead is both simpler and more honest about what the caller wants: the
304
+ * database that has games in it, whatever the binding was called.
305
+ */
306
+ d1(): { file: string; db: DatabaseSync } | null {
307
+ if (this.#d1 !== undefined) return this.#d1;
308
+ for (const file of sqliteFilesIn(join(this.root, "d1", "miniflare-D1DatabaseObject"))) {
309
+ const db = this.#handle(file);
310
+ if (tableExists(db, "games")) {
311
+ this.#d1 = { file, db };
312
+ return this.#d1;
313
+ }
314
+ }
315
+ this.#d1 = null;
316
+ return null;
317
+ }
318
+
319
+ /**
320
+ * Every local Durable Object database, newest-modified first.
321
+ *
322
+ * The directory is `<worker>-<ClassName>`, and a worker name may itself
323
+ * contain a dash, so the class is everything after the LAST one. Ordering by
324
+ * mtime puts the game you just touched at the top, which is nearly always the
325
+ * one being debugged.
326
+ */
327
+ durableObjects(): LocalDurableObject[] {
328
+ const base = join(this.root, "do");
329
+ if (!existsSync(base)) return [];
330
+ const found: LocalDurableObject[] = [];
331
+ for (const namespace of readdirSync(base)) {
332
+ const dir = join(base, namespace);
333
+ if (!statSync(dir).isDirectory()) continue;
334
+ const className = namespace.slice(namespace.lastIndexOf("-") + 1);
335
+ for (const file of sqliteFilesIn(dir)) {
336
+ const db = this.#handle(file);
337
+ const name = tableExists(db, DO_NAME_TABLE) ? ((db.prepare(`select name from ${DO_NAME_TABLE} limit 1`).get() as { name?: string } | undefined)?.name ?? null) : null;
338
+ found.push({ className, id: file.slice(file.lastIndexOf("/") + 1, -".sqlite".length), name, file });
339
+ }
340
+ }
341
+ return found.sort((a, b) => statSync(b.file).mtimeMs - statSync(a.file).mtimeMs);
342
+ }
343
+
344
+ /** The armed alarm for a Durable Object, from its namespace's metadata
345
+ * database. Matched on either column because the id is what Miniflare keys
346
+ * by and the name is what a human recognises. */
347
+ alarm(target: LocalDurableObject): LocalAlarm | null {
348
+ const file = join(dirname(target.file), METADATA_FILE);
349
+ if (!existsSync(file)) return null;
350
+ const db = this.#handle(file);
351
+ if (!tableExists(db, "_cf_ALARM")) return null;
352
+ const row = db.prepare("select actor_id, actor_name, scheduled_time from _cf_ALARM where actor_id = ? or actor_name = ?").get(target.id, target.name ?? target.id) as { actor_id: string; actor_name: string | null; scheduled_time: number | null } | undefined;
353
+ return row === undefined ? null : { actorId: row.actor_id, actorName: row.actor_name, scheduledTime: row.scheduled_time };
354
+ }
355
+
356
+ /** The D1 index rows, newest-updated first. */
357
+ games(options: { status?: string; limit?: number } = {}): LocalGameRow[] {
358
+ const d1 = this.d1();
359
+ if (d1 === null) return [];
360
+ const where = options.status === undefined ? "" : "where status = ?";
361
+ const params = options.status === undefined ? [] : [options.status];
362
+ const rows = d1.db.prepare(`select * from games ${where} order by updated_at desc limit ?`).all(...params, options.limit ?? 50) as Record<string, unknown>[];
363
+ return rows.map(toGameRow);
364
+ }
365
+
366
+ /**
367
+ * Resolve a game reference the way a developer will type it: a full id, a
368
+ * six-character short code, or an id prefix long enough to be unique.
369
+ *
370
+ * D1 is tried first because it can match a short code, then the DO names, so
371
+ * a game whose index row was wiped is still reachable by id.
372
+ */
373
+ resolveGameId(ref: string): string | null {
374
+ const d1 = this.d1();
375
+ if (d1 !== null) {
376
+ const exact = d1.db.prepare("select id from games where id = ? or short_code = ?").get(ref, ref.toUpperCase()) as { id: string } | undefined;
377
+ if (exact !== undefined) return exact.id;
378
+ const prefixed = d1.db.prepare("select id from games where id like ? limit 2").all(`${ref}%`) as { id: string }[];
379
+ if (prefixed.length === 1) return prefixed[0].id;
380
+ if (prefixed.length > 1) throw new Error(`"${ref}" matches more than one game; use a longer prefix`);
381
+ }
382
+ const named = this.durableObjects().filter((o) => o.name !== null && (o.name === ref || o.name.startsWith(ref)));
383
+ if (named.length === 1) return named[0].name;
384
+ if (named.length > 1) throw new Error(`"${ref}" matches more than one game; use a longer prefix`);
385
+ return null;
386
+ }
387
+
388
+ /** The Durable Object holding a game's session, or null if none exists yet. */
389
+ gameDurableObject(gameId: string): LocalDurableObject | null {
390
+ return this.durableObjects().find((o) => o.name === gameId) ?? null;
391
+ }
392
+
393
+ /** Identity for a set of user and bot ids, for rendering seats as names. */
394
+ #identities(userIds: string[], botIds: string[]): Map<string, { username: string; displayName: string }> {
395
+ const out = new Map<string, { username: string; displayName: string }>();
396
+ const d1 = this.d1();
397
+ if (d1 === null) return out;
398
+ for (const [table, ids] of [
399
+ ["users", userIds],
400
+ ["bots", botIds],
401
+ ] as const) {
402
+ if (ids.length === 0) continue;
403
+ const placeholders = ids.map(() => "?").join(",");
404
+ const rows = d1.db.prepare(`select id, username, display_name from ${table} where id in (${placeholders})`).all(...ids) as { id: string; username: string; display_name: string }[];
405
+ for (const row of rows) out.set(row.id, { username: row.username, displayName: row.display_name });
406
+ }
407
+ return out;
408
+ }
409
+
410
+ #seats(rows: { player_index: number; user_id: string | null; bot_id: string | null; type: string }[]): LocalSeat[] {
411
+ const identities = this.#identities(
412
+ rows.map((r) => r.user_id).filter((id): id is string => id !== null),
413
+ rows.map((r) => r.bot_id).filter((id): id is string => id !== null),
414
+ );
415
+ return rows.map((row) => {
416
+ const identity = identities.get(row.user_id ?? row.bot_id ?? "");
417
+ return { playerIndex: row.player_index, userId: row.user_id, botId: row.bot_id, type: row.type, username: identity?.username ?? null, displayName: identity?.displayName ?? null };
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Join both stores for one game: the index row, the session, the transition
423
+ * log, and the derived diagnosis.
424
+ *
425
+ * Returns null only when neither store has heard of the game.
426
+ */
427
+ game(ref: string): LocalGameView | null {
428
+ const gameId = this.resolveGameId(ref);
429
+ if (gameId === null) return null;
430
+
431
+ const d1 = this.d1();
432
+ const indexRow = d1 === null ? undefined : (d1.db.prepare("select * from games where id = ?").get(gameId) as Record<string, unknown> | undefined);
433
+ const index = indexRow === undefined ? null : toGameRow(indexRow);
434
+ const indexSeats =
435
+ d1 === null
436
+ ? []
437
+ : this.#seats(
438
+ d1.db.prepare("select player_index, user_id, bot_id, type from participants where game_id = ? order by player_index").all(gameId) as {
439
+ player_index: number;
440
+ user_id: string | null;
441
+ bot_id: string | null;
442
+ type: string;
443
+ }[],
444
+ );
445
+
446
+ const durableObject = this.gameDurableObject(gameId);
447
+ let meta: LocalGameMeta | null = null;
448
+ let roster: LocalSeat[] = [];
449
+ let transitions: LocalTransition[] = [];
450
+ let outbox: LocalGameView["outbox"] = [];
451
+
452
+ if (durableObject !== null) {
453
+ const db = this.#handle(durableObject.file);
454
+ if (tableExists(db, "meta")) {
455
+ const row = db.prepare("select * from meta where id = 1").get() as Record<string, unknown> | undefined;
456
+ if (row !== undefined) meta = toMeta(row);
457
+ }
458
+ if (tableExists(db, "roster")) {
459
+ roster = this.#seats(db.prepare("select player_index, user_id, bot_id, type from roster order by player_index").all() as { player_index: number; user_id: string | null; bot_id: string | null; type: string }[]);
460
+ }
461
+ if (tableExists(db, "transitions")) {
462
+ const frameSeats = new Map<number, number[]>();
463
+ if (tableExists(db, "frames")) {
464
+ for (const row of db.prepare("select version, player_index from frames order by version, player_index").all() as { version: number; player_index: number }[]) {
465
+ frameSeats.set(row.version, [...(frameSeats.get(row.version) ?? []), row.player_index]);
466
+ }
467
+ }
468
+ transitions = (db.prepare("select * from transitions order by version").all() as Record<string, unknown>[]).map((row) => toTransition(row, frameSeats));
469
+ }
470
+ if (tableExists(db, "outbox")) {
471
+ outbox = (db.prepare("select finish_id, outcomes, created_at from outbox order by created_at").all() as { finish_id: string; outcomes: unknown; created_at: number }[]).map((row) => ({
472
+ finishId: row.finish_id,
473
+ createdAt: row.created_at,
474
+ outcomes: json(row.outcomes),
475
+ }));
476
+ }
477
+ }
478
+
479
+ const alarm = durableObject === null ? null : this.alarm(durableObject);
480
+ const view: Omit<LocalGameView, "diagnosis"> = { gameId, index, indexSeats, durableObject, meta, roster, transitions, outbox, alarm };
481
+ return { ...view, diagnosis: diagnose(view) };
482
+ }
483
+
484
+ /** Run a read-only statement against D1 or one game's Durable Object: the
485
+ * escape hatch for a question this reader does not model. */
486
+ query(sql: string, options: { game?: string; params?: LocalQueryParam[] } = {}): Record<string, unknown>[] {
487
+ const db = options.game === undefined ? this.d1()?.db : this.#gameDb(options.game);
488
+ if (db === undefined || db === null) {
489
+ throw new Error(options.game === undefined ? "no local D1 database found in this Worker's state" : `no local Durable Object found for game ${options.game}`);
490
+ }
491
+ return db.prepare(sql).all(...(options.params ?? [])) as Record<string, unknown>[];
492
+ }
493
+
494
+ /** Table names and row counts, for D1 or one game's Durable Object. */
495
+ tables(options: { game?: string } = {}): { name: string; rows: number }[] {
496
+ const db = options.game === undefined ? this.d1()?.db : this.#gameDb(options.game);
497
+ if (db === undefined || db === null) return [];
498
+ const names = (db.prepare("select name from sqlite_master where type = 'table' order by name").all() as { name: string }[]).map((r) => r.name);
499
+ return names.map((name) => ({ name, rows: (db.prepare(`select count(*) as n from "${name}"`).get() as { n: number }).n }));
500
+ }
501
+
502
+ #gameDb(ref: string): DatabaseSync | null {
503
+ const gameId = this.resolveGameId(ref);
504
+ const target = gameId === null ? null : this.gameDurableObject(gameId);
505
+ return target === null ? null : this.#handle(target.file);
506
+ }
507
+
508
+ /** Release every open handle. */
509
+ close(): void {
510
+ for (const db of this.#open.values()) db.close();
511
+ this.#open.clear();
512
+ this.#d1 = undefined;
513
+ }
514
+ }
515
+
516
+ function toGameRow(row: Record<string, unknown>): LocalGameRow {
517
+ return {
518
+ id: row.id as string,
519
+ createdBy: (row.created_by as string | null) ?? null,
520
+ status: row.status as string,
521
+ access: row.access as string,
522
+ schemaVersion: row.schema_version as number,
523
+ config: json(row.config),
524
+ turnSeconds: (row.turn_seconds as number | null) ?? null,
525
+ budgetSeconds: (row.budget_seconds as number | null) ?? null,
526
+ incrementSeconds: (row.increment_seconds as number | null) ?? null,
527
+ rated: bool(row.rated),
528
+ ratingPool: (row.rating_pool as string | null) ?? null,
529
+ minPlayers: row.min_players as number,
530
+ maxPlayers: row.max_players as number,
531
+ shortCode: row.short_code as string,
532
+ pendingPlayers: row.pending_players === null || row.pending_players === undefined ? null : numbers(row.pending_players),
533
+ turnDeadline: (row.turn_deadline as number | null) ?? null,
534
+ outcomes: json(row.outcomes),
535
+ finishId: (row.finish_id as string | null) ?? null,
536
+ finishedAt: (row.finished_at as number | null) ?? null,
537
+ archivedAt: (row.archived_at as number | null) ?? null,
538
+ createdAt: row.created_at as number,
539
+ updatedAt: row.updated_at as number,
540
+ };
541
+ }
542
+
543
+ function toMeta(row: Record<string, unknown>): LocalGameMeta {
544
+ return {
545
+ gameId: row.game_id as string,
546
+ status: row.status as string,
547
+ access: row.access as string,
548
+ schemaVersion: row.schema_version as number,
549
+ config: json(row.config),
550
+ turnSeconds: (row.turn_seconds as number | null) ?? null,
551
+ budgetSeconds: (row.budget_seconds as number | null) ?? null,
552
+ incrementSeconds: (row.increment_seconds as number | null) ?? null,
553
+ rated: bool(row.rated),
554
+ ratingPool: (row.rating_pool as string | null) ?? null,
555
+ minPlayers: row.min_players as number,
556
+ maxPlayers: row.max_players as number,
557
+ createdBy: (row.created_by as string | null) ?? null,
558
+ rngSeed: (row.rng_seed as string | null) ?? null,
559
+ };
560
+ }
561
+
562
+ function toTransition(row: Record<string, unknown>, frameSeats: Map<number, number[]>): LocalTransition {
563
+ const version = row.version as number;
564
+ const action = json(row.action) as LocalTransition["action"];
565
+ return {
566
+ version,
567
+ state: json(row.state),
568
+ action: action ?? null,
569
+ pending: numbers(row.pending),
570
+ deadline: (row.deadline as number | null) ?? null,
571
+ playerTimes: row.player_times === null || row.player_times === undefined ? null : numbers(row.player_times),
572
+ turnStartedAt: (row.turn_started_at as number | null) ?? null,
573
+ frameSeats: frameSeats.get(version) ?? [],
574
+ };
575
+ }
576
+
577
+ /**
578
+ * Say what the game is waiting for, and whether the two stores agree.
579
+ *
580
+ * The engine's statuses each have exactly one thing that moves them, so this is
581
+ * a total function over `status` rather than a heuristic. The cases developers
582
+ * actually hit are the first two: a lobby that will not fill, and a full lobby
583
+ * whose creator has not pressed start.
584
+ */
585
+ function diagnose(view: Omit<LocalGameView, "diagnosis">): LocalGameDiagnosis {
586
+ const status = view.meta?.status ?? view.index?.status ?? "unknown";
587
+ const seated = (view.meta === null ? view.indexSeats : view.roster).length;
588
+ const min = view.meta?.minPlayers ?? view.index?.minPlayers ?? 0;
589
+ const max = view.meta?.maxPlayers ?? view.index?.maxPlayers ?? 0;
590
+ const latest = view.transitions.at(-1) ?? null;
591
+
592
+ const mirrorDrift: string[] = [];
593
+ if (view.index !== null && view.meta !== null) {
594
+ if (view.index.status !== view.meta.status) {
595
+ mirrorDrift.push(`D1 says status=${view.index.status}, the Durable Object says ${view.meta.status}. The DO is authoritative; a mirror write was lost.`);
596
+ }
597
+ if (view.indexSeats.length !== view.roster.length) {
598
+ mirrorDrift.push(`D1 mirrors ${view.indexSeats.length} seat(s), the Durable Object holds ${view.roster.length}.`);
599
+ }
600
+ const mirroredPending = view.index.pendingPlayers ?? null;
601
+ const actualPending = latest?.pending ?? null;
602
+ if (status === "active" && JSON.stringify(mirroredPending) !== JSON.stringify(actualPending)) {
603
+ mirrorDrift.push(`D1 mirrors pendingPlayers=${JSON.stringify(mirroredPending)}, the newest transition has ${JSON.stringify(actualPending)}.`);
604
+ }
605
+ }
606
+ if (view.index === null && view.meta !== null) {
607
+ mirrorDrift.push("no D1 index row for a game whose Durable Object exists; discovery and history lists cannot show it.");
608
+ }
609
+
610
+ let summary: string;
611
+ switch (status) {
612
+ case "waiting":
613
+ summary = `waiting for players: ${seated}/${min} needed to become ready (${max} max). The next event is a join, or add-bot from the creator.`;
614
+ break;
615
+ case "ready":
616
+ summary = `ready and not started: ${seated}/${max} seats filled. Nothing happens until the CREATOR calls POST /api/engine/games/${view.gameId}/start. A start is explicit and creator-only; filling the lobby does not start a game.`;
617
+ break;
618
+ case "active":
619
+ if (latest === null) {
620
+ summary = "status is active but no transition is committed, which should be impossible: a start commits v0 in the same transaction that sets the status.";
621
+ } else {
622
+ const waitingOn = latest.pending.length === 0 ? "nobody, which means the game should have finished at this version" : `seat(s) ${latest.pending.join(", ")}`;
623
+ const timer = latest.deadline === null ? "untimed, so no alarm is armed and only a move or a forfeit moves it" : `deadline ${new Date(latest.deadline).toISOString()}`;
624
+ summary = `at v${latest.version}, waiting on ${waitingOn}. ${timer}.`;
625
+ }
626
+ break;
627
+ case "finished":
628
+ summary = view.outbox.length > 0 ? `finished, but ${view.outbox.length} outbox row(s) survive: the D1 finish apply has not succeeded, so ratings and history are not published yet.` : `finished at v${latest?.version ?? "?"}; the outbox is clear, so D1 has the outcomes.`;
629
+ break;
630
+ case "aborted":
631
+ summary = "aborted: cancelled by its creator, reaped as abandoned, or torn down by an account purge. Nothing moves an aborted game.";
632
+ break;
633
+ default:
634
+ summary = view.durableObject === null ? "created in D1 but its Durable Object does not exist yet. That is normal for a lobby nobody has touched: the DO is created lazily by the first command or socket." : `unrecognised status ${status}.`;
635
+ }
636
+
637
+ return { summary, mirrorDrift };
638
+ }