v0.5.0 — multiplayer Phases 2 and 3: a server that runs a game and survives being restarted

Phases 0-1 shipped in v0.4.0 (seat/identity split, per-player turn state, the Session boundary).
This lands Phase 2 (server core, one game, no lobby) and Phase 3 (persistence and resumption) per
docs/architecture/multiplayer.md §12. Phases 4-6 (lobby/reconnection, the 22 opponent-directed
cards, StartOS packaging) are still ahead.

Phase 2: src/server/session.ts hosts a game in pure logic (no sockets) on top of game.ts's existing
Game/submit/currentActor/actionMenu; it verifies seat === currentActor(game) itself before calling
submit, since submit() trusts its caller and a server can't. src/server/http.ts and index.ts add
POST /api/game, GET /api/stream (SSE, per-seat), POST /api/intent, and static serving of dist/.
src/sim/frame-delta.ts is a purpose-built per-seat board delta for one live push at a time. Found
and fixed along the way: actionMenu(game, seat) only used seat for the hand field, so a server
computing every connected seat's Menu would have handed the acting player's legal moves to a
waiting seat. Verified with a live end-to-end smoke test (2-player game, two SSE streams, a
rejected intent from the wrong seat, an idempotent resend) plus test/server/session.test.ts and
test/redaction.test.ts. Not verified: an actual browser (none available in this environment).

Phase 3: src/server/persistence.ts writes game.json and turn-timings.json, atomic-rewrite-then-
rename. game.ts gained fromMultiplayerSave, fixing a narration-attribution bug found while testing
it (fromSave's replay loop drops the actor argument, invisible in solitaire, unreadable the moment
there's more than one seat — fromSave itself still has this gap, deliberately untouched). Verified
live: server killed and restarted mid-game, both seats reconnected exactly where they left off.

Two rules bugs found while building this: the New Train phase never implemented its car-placement
round (every car of every train was placed by the Superintendent alone, in every mode, all along —
now reads the round position off tray.consist.length); and victory conditions are now one shared,
configurable GameConfig set across solitaire/competitive/coop instead of a fixed length lookup and
a dead firstToTarget condition.

Also folds in the three fixes already released on the patch line as v0.4.9b/c/d: a switching
train's crew badge failing to draw once it left the Office square, an unload that always took the
westmost car regardless of which was picked, and a legal decision that could render with zero
buttons.

docs/testing/0.5.0-test-plan.md and three reported-bug save files (docs/station-master-seed*.json)
included for reproducibility. tools/jitsi-harness/ deliberately left untracked — unrelated
side-project work, not part of this release. 635 tests, 0 failures.
This commit is contained in:
Jesse
2026-08-20 23:50:38 -04:00
parent f9c4d9fa92
commit c3c5cbfeec
52 changed files with 5282 additions and 420 deletions
+69
View File
@@ -0,0 +1,69 @@
/**
* Persistence — Phase 3 of `docs/architecture/multiplayer.md` (§12 steps 14-15;
* `lobby-and-sessions.md` §6 specifies the exact shape and reasoning).
*
* One game per process (Phase 2's scope, unchanged) — two files in `DATA_DIR`, no index and no
* `gameId`, both deferred to Phase 4's multi-game generalization same as the server core deferred
* them. Every write is a full-file atomic rewrite (write to `.tmp`, `rename` over the real path)
* rather than true on-disk appending: §6 says the storage mechanism is genuinely open as long as the
* LOGICAL history is never rewritten or reordered, which a full rewrite of an always-growing array
* satisfies — and at the measured scale (~350 intents, a few hundred bytes per game) there is nothing
* to optimize yet.
*/
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { SavedGame, TurnTiming } from './session.ts';
const GAME_FILE = 'game.json';
const TIMINGS_FILE = 'turn-timings.json';
type PersistedGame = SavedGame & { engineVersion: string };
async function atomicWrite(path: string, text: string): Promise<void> {
const tmp = `${path}.tmp`;
await writeFile(tmp, text);
await rename(tmp, path);
}
export async function writeGame(dataDir: string, saved: SavedGame, engineVersion: string): Promise<void> {
await mkdir(dataDir, { recursive: true });
const payload: PersistedGame = { engineVersion, ...saved };
await atomicWrite(join(dataDir, GAME_FILE), JSON.stringify(payload, null, 1));
}
export type LoadResult =
| { found: false }
| { found: true; ok: true; saved: SavedGame }
/** §12 step 15 — refused explicitly, never silently replayed under the wrong rules. */
| { found: true; ok: false; storedVersion: string; currentVersion: string };
export async function loadGame(dataDir: string, currentVersion: string): Promise<LoadResult> {
let text: string;
try {
text = await readFile(join(dataDir, GAME_FILE), 'utf8');
} catch {
return { found: false };
}
const payload = JSON.parse(text) as PersistedGame;
if (payload.engineVersion !== currentVersion) {
return { found: true, ok: false, storedVersion: payload.engineVersion, currentVersion };
}
const { engineVersion: _engineVersion, ...saved } = payload;
return { found: true, ok: true, saved };
}
/** Appended once per closed turn span (`GameSession.intent`'s `timing` result) — read-modify-write at
* this scale rather than real appending, same reasoning as `writeGame`. */
export async function appendTiming(dataDir: string, timing: TurnTiming): Promise<void> {
await mkdir(dataDir, { recursive: true });
const path = join(dataDir, TIMINGS_FILE);
let existing: TurnTiming[];
try {
existing = JSON.parse(await readFile(path, 'utf8')) as TurnTiming[];
} catch {
existing = [];
}
existing.push(timing);
await atomicWrite(path, JSON.stringify(existing, null, 1));
}