Files
station-master/test/redaction.test.ts
T
Jesse.MarkowitzandClaude Opus 5 45580d8b61 v0.7.3 — a game that asks before it ends, and a results screen worth reading
Two issues off the tracker, and they are halves of one thing: the end of a game.
Neither ships on the 0.4.9 line — Jesse's call, that line may be complete and
these are not fixes people mid-playtest need.

EXTENDED PLAY (#11). The official result is settled at the original game length
and never changes: in a five-Day game extended to eight, the winner is whoever
led at the end of Day 5. Extending grants exactly one Day and the question is put
again at the end of it — solitaire the player decides alone, multiplayer it is
unanimous and one refusal ends it there. Only days-based endings offer it; a §3.4
collision breach is final, during an extended Day exactly as during the scheduled
game.

It could not be a client-side change. `check` refused every intent once `status`
left `active`; the server never loads a `finished` game back into memory; and a
save is `{ seed, config, history }` replayed through the engine, so a "continue"
the history does not record did not happen. Hence a fourth status,
`awaitingExtension`, and a `game.extend` intent. `config.days` never moves —
`extraDays` counts the borrowed Days and `official` freezes the outcome, the
standings and the statistics at the first ending.

THE RESULTS SCREEN (#16). `GAME OVER — revenueFloor` was `outcome.reason`, an
internal enum interpolated into the page at the one moment the game has the
player's whole attention. Every reason now has a sentence with the game's own
numbers in it. Around it: the result and winner, standings, the rules the game
was dealt under, a per-player breakdown, and the railroad — trains through the
Division and how many worked en route, loads made up and broken, passengers, cars
switched, trains destroyed. It shares the Day-end dialog's blocks rather than
reimplementing them, and stays reopenable so continuing does not cost you the
results.

Statistics are folded, not recorded: `state.tally` counts what the event stream
says happened, hooked at `applyIntent` and `advance` because `reduce` never sees
the phase driver's events — and those are the interesting ones. Nothing in the
rules reads it, and it rides the Frame, so multiplayer gets the same numbers as
solitaire from one implementation.

THREE BUGS FOUND IN TESTING, all of which would have shipped:

  - a saved game containing a vote could not be resumed (NO_ACTOR). A history is
    a flat Intent[] with no seat recorded; the replay derives who acted from the
    turn order, which cannot work for an intent every seat may send in any order.
    `game.extend` carries its voter, checked against the authenticated seat.
  - an all-bot game hung on the question for ever. `driveBots` loops on
    `currentActor`, null the moment the game stops, so it cannot cast a vote, and
    the bot-vote driver returned early with no humans to follow.
  - the balance harness became unbounded — `test/sim.test.ts` went from under a
    second to never finishing. `randomBot` took another Day about half the time,
    so every seeded game ran to playGame's 50,000-turn cap. Fixed in the driver,
    not in a policy, so it holds for bots not yet written.

All three have regression tests. 832 tests pass, against 793 before this change.

NOT BUILT, and a correction. #16's own comment said `trainStoodStill` "is emitted
per Stage, so a run of them is exactly the sat-on-a-siding streak". It is not:
reading advance.ts, it fires once per game and only for a train whose profile
sets `stopEarnsPoint` — the X18 Circus — with `stopPointClaimed` preventing a
second. The streak was built, rendered "1 Stage at (0,0)", and was taken out
again. There is no per-Stage "this train did not move" signal in the engine, so
"longest an engine sat on a siding" needs one first; TODO.md #36 records what it
would take, and the Circus set-up is reported instead. Badges remain the second
pass #16 asks for (TODO.md #33), and because the statistics are derived rather
than recorded, that pass can add any of them retroactively to games already
played and saved.

Extended play has not yet been played at a real table (TODO.md #35): the
multiplayer vote has only been driven through `session.intent`, never through two
browsers.

Closes #11
Closes #16

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EAgJSmeV8zrMh55Mj85ESb
2026-08-29 04:23:26 -04:00

142 lines
6.7 KiB
TypeScript

/**
* §7's redaction test — "the single most important test in the plan."
*
* Everything else about `Frame` degrades gracefully; a redaction bug hands one player's hand to
* another and cannot be walked back once it has been seen. `test/multiplayer.test.ts`'s "the view
* shows one seat at a time" section already proves `snapshot(s, ..., viewer)` gives each seat its
* own hand, board and Revenue — spot-checks that today's code does the right thing. This is the
* different, exhaustive check: serialize a seat's whole `Frame` and assert none of some OTHER seat's
* actual secret data appears anywhere in it, so a future careless edit is caught rather than assumed
* safe. No server needed — `snapshot()` and a multi-player `GameState` are all this exercises.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { pump } from '../src/engine/advance.ts';
import { createGame } from '../src/engine/setup.ts';
import type { GameConfig, GameState, PlayerIndex } from '../src/engine/state.ts';
import { developerBot, playGame } from '../src/sim/bot.ts';
import { snapshot } from '../src/sim/view.ts';
const config: GameConfig = {
mode: 'competitive',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
optionalRules: {
reducedVisibility: false,
employeeRotation: false,
emergencyToolbox: false,
},
};
/** Plays a real multi-player game partway — enough for every seat to hold a real, distinct hand. */
function midGame(players: number, seed: number): GameState {
const s = createGame({
id: `redact-${players}`,
seed,
config,
playerNames: Array.from({ length: players }, (_, i) => `p${i}`),
});
const r = playGame(s, developerBot, pump, 400);
// A partial or finished game both exercise real hands — either is fine for this check.
void r;
return s;
}
describe('redaction — a seat\'s Frame never carries another seat\'s secrets', () => {
it('never contains another seat\'s actual hand-card ids', () => {
for (const players of [3, 4]) {
const s = midGame(players, 1000 + players);
for (let viewer = 0 as PlayerIndex; viewer < players; viewer++) {
const serialized = JSON.stringify(snapshot(s, [], null, null, null, false, viewer));
for (let other = 0 as PlayerIndex; other < players; other++) {
if (other === viewer) continue;
for (const cardId of s.decks.hands.get(other) ?? []) {
assert.ok(
!serialized.includes(`"${cardId}"`),
`${players}p seed ${1000 + players}: seat ${viewer}'s Frame contains seat ${other}'s ` +
`hand card id "${cardId}"`,
);
}
}
}
}
});
it('never contains the Home Office deck\'s order or contents, only its count', () => {
for (const players of [3, 4]) {
const s = midGame(players, 2000 + players);
// The deck's own card ids are the thing that must never leak — distinct from any hand's ids,
// since a card once dealt is removed from `homeOffice` (state.ts).
const deckIds = new Set(s.decks.homeOffice);
for (let viewer = 0 as PlayerIndex; viewer < players; viewer++) {
const frame = snapshot(s, [], null, null, null, false, viewer);
assert.equal(frame.deck, s.decks.homeOffice.length, 'deck field is not a plain count');
const serialized = JSON.stringify(frame);
for (const cardId of deckIds) {
assert.ok(
!serialized.includes(`"${cardId}"`),
`${players}p seed ${2000 + players}: seat ${viewer}'s Frame contains a Home Office deck id "${cardId}"`,
);
}
}
}
});
it('never carries the seed or rngState — Frame has no field for either', () => {
// A structural guarantee, not a runtime one: confirmed here so a future field addition to Frame
// that reintroduces one of these is at least forced past a reader of this test, if not the type
// system directly (see Frame in src/sim/view.ts, which carries neither today).
const s = midGame(3, 3003);
const frame = snapshot(s, [], null, null, null, false, 0);
assert.ok(!('seed' in frame), 'Frame gained a seed field');
assert.ok(!('rngState' in frame), 'Frame gained an rngState field');
const serialized = JSON.stringify(frame);
assert.ok(!serialized.includes(String(s.seed)), 'the seed value leaked into the Frame some other way');
});
it('the tally that rides the Frame is aggregate counts, never a card id (Gitea#16)', () => {
// Gitea#16's statistics live on `GameState` and reach a remote client on the Frame, which is
// only safe because nothing in a Tally identifies a card. That is a property of what
// `tally.ts` chooses to count, and nothing in the type system enforces it — so it is asserted
// here, where a future counter that stashed a `cardId` "just for badges" would be caught.
for (const players of [3, 4]) {
const s = midGame(players, 5000 + players);
const secrets = new Set<string>([...s.decks.homeOffice]);
for (const hand of s.decks.hands.values()) for (const id of hand) secrets.add(id);
for (let viewer = 0 as PlayerIndex; viewer < players; viewer++) {
const serialized = JSON.stringify(snapshot(s, [], null, null, null, false, viewer).tally);
for (const cardId of secrets) {
assert.ok(!serialized.includes(`"${cardId}"`), `the tally carries card id "${cardId}"`);
}
}
}
});
it('every seat sees the SAME tally — it is the table\'s account, not a private one', () => {
const s = midGame(3, 5555);
const tallies = [0, 1, 2].map((p) => snapshot(s, [], null, null, null, false, p as PlayerIndex).tally);
for (const t of tallies) assert.deepEqual(t, tallies[0], 'the tally differs by seat');
});
it('only the viewer\'s own hand and handCount are non-public — everything else matches across seats', () => {
// The redaction surface is four fields (§7), not sixty event types. Cross-check that seats agree
// on everything else a Frame carries about shared state.
const s = midGame(3, 4004);
const frames = [0, 1, 2].map((p) => snapshot(s, [], null, null, null, false, p as PlayerIndex));
for (const f of frames) {
assert.deepEqual(f.timetable, frames[0]!.timetable, 'the public timetable differs by seat');
assert.deepEqual(f.deck, frames[0]!.deck, 'the deck count differs by seat');
assert.deepEqual(
f.players.map((p) => ({ index: p.index, revenue: p.revenue, hand: p.hand })),
frames[0]!.players.map((p) => ({ index: p.index, revenue: p.revenue, hand: p.hand })),
'public standing (names, Revenue, hand COUNTS) differs by seat',
);
}
});
});