Compare commits

..
5 Commits
Author SHA1 Message Date
Jesse.MarkowitzandClaude Fable 5.1 def48201e4 v0.8.6 — a Competitive seat gets its save when the game is over
Jesse's ruling on TODO #117: accept the leak in Co-op; otherwise, save only at the end of
the game. `/api/save` answers 403 SAVE_AFTER_FINISH to a Competitive seat while the game
runs, and serves a Co-op or one-seat game at any time. The Save replay button says why and
stays disabled until the end. Pinned in the HTTP suite; documented in rules.md §6.4.

Also corrects the 0.8.3 changelog entry: 0.8.2's notes did name the Second Section card
going into the deck; what was missing was the save check after it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FrCWubm9GAftYCm2hWdKwK
2026-09-29 17:31:23 -04:00
Jesse.MarkowitzandClaude Fable 5.1 04ca74c365 v0.8.5 — housekeeping from the audit, and the playtest line retired
The third release from the audit; nothing a player sees changes. CHANGELOG has the detail.

The 0.4.9 playtest line is no longer maintained (Jesse, 2026-09-29): the deploy rule that
existed for it is gone and #85 is moot. The table test (#39 #35 #42a #40) is closed — every
line of the checklist was met at a table. #46 is done and cannot regrow: the 36 unused
declarations are removed and `noUnusedLocals`/`noUnusedParameters` are on; two of them were
dead bot functions from rejected candidates the round said it had deleted. The documents no
longer teach `trainCapSlack` (a knob that throws), point at `as-built.md` (deleted in 0.8.2),
model `officeType` (the engine says `tier`) or describe `collisionOccurred` (never emitted);
the README's account of bot flags now matches the bot's. Five playtest saves committed in
`docs/` against the repository's own rule are in the ignored `playtests/`.

What the audit found and did not fix is written down as TODO #112-#117, each with its reason.
#112 is `docs/plans/structure.md`, the proposal for `http.ts`, `main.ts` and `check`. #117 —
`/api/save` hands a seat the seed mid-game — waits on a conversation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FrCWubm9GAftYCm2hWdKwK
2026-09-29 17:02:33 -04:00
Jesse.MarkowitzandClaude Fable 5.1 e47cd3d400 v0.8.4 — the multiplayer transport: server and browser
The second release from the audit. Every fault here was invisible in solitaire, and four of
the five server faults were in the one file no test had ever stood up; `http.ts` now has an
end-to-end suite on a real port. CHANGELOG has the reasoning.

SERVER. Leaving a lobby freed the chair and kept the token, so a leaver could stream and
move for whoever took the seat next — revoked now, in memory and on disk. The browser
numbered intents from 1 per page load while the server remembered the seat's last number,
so the first move after a reload was swallowed as a resend — the connect push carries the
count and the client continues from it. Nothing serialised moves within a game and every
write shared one `.tmp` name, so two moves at once tore `game.json` (measured: 6 of 200),
and the boot's bare `JSON.parse` then took every game down — per-path write queues, a
per-game move queue, and a boot that skips one bad file. An error after the SSE head was
sent crashed the process. Bodies were unbounded before any secret check.

BROWSER. A double-click did the thing twice: one submit in flight at a time. A failed
submit is `false`, not an unhandled rejection. The documentation renderer flattened nested
bullets into a literal "- " mid-sentence on the published home-deck page. The make-up panel
promised cars the engine refuses; it asks `acceptsCar` now.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FrCWubm9GAftYCm2hWdKwK
2026-09-29 17:02:32 -04:00
Jesse.MarkowitzandClaude Fable 5.1 4d222a7eba v0.8.3 — the engine half of the audit, and the deal 0.8.2 silently changed
Seven rules faults and one dealing fault, from a four-way code audit (engine, server,
client, tests) read against the code before anything was acted on. Each is pinned by a
test that failed first. CHANGELOG has the reasoning; this is the list.

THE DEAL. 0.8.2 put the Second Section card into the deck after its save check had run
and without a line in its notes. A deck one card larger shuffles differently from the same
seed, so every save on the test server refused at move 3 — the boot log shows thirteen of
thirteen — while the release notes said three would resume. `withSavedDeal` (was
`withSavedOpening`) now sets `secondSectionCard: false` for a config that predates the
setting, and the thirteen replay exactly as 0.8.2 described: three resume, ten refuse, the
same ten at the same moves.

THE RULES. `check` never tested that a switching tray was in the actor's own district, so
a rival's train could be shunted and the rival charged the Moves. Occupancy matched on
coordinates alone, so a rival's crew blocked your track. A Department draw that emptied the
deck duplicated the drawn card and destroyed the refill card. The unjam cleared the first
load rather than the one named. The collision floor could not fire in Stage 12. The
Expedite fault was charged once per clearance question rather than once per phase. A train
held at the Limits was only ever released by another arrival, never by a departure.

Docs: rules.md describes each as built (and no longer says an Expedited train departs at
Shift Change — that was v0.4.8's reading, corrected in v0.4.9's code and never in the
document); game-state.md's collision-floor note now matches the code.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FrCWubm9GAftYCm2hWdKwK
2026-09-29 17:02:31 -04:00
Jesse.MarkowitzandClaude Opus 5 6f2a8dff09 The guide still has the workshop showing — TODO #111
Jesse's read of the rendered documentation after 0.8.2: dramatically better, and still
carrying too much of what was said about the game rather than what the game is. Four
things to fix, recorded with the measurements so the pass can start without re-surveying.

SECTION NUMBERS, 25 of them — rules 11, home-deck 5, mainline-deck 5, components 4,
quickstart 0. Two problems in the same notation. Sections 8.1, 8.2, 8.3, 10, 2.2 and the
7 cited by the deck documents resolve to nothing published: they are the prototype
rulebook's numbering, and rules.md:456 is a section whose own heading is named after it.
Sections 3.5 and 4.2 through 4.6 do resolve, because rules.md numbers its headings, but a
reader has to go counting. The renderer settles the fix: slug() in scripts/markdown.ts
strips a leading number, so a numbered reference has no anchor to point at and a
cross-reference has to become a named link. Do that first and the rest is mechanical.

REPOSITORY PATHS — four documents cite src/engine/content.ts to vouch that a table is
generated. The guarantee is worth keeping; the path is not.

CARD COUNTS, which reverses a standing ruling. #15a's "deliberately NOT including card
counts per category" was Jesse's call of 2026-08-22 and this is the same person reversing
it, so that entry is marked reversed here rather than left to read as current. The two
places the ruling is written into the documents are named. Generation answers the
staleness the ruling guarded against: every catalogue row already carries copiesInDeck or
copies, so the generator gains a column and the existing test keeps it honest. The one
hard part is recorded too — since 0.8.2 the office cards dealt depend on the starting
Office, so a printed count has to say it describes the default Depot opening.

BUILD-STATUS COMMENTARY, with the line that must not be crossed. "It is not implemented,
and never has been" and the live/dormantSolo/unbuilt column are an engineering status
printed for players, and they go. The facts underneath them do not: a player needs to know
the opponent-directed cards are not dealt and that the Interchange does not sort cars. A
pass that deletes the sentence and the fact together makes the documents wrong instead of
clean.

No code, no documents and no version touched — this is the worklist only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUizFYCMHRWhbWwXhp7WPR
2026-09-23 07:43:24 -04:00
64 changed files with 1960 additions and 5003 deletions
+223
View File
@@ -19,6 +19,229 @@ page as `v0.1.0 · <sha> · <date>`, so what is deployed can always be identifie
--- ---
## 0.8.6 — 2026-09-29
### A Competitive seat gets its save when the game is over
`/api/save` handed any seat its save — seed and all — while the game ran. The comment said every
move was already on the player's screen, which was true of the moves and false of the seed, and the
seed is every rival's hand and the order of the deck: the exact thing the shared log strips. But a
save without a seed is not a save. **Jesse's ruling: accept the leak in Co-op; otherwise, save only
at the end of the game.** A Competitive seat is refused with `SAVE_AFTER_FINISH` until the game is
finished, and the Save replay button says why and waits; a Co-op table, which has nothing to hide
from itself, and a one-seat game download at any time.
### A correction to the 0.8.3 entry
It says the Second Section card went into the deck "without a line in its notes". 0.8.2's release
notes did name it — "ordering a Second Section costs the card, which was declared in the rules and
never actually dealt". What was missing was not the line but the save check after the change; the
process rule in `TODO.md` stands as written.
---
## 0.8.5 — 2026-09-29
The third release from the audit: housekeeping. Nothing a player can see changes; what changes is
what the repository says about itself and what the build refuses.
### The playtest line is retired
The 0.4.9 line — the build handed to playtesters since August, ported by hand from `main` and
diverging structurally by 0.7 — is no longer maintained (Jesse, 2026-09-29). Its worktree and
branches are deleted, the "deploy from the right line" rule is gone with it, and #85 (the line
being behind on a ruling) is moot. The public site serves the last 0.4.9h build until `npm run
deploy:web` is run once from `main`.
### The table test is closed
#39, #35, #42a and #40 — the Yard Office offer, the Red Flag hold, the loaded Extra, extended play
through two browsers, the setup screen, the save-file sentence — were all met at a table. The
section stays in `TODO.md` for the one measurement it holds: which interruptions fire on their own
and which have to be set up.
### #46, and the flag that keeps it at zero
The unused-declaration count had gone 29 → 40 → 36 across six weeks because nothing ran the flag.
All 36 are gone and `noUnusedLocals` + `noUnusedParameters` are on in `tsconfig.json`. Two were dead
bot functions from rejected candidates the round said it had deleted (`wouldBuryTheEngine`,
`strandedWantedCars`); `isLegal` and `restoreRng` had no callers; `trayySeat` was a typo; the ten
in `sim/replay.ts` were imports, so #48 (what that viewer is for) is untouched.
### What the documents said that was not so
`README.md`, `compare.ts`, `save-replay.ts` and the bot all taught `trainCapSlack`, a knob deleted
weeks ago — `parseTweaks` throws on it. The README also said a flag is deleted when adopted while
the bot's own doc block says every flag is a permanent ablation of an adopted heuristic; the bot was
right, and had two doc blocks back to back, the first attached to nothing. `card-reference.md` sent
readers to `as-built.md`, deleted in 0.8.2; three `TODO.md` entries and two architecture pages said
the same. `game-state.md` modelled `officeType`, which the engine calls `tier`; `protocol.md`
described a `collisionOccurred` event the engine has never emitted (`trainsDestroyed`). `design.md`
carried its print-and-play paragraph twice. Five playtest saves — seeds, names, an August ruleset —
sat committed in `docs/` against the repository's own rule; they are in `playtests/` now, ignored.
### The audit's leftovers, written down
Everything the four reviewers found that was real and is not fixed is in `TODO.md` §11 as #112-#117,
each with its reason. #112 is `docs/plans/structure.md`: the route table for `http.ts`, five
extractions for `main.ts`, `check` per phase — each naming the test it would make possible. #117 is
the one that needs a conversation: `/api/save` hands a seat the seed mid-game, and a save without a
seed is not a save.
---
## 0.8.4 — 2026-09-29
The second release from the audit: the multiplayer transport, server and browser. Every fault here
was invisible in solitaire, and four of the five server faults were in the one file no test had
ever stood up — `http.ts` now has an end-to-end suite that binds a real port.
### A player who left could play the seat the next arrival took
Leaving a lobby freed the chair and kept the token: it stayed in memory and on disk, and the next
player to join was given the vacated chair. So once the game began, the leaver's browser still held
a token for that seat — `/api/stream` served it the newcomer's hand and menu, `/api/intent` let it
move for them, and its stream connection displaced theirs. `lobby-and-sessions.md` had said all
along that Leave "drops the token"; the code did not. It does now, for a player's own leave and for
the host's remove alike, in memory and in `sessions.json`, before the chair is offered to anyone.
### The first move after a reload could be silently swallowed
The browser numbered its intents from 1 on every page load; the server remembers a seat's last
accepted number for the life of the game and answers a repeat with "already applied". A seat that
had made one move, reloaded, and clicked again sent `seq: 1` twice — ok, nothing happened, nothing
pushed, the click looked dead. The connect push now carries the server's count (`lastSeq`) and the
client continues from it, never backwards.
### Two moves at once could tear the save, and a torn save took every game down
Nothing serialised moves within a game: the handler awaits the disk write between applying and
answering, and two moves arriving together interleaved across it — both applied in memory, both
writing the same `game.json.tmp`. Measured at 200 rounds of two concurrent writes: every round lost
one to `rename` ENOENT, six left the file as invalid JSON. And the boot did a bare `JSON.parse` on
each save at the top level, so one such file was a crash loop with every game on the server
unreachable. Three fixes, each pinned: every write to a path queues behind the one before it with a
unique temp name; each game's moves run one at a time through apply, persist, answer, broadcast; and
an unreadable save is logged and skipped rather than fatal, as is one whose replay throws.
### One error after the SSE head was sent was a whole-server crash
The handler's one `catch` answered every error with a JSON 500 — and on a response whose head was
already written (both streams, static files) `writeHead` throws inside the catch, with nothing above
it. Node exits on an unhandled rejection. `sendJson` now ends such a response instead; the lobby's
host-reassignment write and the static file stream have their own error paths; and the 500 no longer
echoes the error's message, which for a disk error carried the data directory's absolute path.
### Anyone could exhaust the process's memory with one POST
Request bodies were buffered whole, with no cap, before any secret was checked. A 64 KiB limit —
the largest body any route has a use for is a few hundred bytes — answers 413; a body that is not a
JSON object answers 400 rather than surfacing as a 500.
### In the browser
**A double-click did the thing twice.** The page redraws the same menu the instant a submit is sent,
so a second click before the round trip posted a second, fresh `seq` for the same option, and the
server applied it again: two cards drawn, two Moves spent, two cars coupled. One submit in flight at
a time now; a click that lands during one is dropped, and the push is milliseconds away. A network
failure or a non-JSON answer is `false` from `submit` rather than an unhandled rejection.
**The documentation renderer flattened nested bullets.** The comment said nesting was rendered by
recursion; the code appended the nested bullet to its parent as text, and the published home-deck
page read "…knows. - ABS Signals is the exception…" with a literal dash mid-sentence. Real nesting
now, and the test renders the real document to prove the dash is gone.
**"Still needs 2 boxcar" behind a caboose.** The make-up panel counted by category and promised cars
the engine would refuse: nothing couples behind a caboose (§A.3), so it printed a need while no yard
chip lit and the only offer was to send the train out as it stands. It asks `acceptsCar` per
category now, the way the engine's own make-up report does, and says why when nothing more couples.
---
## 0.8.3 — 2026-09-29
The first of three releases from a code audit (engine, server, client, tests and hygiene, each read
by a separate reviewer and every finding re-verified against the code before it was acted on). This
one is the engine: seven rules faults and one dealing fault, each pinned by a test written to fail
first. **Every save on the test server was replayed under this build before release** — and that is
how the dealing fault was found, because under 0.8.2 none of them replayed at all.
### 0.8.2 stranded every game on the server, and said it stranded ten
The 0.8.2 notes said three of thirteen saves would resume. The server's own boot log, read for this
release, refused all thirteen at **move 3**, `CARD_NOT_IN_HAND` — including the game saved by 0.8.1.0
the notes had counted as safe. A refusal at move 3 is not a rule; it is a different deal.
The **Second Section card went into the deck in 0.8.2** (Q9, one copy — it had been defined and
never dealt), after that release's save check had been run and without a line in its notes. A deck
one card larger shuffles into a different order from the same seed, so every save older than the
card was replaying a different railroad from intent one. `withSavedOpening` could not help: it names
the opening, and the opening was not the problem.
Now `withSavedDeal`, and it names both. `secondSectionCard` is a house rule with no dial — a fact
about how a game was dealt, kept for the same reason `startingOffice` is — set false for a saved
config that predates the setting and true for everything dealt since. Under this build the thirteen
replay exactly as 0.8.2's notes described: **three resume, ten refuse, the same ten at the same moves
for the same rules.** The process rule this breaks is already written down ("say which way games in
progress go, every time"); what it adds is that the save check has to be the LAST thing before the
tag, not a thing done during the work.
### A player could switch a rival's train, and the rival paid for it
`check` resolved a switching tray with no seat test at all. The legal-move generator filtered trays
by seat; `check` did not; the server validates with `check` alone. Every district opens on the same
coordinates, so a destination legal for your own tray at (0,0) was "legal" for a rival's tray at
THEIR (0,0) — and the Moves came off the rival's turn, because `trayMoved` charges whoever sits in
the district the tray is in. All four switching intents now refuse a tray outside the actor's own
district with `NO_SUCH_TRAY`. Invisible in solitaire, which is why it lasted.
### A rival's crew blocked your own track
`occupancyFor().trayAt` matched on coordinates alone, so a crew standing at seat 0's (0,2) was
"another train standing here" at seat 1's (0,2) — a phantom that refused Moves and closed the Yard
Office walk in any game with more than one seat. It asks the seat now.
### Drawing the last card off a Department could duplicate it and destroy the refill
When a Department draw emptied the Home Office deck, the reshuffle was computed from the table
BEFORE the draw and the refill had been reduced: it swept up the card being drawn and missed the
refill card. The reducers then dealt the drawn card into the new deck while the refill card, moved
onto a pile the reshuffle wiped a moment later, left the game. Proven by counting — 47 cards in, 46
distinct out — and fixed by describing the sweep as the table will be after the events ahead of it.
### The unjam cleared the first load, not the one you named
`facilityUnjammed` carried no index, so the reducer cleared the FIRST load on MEN | AT | WORK and the
first car of the named type in a box. With an inbound tank load on MEN and a stranded outbound
hopper on WORK, unjamming the hopper deleted the tank load, sent a loaded hopper to the yard and
left the jam. The event carries the index now; events are regenerated on replay, so no save changes.
### The collision floor could not fire in Stage 12
`shiftChange` reset the Day's collision count at the rollover and only then judged it, so a breach
reached in the last Stage of a Day read as zero. The limits are judged on the Stage just played,
before the Day rolls over. `docs/architecture/game-state.md` had said the check was immediate; it
never was, and it now says what happens.
### The Expedite fault was charged once per question
The Mainline phase is re-entered from the top after every clearance, Yard Office and Red Flag
ruling, and the Q3 fault loop at the top ran unguarded — an Expedited train left on a siding was
fined once per interruption. Once per phase now. The rules document had also still described the
v0.4.8 reading of Expedite (departs at Shift Change), corrected in the code in v0.4.9; both passages
now describe the rule as built.
### A train held at the Limits was only ever released by another arrival
`arriveAtOffice` promised "held at the Limits until an A/D track frees up", and the only release
was inside `arriveAtOffice` for a DIFFERENT train. An Office that emptied by departures kept its
held train at the Limits for the rest of the game, invisible — no transit, no A/D track, no part in
the clearance check. At the end of every Mainline phase, held trains now take any free tracks in
the order they were held, and the history says a departure freed the track rather than naming an
arriving train that does not exist.
---
## 0.8.2 — 2026-09-23 ## 0.8.2 — 2026-09-23
A playtest read back against the save file, and the rules that came out of it. Nine questions were A playtest read back against the save file, and the rules that came out of it. Nine questions were
+7 -6
View File
@@ -84,7 +84,7 @@ station-master/
├── CHANGELOG.md ← what changed and why, in detail, commit to commit ├── CHANGELOG.md ← what changed and why, in detail, commit to commit
├── TODO.md ← open questions, provisional numbers, things to come back to ├── TODO.md ← open questions, provisional numbers, things to come back to
├── docs/ ├── docs/
│ ├── rules/ ← the ruleset, card reference, glossary, decision record │ ├── rules/ ← the ruleset, glossary, decision record (the card tables are in docs/*-deck.md)
│ ├── architecture/ ← how it is built, and what the pieces are │ ├── architecture/ ← how it is built, and what the pieces are
│ ├── plans/ ← worked plans for a single change, kept for the reasoning │ ├── plans/ ← worked plans for a single change, kept for the reasoning
│ └── design/ ← board layout studies and rendering samples │ └── design/ ← board layout studies and rendering samples
@@ -124,7 +124,7 @@ syntax**: no `enum`, no parameter properties, no namespaces. `tsconfig.json` enf
```sh ```sh
node src/sim/harness.ts 200 # how the bot does, with the funnel node src/sim/harness.ts 200 # how the bot does, with the funnel
node src/sim/compare.ts 1600 trainCapSlack=1 # one change, paired against the current bot node src/sim/compare.ts 1600 noValueLays=1 # one ablation, paired against the current bot
``` ```
**Never judge a heuristic on an unpaired run.** Revenue has σ ≈ 9 across games, so two runs of the **Never judge a heuristic on an unpaired run.** Revenue has σ ≈ 9 across games, so two runs of the
@@ -134,10 +134,11 @@ standard error at ±0.13, in under two minutes. Keep a change at **t ≥ 3**, an
better/worse/identical split beside the mean: a gain carried by a few rescued games is a different better/worse/identical split beside the mean: a gain carried by a few rescued games is a different
claim from one spread across the field. claim from one spread across the field.
Variants come from `makeDeveloperBot(tweaks)`. A tweak is **temporary** — when it measures well it Variants come from `makeDeveloperBot(tweaks)`. Every flag is an **ablation**: it turns OFF a
becomes the default and the flag is deleted in the same commit; when it measures badly it is deleted heuristic that is now the bot's default play (`noPlanSwitching`, `noValueLays`, …), so an adopted
with the finding recorded in `CHANGELOG.md`. A bot that accumulates switches nobody can account for heuristic can be re-measured when the deck or the rules move under it. A candidate that measures
is the thing this machinery exists to prevent. badly is deleted, with the finding recorded in `CHANGELOG.md` — a switch nobody turns on is a switch
nobody maintains. `compare.ts` lists the flags it accepts and refuses any other name.
## Design notes worth knowing ## Design notes worth knowing
+224 -29
View File
@@ -54,8 +54,13 @@ Not items. Things that are true of every change, and that have gone wrong when s
- **Commits and tags are GPG-signed and I cannot make them.** Stage the work, write the message to - **Commits and tags are GPG-signed and I cannot make them.** Stage the work, write the message to
a file, hand over a `!` command. Tags must be `git tag -s` — a bare `git tag` makes a lightweight a file, hand over a `!` command. Tags must be `git tag -s` — a bare `git tag` makes a lightweight
tag and `git push --follow-tags` skips it *without any error*. tag and `git push --follow-tags` skips it *without any error*.
- **Deploy from the right line.** `npm run deploy:web` defaults to the same destination on both - **There is one line now.** The 0.4.9 playtest line was retired on 2026-09-29 (Jesse: "no longer
lines, so deploying from `station-master/` silently replaces the playtesters' build with main's. being maintained"), so `npm run deploy:web` from this directory is the deploy. The public site
serves the last 0.4.9h build until that is run once from `main`.
- **The save check is the LAST thing before the tag, not a thing done during the work.** 0.8.2
replayed every server save, wrote "three resume, ten refuse" into its notes, and then put a card
into the deck — and shipped with zero of thirteen resuming. Replay the server's saves against the
exact tree being tagged (`tryResumeSession`, not `fromSave`).
- **A failing test written before the fix is the only thing that proves a fix.** Three releases - **A failing test written before the fix is the only thing that proves a fix.** Three releases
(v0.7.5 through v0.7.8) each reported the same bug fixed, and each fixed something real that was (v0.7.5 through v0.7.8) each reported the same bug fixed, and each fixed something real that was
not the reported fault, because every verification read what the SERVER served rather than not the reported fault, because every verification read what the SERVER served rather than
@@ -97,7 +102,7 @@ Not items. Things that are true of every change, and that have gone wrong when s
## Sections ## Sections
1. **Play it at a table** — #39 #35 #42a #40 1. **Play it at a table** — CLOSED 2026-09-29: #39 #35 #42a #40 all confirmed at a table
2. **The common board, and watching play happen — Gitea#20** — #13 #15 #18 #75 2. **The common board, and watching play happen — Gitea#20** — #13 #15 #18 #75
3. **Multiplayer, sessions and operations** — #8 #7 #76 #77 #79 3. **Multiplayer, sessions and operations** — #8 #7 #76 #77 #79
4. **The screen** — #44 #81 #33 #36 4. **The screen** — #44 #81 #33 #36
@@ -106,7 +111,8 @@ Not items. Things that are true of every change, and that have gone wrong when s
7. **Play balance** — #61 #62 #63 #64 #67 #68 #69 #70 #71 #72 #73 #66 #65 #74 7. **Play balance** — #61 #62 #63 #64 #67 #68 #69 #70 #71 #72 #73 #66 #65 #74
8. **The bot** — #104 #105 #106 #41 #57 #59 #54 #58 #55 #56 #60 8. **The bot** — #104 #105 #106 #41 #57 #59 #54 #58 #55 #56 #60
9. **Code health and housekeeping** — #46 #45 #84 #87 9. **Code health and housekeeping** — #46 #45 #84 #87
10. **Documentation and assets** — #15a #86 #88 10. **Documentation and assets** — #15a #86 #88 #111
11. **The 2026-09-29 audit — what it found and did not fix** — #112 #113 #114 #115 #116 #117
Then, at the back: **Reference** (the measurements, rulings and rejected approaches behind the Then, at the back: **Reference** (the measurements, rulings and rejected approaches behind the
items above) and **Done** (everything closed, kept because several of them are the only record of a items above) and **Done** (everything closed, kept because several of them are the only record of a
@@ -116,6 +122,10 @@ ruling or a lesson).
## Play it at a table ## Play it at a table
**CLOSED 2026-09-29.** Jesse: "The table test was completed." Every item and every checklist line
below was met at a table; the section is kept because the measurement in *Preparing the session*
(which interruptions fire by themselves and which have to be set up) is the only record of it.
The largest gap in the project, and none of it is a coding gap. Features are shipped, packed, The largest gap in the project, and none of it is a coding gap. Features are shipped, packed,
running on `phoenix.local` — and the items below name the ones no person has met at a board. running on `phoenix.local` — and the items below name the ones no person has met at a board.
Everything else in this file waits behind a release; this waits behind an afternoon. Everything else in this file waits behind a release; this waits behind an afternoon.
@@ -188,41 +198,41 @@ developer present; what it needs is somebody writing down what they saw.
**Game A — `days: 1`, two humans, two browsers.** Reaches the extension vote in one Day. **Game A — `days: 1`, two humans, two browsers.** Reaches the extension vote in one Day.
- [ ] The vote appears **in front of both players**, not underneath the results dialog (#35 — this is - [x] The vote appears **in front of both players**, not underneath the results dialog (#35 — this is
the exact shape of the bug v0.7.9 fixed). the exact shape of the bug v0.7.9 fixed).
- [ ] While one player has not voted, the other's turn chart says **who** it is waiting on (#35). - [x] While one player has not voted, the other's turn chart says **who** it is waiting on (#35).
- [ ] **Close the second laptop mid-vote.** Does the first player learn why nothing is happening, and - [x] **Close the second laptop mid-vote.** Does the first player learn why nothing is happening, and
does "waiting on Carol" still read once Carol is gone? (#35 — never tested.) does "waiting on Carol" still read once Carol is gone? (#35 — never tested.)
- [ ] Reopen it. The history panel comes back **populated**, not empty, and the board is current - [x] Reopen it. The history panel comes back **populated**, not empty, and the board is current
(the v0.7.9.5 reconnect fix, never seen by a person). (the v0.7.9.5 reconnect fix, never seen by a person).
- [ ] Vote yes. The extra Day begins and the official result is **unchanged** from when the - [x] Vote yes. The extra Day begins and the official result is **unchanged** from when the
timetable ran out (#35). timetable ran out (#35).
**Game B — ordinary length, two humans, bots to fill.** Everything else. **Game B — ordinary length, two humans, bots to fill.** Everything else.
- [ ] Somebody **builds a Yard Office** and lets a freight train (no coach) arrive at it. The offer - [x] Somebody **builds a Yard Office** and lets a freight train (no coach) arrive at it. The offer
interrupts the Mainline Phase and asks a question mid-thought — is it legible, and does it say interrupts the Mainline Phase and asks a question mid-thought — is it legible, and does it say
which train? (#39) which train? (#39)
- [ ] Somebody **holds the Red Flags card** while their A/D tracks are full, so an arrival would - [x] Somebody **holds the Red Flags card** while their A/D tracks are full, so an arrival would
collide. The hold is offered out of phase (#39). collide. The hold is offered out of phase (#39).
- [ ] A **loaded Extra** is made up and run (#39 — the third of its three). - [x] A **loaded Extra** is made up and run (#39 — the third of its three).
- [ ] Watch a bot take a whole turn: does the district follow it, does the lit pile catch the eye, - [x] Watch a bot take a whole turn: does the district follow it, does the lit pile catch the eye,
does the caption say who and what? (v0.8.0) does the caption say who and what? (v0.8.0)
- [ ] Find the speed that suits you and say what it is — it becomes the committed default. - [x] Find the speed that suits you and say what it is — it becomes the committed default.
- [ ] Let the board fall behind, then press **Skip**. Nothing is lost; the history has it all. - [x] Let the board fall behind, then press **Skip**. Nothing is lost; the history has it all.
- [ ] End a Day with a collision on it: the summary reads "N on Day D, N in all" and cannot - [x] End a Day with a collision on it: the summary reads "N on Day D, N in all" and cannot
contradict itself (v0.8.0.2). contradict itself (v0.8.0.2).
**Solitaire, five minutes, alone.** **Solitaire, five minutes, alone.**
- [ ] Click through **every field** on the setup screen and confirm the dealt game matches what was - [x] Click through **every field** on the setup screen and confirm the dealt game matches what was
chosen (#42a). chosen (#42a).
**Whatever else happens.** The two bugs that came out of the 0.7.4-0.7.9 runs were both things **Whatever else happens.** The two bugs that came out of the 0.7.4-0.7.9 runs were both things
nobody set out to test. Write down anything that reads wrong, even where the rule underneath is nobody set out to test. Write down anything that reads wrong, even where the rule underneath is
right — most of this release's defects were legible-but-wrong rather than broken. right — most of this release's defects were legible-but-wrong rather than broken.
- [ ] **#39** — **None of v0.7.4 has been played by a human.** The Yard Office offer, the Red Flag - [x] **#39** — **CONFIRMED at a table, 2026-09-29.** Originally: **None of v0.7.4 has been played by a human.** The Yard Office offer, the Red Flag
hold and its out-of-phase prompt, and the loaded-Extra make-up rules are tested end to end, hold and its out-of-phase prompt, and the loaded-Extra make-up rules are tested end to end,
packed, and running on `phoenix.local` — and nobody has met any of them at a board. **Two are packed, and running on `phoenix.local` — and nobody has met any of them at a board. **Two are
interruptions that stop the Mainline Phase and put a question in front of somebody interruptions that stop the Mainline Phase and put a question in front of somebody
@@ -230,7 +240,7 @@ right — most of this release's defects were legible-but-wrong rather than brok
happens by itself — 0/10 games. See Preparing the session above for what to set up.** See happens by itself — 0/10 games. See Preparing the session above for what to set up.** See
**Reference · #39**. **Reference · #39**.
- [ ] **#35** — **Extended play has never been played at a real table.** It was verified over the HTTP - [x] **#35** — **CONFIRMED at a table, 2026-09-29.** Originally: **Extended play has never been played at a real table.** It was verified over the HTTP
API, which renders no dialog — and when a human first reached it in a browser it was unusable API, which renders no dialog — and when a human first reached it in a browser it was unusable
(fixed in v0.7.9). The multiplayer vote has still never been driven through two browsers: what a (fixed in v0.7.9). The multiplayer vote has still never been driven through two browsers: what a
second player sees while waiting, and whether "waiting on Carol" reads once Carol has closed her second player sees while waiting, and whether "waiting on Carol" reads once Carol has closed her
@@ -426,8 +436,9 @@ need RAR or Jesse rather than code.**
Gitea#14 closed with those ten listed on the issue so they do not vanish with it. See Gitea#14 closed with those ten listed on the issue so they do not vanish with it. See
**Reference · #83**. **Reference · #83**.
- [ ] **#85** — The 0.4.9 playtest line is behind on a rules ruling, and that was checked rather than - [x] **#85** — **MOOT 2026-09-29** — the 0.4.9 playtest line is retired, so it is behind on every ruling
assumed. See **Reference · #85**. since and that no longer matters. Originally: behind on a rules ruling, checked rather than assumed.
See **Reference · #85**.
- [x] **#107** — **May a Small Yard put cars on the NOSE of the engine? YES** — raised by Jesse - [x] **#107** — **May a Small Yard put cars on the NOSE of the engine? YES** — raised by Jesse
2026-09-17, discussed the same day and built. Two sources disagreed: the v0.4.5 card text says 2026-09-17, discussed the same day and built. Two sources disagreed: the v0.4.5 card text says
@@ -580,9 +591,11 @@ non-player advantage — it reads the board, never the deck.
Dead code, untrustworthy tests, and things carried but not used. Individually small; the reason they Dead code, untrustworthy tests, and things carried but not used. Individually small; the reason they
are one section is that each one found the next. are one section is that each one found the next.
- [ ] **#46** — 29 unused declarations across 14 files, and the build does not run the flag that finds - [x] **#46** — **DONE 2026-09-29 (v0.8.5).** The 36 it had regrown to are gone and
them. **The flag matters more than the 29** — two are Gitea#18 leftovers in one file, one found `noUnusedLocals` + `noUnusedParameters` are on in `tsconfig.json`, so the list cannot regrow.
by hand and the other missed. Do #48 first; it settles ten of them. See **Reference · #46**. The ten in `sim/replay.ts` were unused IMPORTS, removed without deciding #48 — that question is
untouched. Two dead bot functions (`wouldBuryTheEngine`, `strandedWantedCars`) were rejected
candidates left behind; `isLegal` and `restoreRng` had no callers. See **Reference · #46**.
- [ ] **#84** — Five test fixtures pinned a seed and meant "a game like this". All five broke on - [ ] **#84** — Five test fixtures pinned a seed and meant "a game like this". All five broke on
Gitea#14 for that reason. See **Reference · #84**. Gitea#14 for that reason. See **Reference · #84**.
@@ -606,6 +619,93 @@ What the project says about itself, and what it ships alongside the code.
- [ ] **#88** — `card-reference.md`'s industry table may still be stale beyond Grocer's Warehouse and - [ ] **#88** — `card-reference.md`'s industry table may still be stale beyond Grocer's Warehouse and
the Oil Refinery. See **Reference · #88**. the Oil Refinery. See **Reference · #88**.
- [ ] **#111** — A full pass over the five player-facing documents: strip the playtest commentary and
the pointers into the code, publish the card counts, and take out every section number and
repository-file reference. Jesse's read after the 0.8.2 rendering landed — much better, still
too much of the workshop showing. See **Reference · #111**.
---
## The 2026-09-29 audit — what it found and did not fix
Four reviewers read the engine, the server, the browser client and the sim/tests/hygiene, and every
finding was re-verified against the code before anything was acted on. v0.8.3 (engine), v0.8.4
(transport) and v0.8.5 (housekeeping) took the faults; these are the findings that were real and
were NOT fixed, each with the reason, so nothing quietly evaporates.
- [ ] **#112** — **The structure proposal.** `docs/plans/structure.md`: a route table with auth
wrappers for `http.ts`; five extractions and a `Selection` value for `main.ts`; `check` and
`reduce` split per phase; one `carCategory`; one `Push` type. Each names the test it makes
possible. Ordered by payoff; the first two are afternoons. Do the `http.ts` table before the
next route (#20's display stream).
- [ ] **#113** — **Server faults left as found.** (a) A second SSE connection from the same seat
shadows the first without ending it, and the old socket's close then broadcasts "disconnected"
for a seat that is still there — end the old response on replace, and only announce a close
when the closing response is the live one. (b) Seat tokens travel in URLs on `/api/intent`,
`/api/save`, `/api/session`, and the JOIN SECRET on `/api/lobby/preview?secret=` — every
reverse proxy's access log holds them; `lobby-and-sessions.md` §1 says keep them out. Move to a
header or the body (EventSource forces the two stream routes). (c) `gameCodes` is not seeded
from running games on boot, so a game that survived a restart finishes with `gameCode: ''` in
the index and the admin listing, and `freshGameCode` can reissue its code. (d) `/api/lobby/start`
mutates memory and tells every lobby watcher the game began BEFORE the writes; a failed write
resurrects the lobby on restart with a fresh seed. (e) Secret comparisons are `!==`;
`timingSafeEqual` costs nothing. (f) An admin can mint a claim for a lobby seat that `/api/claim`
then cannot redeem. (g) `everConnected` is never pruned on delete. (h) `body.config` from the
host is never shape-checked — a bad one wedges the lobby at Start with a 500 each time.
- [ ] **#114** — **Client faults left as found.** (a) Rules refusals and transport failures are
invisible: every `void session.submit(...)` discards the `false`, and `lobby.ts`'s `postJson`
has no catch, so a host who presses Start while the server restarts sits on "Starting…" until
a reload. (b) `lobby.ts` reads `localStorage` bare (four sites) where `main.ts` guards every
access — a browser with site storage blocked throws before any button is wired. (c) `claimSeat`
awaits with no try: a 502 leaves the lobby doors drawn and dead. (d) `build-web.ts` stamps
`sha-dirty` for every dirty build of one commit, so two dirty deploys publish byte-identical
module URLs and a returning browser serves stale modules against new HTML. (e) "New game" on
the results screen does `location.search = ''`, which the code elsewhere asserts is a no-op
when the search is already empty — the save is wiped and the player stays on the finished
board; `commitNewGame` has the `reload()` fallback, this button does not. (f) The animation
loop outlives the session: `leavegame` does not reset the step queue, so rejoining another game
runs the old game's steps against the new session until the first push. (g) Seven independent
HTML-escape helpers with differing coverage, none escaping `'`; no test feeds a display name
containing `<` or `"`. No XSS was found; the risk is the next helper.
- [ ] **#115** — **Engine drift left as found.** (a) `maneuver.flyingSwitch` is a weaker copy of
`switch.dropCars` — no `switchingRefusal`, no `engineAt` clamp, no `standingWest` handling — latent
at 0 copies, wrong the day the card is dealt. (b) Car category is spelled three times
(`acceptsCar`, `newTrainPhase`, `isFreight`/`carriesLoad`). (c) `redFlag.play` emits a
`phaseEnded` the reducer ignores — a no-op intent offered whenever the Emergency Toolbox is on;
either the toolbox or the intent is vestigial. **Needs Jesse.** (d) The hand limit is enforced
only on `draw.end`; `switch.end` and `freightAgent.end` let a `sixRandom` hand stay at six all
game, and `card.discard` is ungated by option. (e) `freightAgent.unjam` from an inbound box
returns the car `pooled()` but loaded — the same "coach that can never unload again" 0.8.1.0
fixed for `clearInbound`. (f) `mainlinePhase` iterates a snapshot of trays after `collide`
deletes some, so later per-train logic in that loop reads a dead tray; benign today. (g) A
`Map`-order dependence in candidate ordering that would not survive deserialising state from
JSON with a different key order — worth one comment in `legal.ts`.
- [ ] **#116** — **Test-suite faults left as found.** (a) `test/card-reference.test.ts` REWRITES
`docs/home-deck.md` and `mainline-deck.md` and then compares — when they are stale the test is
red AND the diff to inspect is already gone. Generate to a string and compare. (b)
`test/track.test.ts` asserts on wall-clock elapsed time (`< 5000 ms`) in the default suite.
(c) `test/sim.test.ts` pins 300 games to `seed: 1000 + i*7919` to reach the one where a tank
car is first dropped (#84's shape; it is the seven-minute suite that breaks). (d)
`test/web.test.ts` slices `src/server/http.ts`'s source text between two constant names. (e)
`multiplayer.test.ts` still hard-codes seed 4242 where the playtest line had a seed search.
(f) `package.json`'s `test/**/*.test.ts` only works because dash has no globstar and there is
exactly one nesting level; spell it `test/*/*.test.ts`.
- [x] **#117** — **RULED 2026-09-29 (Jesse): "accept the leak in coop. otherwise save only at end of
game."** Built the same day: `/api/save` answers `403 SAVE_AFTER_FINISH` to a Competitive seat
while the game runs and serves a Co-op or one-seat game at any time; the page's Save replay
button says so and stays disabled until the end. Originally: **`/api/save` hands every seat the seed mid-game — NEEDS JESSE.** The seat's own
save download returns `seed` while the game is active; in Competitive that is every rival's
hand and the deck order, the exact leak `game.ts` strips from the log. But a save without the
seed cannot replay, which is the whole point of a save. Jesse (2026-09-29): "We should discuss
before making changes on this one." Options on the table: serve the seat's save only once the
game is finished; serve it mid-game without the seed (a receipt, not a replay) and with the seed
once finished; or accept the leak in Co-op only. See **Reference · #117**.
--- ---
## Reference — measurements, rulings and rejected approaches ## Reference — measurements, rulings and rejected approaches
@@ -2041,13 +2141,16 @@ unbuilt, each row citing the file that reads it); the same honesty is what makes
reference worth more than a transcription. `enhancementText()` and `mainlineDescription()` are reference worth more than a transcription. `enhancementText()` and `mainlineDescription()` are
the model: prose composed from the data, so a tooltip cannot drift from the rule it describes. the model: prose composed from the data, so a tooltip cannot drift from the rule it describes.
**Deliberately NOT including card counts per category.** Jesse's call in the same breath: the **Deliberately NOT including card counts per category — REVERSED 2026-09-23, see #111.** The
ruling below stood from 2026-08-22 until Jesse asked for the counts to be published; generation
answers the staleness it was guarding against. Read it as history. Jesse's call in the same breath: the
counts move with play balance, so a document that prints them is stale on the next retune. The counts move with play balance, so a document that prints them is stale on the next retune. The
same rule was applied to `content.ts`'s own comments on 2026-08-22 — see the pass recorded in same rule was applied to `content.ts`'s own comments on 2026-08-22 — see the pass recorded in
CHANGELOG for what came out and what was kept. CHANGELOG for what came out and what was kept.
**BUILT 2026-09-07 in v0.7.9.2, completed in v0.7.9.3, as the first of the two options** — a build step writing Markdown, **BUILT 2026-09-07 in v0.7.9.2, completed in v0.7.9.3, as the first of the two options** — a build step writing Markdown,
`scripts/build-card-reference.ts` → `docs/rules/as-built.md`, with `test/card-reference.test.ts` `scripts/build-card-reference.ts` → `docs/rules/as-built.md` (since 0.8.2 the tables are written
into `docs/home-deck.md` and `docs/mainline-deck.md` instead), with `test/card-reference.test.ts`
re-running the generator and failing when the checked-in file disagrees. All six sections are re-running the generator and failing when the checked-in file disagrees. All six sections are
there, and so is the honesty column: every Enhancement carries its `live` / `dormantSolo` / there, and so is the honesty column: every Enhancement carries its `live` / `dormantSolo` /
`unbuilt` status, and the opponent-directed cards say plainly that none of them is dealt. `unbuilt` status, and the opponent-directed cards say plainly that none of them is dealt.
@@ -2101,13 +2204,104 @@ deliberately did NOT rewrite them, on the grounds that changing a Laborer count
decision rather than a documentation one. **That reasoning still stands and nothing was changed in decision rather than a documentation one. **That reasoning still stands and nothing was changed in
the engine.** the engine.**
What changed is that `card-reference.md` is no longer where anyone looks. `docs/rules/as-built.md` What changed is that `card-reference.md` is no longer where anyone looks. The card tables (in
is generated from `content.ts` and carries the industry table the game actually runs; the old file `docs/home-deck.md` and `docs/mainline-deck.md` since 0.8.2; `docs/rules/as-built.md` before) are
generated from `content.ts` and carries the industry table the game actually runs; the old file
keeps its SUPERSEDED banner, now pointing forward, and its numbers are read as what the v0.4.5 keeps its SUPERSEDED banner, now pointing forward, and its numbers are read as what the v0.4.5
placeholder said. **The balance question the entry was really guarding is #70** (the rolling stock placeholder said. **The balance question the entry was really guarding is #70** (the rolling stock
supply and the uniform 1/1/1 industry model, both marked provisional in `content.ts`) — that is supply and the uniform 1/1/1 industry model, both marked provisional in `content.ts`) — that is
where it belongs, and it is still open. where it belongs, and it is still open.
#### #111 — A full editorial pass over the player-facing documentation.
**Raised by Jesse 2026-09-23**, on reading the rendered guide and the rewritten wrapper
instructions that shipped in 0.8.2. The verdict was that both are dramatically better and that the
workshop is still visible through them: *"There is still far too much of the feedback from
playtesting, pointing directly into code, commentary about decisions made versus gaps… People
playing the game do not need reference to old, outdated source material. They just want the
rules."* Four things to fix, and they are separable.
**1. Take the section numbers out.** Measured on 2026-09-23: `rules.md` 11, `home-deck.md` 5,
`mainline-deck.md` 5, `components.md` 4, `quickstart.md` 0. They are two different problems wearing
the same notation:
- **References to a rulebook nobody has.** §8.1, §8.2, §8.3, §10, §2.2 and the §7 cited in the deck
documents do not resolve to anything published — they are the numbering of the prototype rules
document. `rules.md:456` is the worst of them: a section whose own heading is
`## §8.1 in practice`, named after a document the reader cannot open. `rules.md:203` quotes one
outright — `§6.2: *"If any of the Department decks is empty…"*`.
- **References that do resolve, but only by number.** §3.5, §4.2–§4.6 and §6 are real sections of
`rules.md`, which numbers its own headings 1–7. These are not wrong, they are brittle and
unfriendly: `home-deck.md:207` "see Rules §4.4" asks a player to go count.
**The renderer settles how to fix these.** `scripts/markdown.ts`'s `slug()` deliberately strips a
leading section number, so §4.6 has no anchor to link to — the target is
`rules.html#passenger-work`. A cross-reference therefore becomes a named link
(`[Passenger work](rules.md#passenger-work)`) and the heading numbers themselves come off. Do
that first: it is what makes the rest of the pass mechanical.
**2. Take the pointers into the repository out.** Four of the five documents cite
`src/engine/content.ts` by path — `home-deck.md:8`, `mainline-deck.md:8`, `rules.md:8`,
`components.md:10` — to vouch that a table is generated. The guarantee is worth keeping and the
path is not; say the tables are generated from the game itself. No `.ts`, `.md` or `docs/` path
belongs in a player's document. (`docs/design.md` is a developer document and out of scope.)
**3. Publish the card counts.** *"It will change as playtesting evolves and things alter, but the
current count should be listed here. That is crucial information."*
> **This reverses a standing ruling — #15a's "Deliberately NOT including card counts per
> category", Jesse's call of 2026-08-22 — and it is the same person reversing it.** Two years of
> that ruling are baked into the files and all of it has to come out: the banner at
> `home-deck.md:12` (*"Card counts are not published…"*) and the clause at `components.md:11`
> (*"per-category CARD counts are not published, because they move with play balance"*). Update
> #15a's reference entry so it does not read as still in force.
The staleness the old ruling guarded against is answered by generation, not by omission. Every
catalogue row already carries its own count — `copiesInDeck` on track and office cards, `copies` on
industries, modifiers, enhancements, Mainline cards and Second Section — so
`scripts/build-card-reference.ts` gains a **Copies** column and `test/card-reference.test.ts` keeps
it honest for free. Nothing is typed by hand, and the count cannot drift from the deck.
**The one hard part is which deck a printed count describes.** Since 0.8.2 the office cards dealt
depend on the house rule: a game opening on Depots pulls the four Depot cards, one opening on
Whistle Posts keeps them. A single number is wrong for one of those two games. Print the default
game — every district opens on a Depot — and say so where the office table gives its counts.
`deckComposition()` and `SOLITAIRE_DECK_SIZE` are the totals to reconcile against.
**4. Strip the build-status commentary, without deleting true information.** Measured lines:
`rules.md` 5, `home-deck.md` 4, `mainline-deck.md` 3, `quickstart.md` 2, `components.md` 0. The
distinction that matters:
- **Commentary about the project — goes.** `rules.md:6` "this document reports **executable
behaviour** and marks unimplemented material"; `mainline-deck.md:104` "**It is not implemented,
and never has been.**"; the `live` / `dormantSolo` / `unbuilt` vocabulary in `home-deck.md`'s
enhancement table (251, 265, 273, 276) — that is an engineering status column printed for
players.
- **The fact underneath it — stays, in the player's language.** A player does need to know that
the opponent-directed cards are not in the deck, that the Interchange does not sort cars, and
that Facing Point Locks and the Water Column do nothing to a solitaire opponent. Say what happens
at the table ("this card is not dealt", "this card has no effect in a solitaire game"), not what
the code has got round to. A pass that deletes the sentence and the fact together makes the
documents wrong rather than clean.
**Where this leaves #15a.** Nothing here reopens it — the tables are generated and that holds. This
is the editorial half that generation was never going to do.
### The 2026-09-29 audit
#### #117 — `/api/save` and the seed
Found by the server reviewer, verified: `http.ts`'s `/api/save` returns `session.exportSave()` —
seed, config, names, full history — to any valid seat token while `status === 'active'`. The comment
above the route says "every one of those moves is already on this player's screen", which is true
of the moves and false of the seed. `game.ts` strips the seed from the shared log for exactly this
reason ("handed each of them the whole future of the deal"), `test/redaction.test.ts` pins that a
Frame never carries it, and `/api/lobby/preview` refuses to send it. Jesse's question, which is the
right one: a save without the seed is not a save. The finished-game-only answer keeps the download
button honest (it works; it just waits for the end); the receipt answer keeps a mid-game download
possible but replays nothing; the Co-op answer accepts that a co-operative table has nothing to hide.
## Done ## Done
Closed items, kept because several are the only record of a ruling or a lesson. Newest first within Closed items, kept because several are the only record of a ruling or a lesson. Newest first within
@@ -2418,7 +2612,8 @@ the numbers stay so cross-references above and below still resolve.
it describes the v0.4.5 deck, where 3/4 is a Mail-Express with three coaches against a `content.ts` it describes the v0.4.5 deck, where 3/4 is a Mail-Express with three coaches against a `content.ts`
whose train 3 is the Express with two freight cars. **The fix is not a rewritten table** — every whose train 3 is the Express with two freight cars. **The fix is not a rewritten table** — every
file in `docs/rules/` is a deliberate historical record and worth more intact than patched. A new file in `docs/rules/` is a deliberate historical record and worth more intact than patched. A new
`as-built.md` is GENERATED from the same catalogues the engine instantiates from, by `as-built.md` (folded into `docs/home-deck.md` and `docs/mainline-deck.md` in 0.8.2) is
GENERATED from the same catalogues the engine instantiates from, by
`scripts/build-card-reference.ts` (`npm run build:cards`), and `test/card-reference.test.ts` `scripts/build-card-reference.ts` (`npm run build:cards`), and `test/card-reference.test.ts`
re-runs the generator and fails if the checked-in file disagrees. **Worth knowing:** a re-runs the generator and fails if the checked-in file disagrees. **Worth knowing:** a
hand-written replacement would have drifted the same way and for the same reason — nothing fails hand-written replacement would have drifted the same way and for the same reason — nothing fails
+3 -1
View File
@@ -60,7 +60,9 @@ is what makes the whole system testable without a server.
- **Where:** Engine · **When:** loaded once at startup, immutable thereafter - **Where:** Engine · **When:** loaded once at startup, immutable thereafter
- **Does:** the 52-card deck composition, freight and passenger facility profiles, Modifier effects, - **Does:** the 52-card deck composition, freight and passenger facility profiles, Modifier effects,
train consist specs, track geometries. Source: [`../rules/card-reference.md`](../rules/card-reference.md) train consist specs, track geometries. Source: `docs/Deck cards5.xlsx` and the PDFs, transcribed
into `content.ts`; the generated tables in [`../home-deck.md`](../home-deck.md) and
[`../mainline-deck.md`](../mainline-deck.md) are what it deals today
- **MVP: S** · **Final: S** · ~200 → ~350 LOC - **MVP: S** · **Final: S** · ~200 → ~350 LOC
- **Size driver:** it is data, not logic. Grows only if card variants are added. - **Size driver:** it is data, not logic. Grows only if card variants are added.
- **Note:** every number here is provisional and will be retuned repeatedly. Keep it as data files, - **Note:** every number here is provisional and will be retuned repeatedly. Keep it as data files,
+16 -12
View File
@@ -131,24 +131,24 @@ Office; everything else is Secondary Track.
``` ```
OfficeArea OfficeArea
owner : PlayerIndex owner : PlayerIndex
officeType : whistlePost | depot | station | terminal tier : whistlePost | depot | station | terminal -- `OfficeTier`; `officeType` in early drafts
grid : Map<GridCoord, TrackCard> -- sparse; cards are placed during play grid : Map<GridCoord, TrackCard> -- sparse; cards are placed during play
officeCoord : GridCoord -- where the Office card sits officeCoord : GridCoord -- where the Office card sits
runningRow : integer -- the grid row that is the Running Track runningRow : integer -- the grid row that is the Running Track
limitsWest : GridCoord -- moves outward as the Running Track grows limitsWest : GridCoord -- moves outward as the Running Track grows
limitsEast : GridCoord limitsEast : GridCoord
adOccupancy : CrewTrayId[] -- length ≤ adTrackCount(officeType) adOccupancy : CrewTrayId[] -- length ≤ adTrackCount(tier)
``` ```
``` ```
adTrackCount: whistlePost 1 | depot 2 | station 3 | terminal 4 -- §11.1 adTrackCount: whistlePost 1 | depot 2 | station 3 | terminal 4 -- §11.1
isControlPoint = officeType != whistlePost isControlPoint = tier != whistlePost
isPassengerFacility = officeType != whistlePost isPassengerFacility = tier != whistlePost
``` ```
**Office cards are geometrically interchangeable** (§11.3). All four tiers carry the same track **Office cards are geometrically interchangeable** (§11.3). All four tiers carry the same track
footprint — a through track plus a plain junction stub above and below — and differ *only* in the footprint — a through track plus a plain junction stub above and below — and differ *only* in the
three properties above. An upgrade therefore changes `officeType` and nothing else; it must never three properties above. An upgrade therefore changes `tier` and nothing else; it must never
touch `grid`, `connections`, or anything attached to the Office card. The junction stubs carry no touch `grid`, `connections`, or anything attached to the Office card. The junction stubs carry no
directional restriction: §A.1's turnout rule governs drawn turnout cards only. directional restriction: §A.1's turnout rule governs drawn turnout cards only.
@@ -187,7 +187,7 @@ These are the ones that will be got wrong if they are not written down explicitl
9. **An Office upgrade must preserve every connection** (§11.3). All four tiers share identical 9. **An Office upgrade must preserve every connection** (§11.3). All four tiers share identical
geometry precisely so the upgrade is a property change, not a card swap. An implementation that geometry precisely so the upgrade is a property change, not a card swap. An implementation that
models the upgrade as "remove old card, place new card" will silently orphan any Secondary Track models the upgrade as "remove old card, place new card" will silently orphan any Secondary Track
hanging off the Office — mutate `officeType` in place instead. hanging off the Office — mutate `tier` in place instead.
10. **The Office card's stubs are not turnouts.** Do not route them through the §A.1 directional 10. **The Office card's stubs are not turnouts.** Do not route them through the §A.1 directional
logic; a train may pass between the Running Track and either Secondary row freely. logic; a train may pass between the Running Track and either Secondary row freely.
@@ -258,8 +258,9 @@ Facility
modifiers : ModifierRef[] -- adjacent cards raising capacity, track length or workers modifiers : ModifierRef[] -- adjacent cards raising capacity, track length or workers
``` ```
All of these are populated from [`../rules/card-reference.md`](../rules/card-reference.md), which is All of these are populated from `content.ts`, transcribed from the catalogue spreadsheets; the
the authoritative per-card catalogue. generated tables in [`../home-deck.md`](../home-deck.md) and [`../mainline-deck.md`](../mainline-deck.md)
are the per-card reference (`card-reference.md` is the superseded placeholder).
**`industryTrack` is where cars are spotted for loading and unloading**, and it is the field that **`industryTrack` is where cars are spotted for loading and unloading**, and it is the field that
stops being Operational Rail while `menAtWork` holds any load (constraint 4 below). Its `length` is stops being Operational Rail while `menAtWork` holds any load (constraint 4 below). Its `length` is
@@ -275,8 +276,9 @@ the car (§9.3). A Porter earns a point in one action. This asymmetry is deliber
per Stage, and stocking a green box or clearing a red one consumes the whole of it (§6.3). That per Stage, and stocking a green box or clearing a red one consumes the whole of it (§6.3). That
one-action-per-Stage budget is what actually limits Revenue — roughly one point per action, ceiling one-action-per-Stage budget is what actually limits Revenue — roughly one point per action, ceiling
12 per Day. Worker counts mostly determine how often a facility idles. See 12 per Day. Worker counts mostly determine how often a facility idles. See
[`../rules/card-reference.md`](../rules/card-reference.md#7-economy-summary) for the full model; it is [`../rules/card-reference.md`](../rules/card-reference.md#7-economy-summary) for the model as it was
what §3's targets are calibrated against. first worked out (that document is otherwise superseded); the figures §3's targets were calibrated
against are the measurements in `TODO.md`'s Play balance section.
--- ---
@@ -328,8 +330,10 @@ Outcome
Termination checks, in the order they must be evaluated: Termination checks, in the order they must be evaluated:
1. **Collision floor** (Competitive only) — `collisionsToday >= 3` ends the game immediately, all 1. **Collision floor** (every mode) — `collisionsToday >= maxCollisionsPerDay` or
players lose (§3.4). Checked the moment a collision resolves, not at end of Stage. `collisionsTotal >= maxCollisionsTotal` ends the game, all players lose (§3.4). Judged at the
Shift Change that closes the Stage, on the Stage just played and before the Day rolls over — so
Load/Unload still scores in the Stage of the breach, and a breach in Stage 12 counts.
2. **Target reached** (firstToTarget) — checked whenever Revenue increases. 2. **Target reached** (firstToTarget) — checked whenever Revenue increases.
3. **Days elapsed** (highestAfterDays) — at the end of the final Day, apply the collective Revenue 3. **Days elapsed** (highestAfterDays) — at the end of the final Day, apply the collective Revenue
floor `3 × players × Days` for Competitive (§3.5), or the mode target for Solitaire and Co-op floor `3 × players × Days` for Competitive (§3.5), or the mode target for Solitaire and Co-op
+3 -1
View File
@@ -107,7 +107,9 @@ clashing join is refused (`NAME_TAKEN`, compared trimmed and case-insensitively)
suffixed: a player should play under the name they chose, or be asked for another. suffixed: a player should play under the name they chose, or be asked for another.
**Anybody may leave, and the host may clear a chair.** `Lobby.Leave` frees the seat, drops the token **Anybody may leave, and the host may clear a chair.** `Lobby.Leave` frees the seat, drops the token
from `joinOrder`, and passes host rights on exactly as a dropped connection does. Naming somebody from `joinOrder`, **revokes it** — in memory and in `sessions.json`, since v0.8.4; until then the
leaver's token still opened the seat the next arrival took — and passes host rights on exactly as a
dropped connection does. Naming somebody
else's `seat` is host-only. When the last human leaves, the lobby is deleted outright — code, file and else's `seat` is host-only. When the last human leaves, the lobby is deleted outright — code, file and
index row — rather than left as a table of bots waiting for a host who no longer exists. Before this index row — rather than left as a table of bots waiting for a host who no longer exists. Before this
existed a mis-join or a player who wandered off wedged the whole table, since Start needs every chair existed a mis-join or a player who wandered off wedged the whole table, since Start needs every chair
+10 -3
View File
@@ -96,7 +96,8 @@ or a replay viewer has to reconstruct the whole board to draw one frame.
Two consequences worth knowing before adding an event: Two consequences worth knowing before adding an event:
- **`collisionOccurred` carries `faultPlayer` explicitly** rather than leaving clients to derive it. - **`trainsDestroyed` carries the player at fault (`player`) explicitly** rather than leaving clients to
derive it (the event was called `collisionOccurred` in this design; the engine emits `trainsDestroyed`).
Fault depends on *where* the wreck happened — Superintendent for a Mainline card, the local player Fault depends on *where* the wreck happened — Superintendent for a Mainline card, the local player
between their Limits (§10) — and getting it wrong misattributes a −5 and, in Competitive, feeds a between their Limits (§10) — and getting it wrong misattributes a −5 and, in Competitive, feeds a
floor that ends the game. floor that ends the game.
@@ -151,8 +152,14 @@ multiplayer work: everything else degrades gracefully, a redaction bug hands a p
- Events carry a monotonic sequence per game. Clients apply strictly in order and request a replay on - Events carry a monotonic sequence per game. Clients apply strictly in order and request a replay on
a gap rather than guessing. a gap rather than guessing.
- Intents carry a client `seq`. The server ignores a repeat of one it has already applied, so a - Intents carry a client `seq`. The server ignores a repeat of one it has already applied, so a
reconnecting client can safely resend anything it is unsure about. reconnecting client can safely resend anything it is unsure about. **The count is the server's,
for the life of the game**: the connect push carries the seat's last accepted `seq` (`lastSeq`)
and the client continues from it, never from 1 — a page that restarted its own count after a
reload re-sent a number the server had already applied, and the move was silently swallowed as
a resend (v0.8.4).
- **The server never applies two intents concurrently within a game.** A per-game queue is sufficient - **The server never applies two intents concurrently within a game.** A per-game queue is sufficient
and there is nothing cleverer to do at this scale. Note this is a serialisation rule, not a and there is nothing cleverer to do at this scale. It is a real queue (`http.ts`'s `inTurn`), not a
reliance on the single thread: the handler awaits the disk write between applying and answering,
and two moves arriving together used to interleave across that await (v0.8.4). Note this is a serialisation rule, not a
one-actor-at-a-time rule: per-player turn state (`turns: Map<PlayerIndex, TurnState>`) means several one-actor-at-a-time rule: per-player turn state (`turns: Map<PlayerIndex, TurnState>`) means several
players may hold an open turn at once, and their intents still land one at a time. players may hold an open turn at once, and their intents still land one at a time.
+1 -1
View File
@@ -1,6 +1,6 @@
# Station Master — Components and Markers # Station Master — Components and Markers
**Version 0.8.2** · 2026-09-23 **Version 0.8.6** · 2026-09-29
**Scope:** non-card physical components and supplies. Card-created facilities, workers, deck piles, **Scope:** non-card physical components and supplies. Card-created facilities, workers, deck piles,
hand state, timetable state and other markers are documented with their cards or in the hand state, timetable state and other markers are documented with their cards or in the
-3
View File
@@ -120,6 +120,3 @@ writes a self-contained HTML file — open it in any browser and step through th
Division, the Office Area grid, every facility's boxes and `MEN|AT|WORK` track, plain-English Division, the Office Area grid, every facility's boxes and `MEN|AT|WORK` track, plain-English
narration of each event, and a **Blocked** panel explaining why nothing is moving. narration of each event, and a **Blocked** panel explaining why nothing is moving.
Running alongside, and independent of all of it: **print-and-play components.** `card-reference.md`
specifies every card face, so layout and art are the only remaining work before a table playtest —
which answers the one question simulation cannot, whether it is fun.
+2 -2
View File
@@ -1,6 +1,6 @@
# Station Master — Home Deck # Station Master — Home Deck
**Version 0.8.2** · 2026-09-23 **Version 0.8.6** · 2026-09-29
**Scope:** the Home Office deck — how it is dealt, drawn, discarded and reshuffled, and what the **Scope:** the Home Office deck — how it is dealt, drawn, discarded and reshuffled, and what the
rules are for playing each kind of card out of it. rules are for playing each kind of card out of it.
@@ -381,7 +381,7 @@ an Office without wrecking.
**"Players start with Whistle Posts, not Depots"** is the harder game, set when the game is created. **"Players start with Whistle Posts, not Depots"** is the harder game, set when the game is created.
A Whistle Post has **one** A/D track and is not a Passenger Facility: no passenger earns anything A Whistle Post has **one** A/D track and is not a Passenger Facility: no passenger earns anything
until somebody draws and plays a Depot upgrade, and a second train arriving is a collision unless an until somebody draws and plays a Depot upgrade, and a second train arriving is a collision unless an
Interlocking holds it at the Limits. Interlocking holds it at the Limits until the track frees.
The deck follows the choice. Starting on Depots, the **Depot upgrade cards are left out** — an The deck follows the choice. Starting on Depots, the **Depot upgrade cards are left out** — an
upgrade must be to the next tier up, so a Depot card at a table that already has Depots is a dead upgrade must be to the next tier up, so a Depot card at a table that already has Depots is a dead
+1 -1
View File
@@ -1,6 +1,6 @@
# Station Master — Mainline Deck # Station Master — Mainline Deck
**Version 0.8.2** · 2026-09-23 **Version 0.8.6** · 2026-09-29
**Scope:** the tarot-sized Mainline cards placed between Offices — how the deck is dealt, what a **Scope:** the tarot-sized Mainline cards placed between Offices — how the deck is dealt, what a
card does to a train crossing it, and the Home Deck cards played onto one. card does to a train crossing it, and the Home Deck cards played onto one.
+113
View File
@@ -0,0 +1,113 @@
# Structure — a proposal (2026-09-29)
What the 2026-09-29 audit found about the SHAPE of the code, as distinct from its faults, and what
to do about it. Nothing here changes behaviour; each item is a seam that would let the next fault be
found by a test instead of by a reviewer reading three thousand lines. Ordered by payoff.
The faults the audit fixed in 0.8.3 and 0.8.4 were nearly all in the three largest functions or in
the one file no test stood up. That is the argument: the structure is where the bugs were.
## 1. `http.ts` — a route table, and one place for authentication
**Today.** `startServer` is one 600-line async closure of `if (pathname === … && method === …)`
chains. The token → session → lobby-or-game resolution is copy-pasted eight times; the admin-secret
check, the join-secret check and the host check are each inline where they are needed. The catch at
the bottom is the only error path, and until 0.8.4 it was itself a crash.
**Proposed.** A table of routes, each `{ method, path, auth, handler }`, with three auth wrappers:
```
withToken(handler) // resolves { ps, lobby?, game? } from the token, 404s if none
withHost(handler) // withToken, then refuses anyone but lobby.hostToken
withAdmin(handler) // the x-admin-secret gate; the whole prefix is absent when unset
```
Handlers become ten to thirty lines each and take a typed context. The one dispatcher owns
`readJson`, `sendJson`, the `HttpError` catch and the `headersSent` guard — one place, so 0.8.4's
crash fix cannot be forgotten by the next route. The per-game `inTurn` queue becomes a property of
the game context rather than something a handler has to remember to call.
**Cost.** A day. Every route is exercised by `test/server/http.test.ts` now, so the move is
mechanical and verifiable. Do it before adding the next route (the seatless display stream, #20).
## 2. `main.ts` — five extractions, and a `Selection` value
**Today.** 3200 lines, ~21 module-level `let`s (`session`, `selected`, `mode`, `pendingAt`,
`selectedCrew`, `peekPlayer`, `zoom`, `soundOn`, `gameCode`, `remoteToken`, …), and `start()` runs at
import. `render()` is ~470 lines; `renderActions` ~360. `test/web.test.ts` has to stub the DOM before
importing, can never build two pages, and cannot call `render()` with a `Frame` of its choosing —
which is why every screen fault in the audit was found by reading, not by a test.
**Proposed, in the order they pay:**
1. **`web/remote-store.ts`** — `RemoteRecord`, `readStore`/`writeStore`, `loadRemote`/`saveRemote`/
`forgetRemote`/`knownRemote`, and `lobbyHandlers`. Pure functions over `localStorage`; testable
with a Map. Today they are untestable except through the page.
2. **`web/url-options.ts`** — `RULE_PARAMS`/`VICTORY_PARAMS`/`OPTIONAL_PARAMS`, `gameOptionsFromUrl`,
`solitaireDefaults`, `rulesToUrl`. A pure round trip; the audit found the `location.search = ''`
no-op assumption (#114) by reading this code, and a test on the round trip would have found it.
3. **`web/setup-screen.ts`** — `wireGameTypeBlock`, `commitNewGame`, `runSolitaireSetup`.
4. **A `Selection` object** replacing the five `let`s (`selected`, `mode`, `pendingAt`,
`selectedCrew`, `peekPlayer`) that every click handler mutates. One value, one `reset()`, passed
to `render` rather than read from module scope — which is what lets a test call `render(frame,
selection)` and assert on the HTML.
5. **`web/game-shell.ts`** — session routing: `beginRemote`, `abandonRemote`, `claimSeat`, `start`,
`applyCapabilities`, the handoff. This is where the animation loop outliving the session (#114)
lives, and it is easier to see once it is not surrounded by rendering.
Keep `render()` in `main.ts` but split the board-and-hand wiring (~240 lines of `addEventListener`)
into `wireBoard(selection)` so what is DRAWN and what is CLICKABLE are separate functions.
**Cost.** Two to three days across the five, each its own commit; the first two are an afternoon
each and carry no risk.
## 3. The engine — `check` per phase, and one car category
**Today.** `check` (~600 lines) and `reduce` (~700) are single switches mixing every phase;
`moveTrain` nests four position kinds by three decision kinds. Car category (coach / caboose /
freight) is computed in three places with three spellings. The seat guard 0.8.3 added to the four
switching intents is the same four lines four times.
**Proposed.**
- Split `check` by phase — `checkLocalOps`, `checkNewTrain`, `checkLoadUnload`, `checkMainline` —
each a switch over its own intents, dispatched by `inPhase`. The shared guards (`ownTray`, the
option-chosen test, the Moves test) become the first lines of `checkLocalOps` rather than four
repeats. `reduce` splits the same way.
- One exported `carCategory(type)` in `content.ts`, used by `acceptsCar`, `newTrainPhase`,
`consistNeeds` and `isFreight`/`carriesLoad`.
- `maneuver.flyingSwitch` is a weaker copy of `switch.dropCars` (no `switchingRefusal`, no
`engineAt` clamp, no `standingWest` handling). It should CALL the dropCars path with a flag,
or be deleted until the card is dealt (it is at 0 copies). Deciding is #115's job; the structure
point is that there must be one cut-dropping reducer.
**Cost.** The `check`/`reduce` split is a day and is pure motion — every test in `apply.test.ts`
and `advance.test.ts` runs unchanged. `carCategory` is an hour.
## 4. One `Push` type
`web/session.ts` mirrors `server/session.ts`'s `Push` by hand so the browser bundle never imports
from `src/server/`. Every envelope change (0.8.4 added `lastSeq`) is two edits. Move the wire types
— `Push`, `LobbyPush`, `LobbyPreview` — into `src/sim/wire.ts`, which both sides already import
from, and delete the mirror.
**Cost.** An hour.
## 5. Tests that would then exist
Each extraction above names the test it makes possible:
| after | test |
| --- | --- |
| route table | one test per route for the 404/403/400 answers, from a table |
| `remote-store.ts` | the `RemoteRecord` round trip, the "seat tied to this browser" notice (#33) |
| `url-options.ts` | `rulesToUrl(gameOptionsFromUrl(x)) === x`, and the `search = ''` case |
| `Selection` | `render(frame, selection)` snapshot tests for each screen state |
| `check` per phase | the seat guard once, as a property over every switching intent |
## What not to do
- Do not refactor `render()` and fix a screen bug in the same commit. The audit's value was that
each finding could be verified against unchanged code.
- Do not introduce a framework or a runtime dependency to do any of this. The zero-dependency rule
is what makes the package a 63 MB `.s9pk` and the site a static upload.
+1 -1
View File
@@ -1,6 +1,6 @@
# Station Master — Quickstart # Station Master — Quickstart
**Version 0.8.2** · 2026-09-23 **Version 0.8.6** · 2026-09-29
For a player who has never played. For a player who has never played.
+17 -9
View File
@@ -1,6 +1,6 @@
# Station Master — Rules # Station Master — Rules
**Version 0.8.2** · 2026-09-23 **Version 0.8.6** · 2026-09-29
**Authority:** observed code paths and tests. Where a card face, a prototype document and executable **Authority:** observed code paths and tests. Where a card face, a prototype document and executable
behaviour differ, this document reports **executable behaviour** and marks unimplemented material. behaviour differ, this document reports **executable behaviour** and marks unimplemented material.
@@ -184,7 +184,7 @@ Each of 12 Stages follows this sequence:
**"Proceeding left" is seat order, west to east**, which is how the Division map draws it — the **"Proceeding left" is seat order, west to east**, which is how the Division map draws it — the
screen says "eastward" for that reason, because a table has no shared left. screen says "eastward" for that reason, because a table has no shared left.
At a Shift Change, Laborers and Porters reset. The Fedora moves after Stages 3, 6, 9, and 12. At Day end, dispatch-device use resets, collision count resets, the Day and Stage roll over, and victory is checked. At a Shift Change, Laborers and Porters reset. The Fedora moves after Stages 3, 6, 9, and 12. The collision limits are judged on the Stage just played, before anything else. At Day end, dispatch-device use resets, collision count resets, the Day and Stage roll over, and victory is checked.
### 4.2 Local Operations: choose one option ### 4.2 Local Operations: choose one option
@@ -207,7 +207,7 @@ roll a tail cut into a connected Freight Facility.
> draw actually empties the pile; a pile with cards buried under the one taken is not refilled, or > draw actually empties the pile; a pile with cards buried under the one taken is not refilled, or
> the Departments would grow without limit and drain the deck into themselves. > the Departments would grow without limit and drain the deck into themselves.
> >
**Freight Agent.** Make one of these operations, then the turn ends: stock one green outbound box from a matching loaded Division Yard car; clear one red inbound box to the Classification Yard; unjam one outbound, inbound, or MEN | AT | WORK load to the Classification Yard; or explicitly end without acting. Freight can be stocked only when an unclaimed empty matching car is already spotted at that industry. Passengers may wait in a green Office box without a train present. **Freight Agent.** Make one of these operations, then the turn ends: stock one green outbound box from a matching loaded Division Yard car; clear one red inbound box to the Classification Yard; unjam one outbound, inbound, or MEN | AT | WORK load — the one you name, when a box holds more than one — to the Classification Yard; or explicitly end without acting. Freight can be stocked only when an unclaimed empty matching car is already spotted at that industry. Passengers may wait in a green Office box without a train present.
> **A car cleared from a red Inbound box comes back empty.** Whatever was in it has arrived — the > **A car cleared from a red Inbound box comes back empty.** Whatever was in it has arrived — the
> passengers are out of the station, or the load is in the industry — and the Revenue for it was > passengers are out of the station, or the load is in the industry — and the Revenue for it was
@@ -261,9 +261,9 @@ point. On a normal card, a train must check the entire next Subdivision before e
**Uncontrolled Siding** is not a passing card: a train arriving to find it occupied takes the **Uncontrolled Siding** is not a passing card: a train arriving to find it occupied takes the
siding a region behind, which costs it the extra Stage instead of a collision. siding a region behind, which costs it the extra Stage instead of a collision.
An Office arrival normally takes a free A/D track. If the Office is full, the inbound train collides and the local Office player loses 5 Revenue; Interlocking instead holds it at the Limits. A coachless inbound train may divert to a Yard Office. Cars fouling the Running Track at the Office also cause a collision. An Office arrival normally takes a free A/D track. If the Office is full, the inbound train collides and the local Office player loses 5 Revenue; Interlocking instead holds it at the Limits. A held train takes the first A/D track that frees — whether another train's arrival or a departure freed it — ahead of anything arriving after it, and no later than the end of the Mainline phase in which the track became free. A coachless inbound train may divert to a Yard Office. Cars fouling the Running Track at the Office also cause a collision.
An expedited train remains available for this Stage’s Load/Unload work after arriving, then attempts to depart at Shift Change. A non-expedited arrival waits until a later Mainline phase. A train departing an Office must be correctly made up: engine at one end, caboose at the far end if present. An expedited train is released by the ordinary rules like any other; what Expedite restricts is where it may be left. If it is standing anywhere in the district but the Office when a Mainline phase begins, its owner is fined once for that phase. An arrival waits until a later Mainline phase. A train departing an Office must be correctly made up: engine at one end, caboose at the far end if present.
When a train leaves the far Division Point, its cars are returned to yards, its Crew Tray becomes free, and each player receives the configured train-transit Revenue (zero by default). When a train leaves the far Division Point, its cars are returned to yards, its Crew Tray becomes free, and each player receives the configured train-transit Revenue (zero by default).
@@ -372,6 +372,11 @@ stay where they are.
So multiplayer changes shared traffic, scores, turn order and how the game is won or lost — not card So multiplayer changes shared traffic, scores, turn order and how the game is won or lost — not card
attacks, which do not exist in any mode. attacks, which do not exist in any mode.
**Saving a multiplayer game.** The server holds the save; **Save replay** downloads your copy. A save
carries the seed, and the seed is the whole deal — every hand and the order of the deck — so in a
**Competitive** game the download is available once the game is over. In **Co-op** it is available
at any time.
## 7. Frequently asked questions ## 7. Frequently asked questions
### Is the same seed always the same game? ### Is the same seed always the same game?
@@ -406,10 +411,12 @@ The Office had no free A/D track and no Interlocking. A full Office is an automa
It may be on Secondary Track rather than the Office, or be badly made up: its engine is between cars or its caboose is not at the far end. It may be on Secondary Track rather than the Office, or be badly made up: its engine is between cars or its caboose is not at the far end.
### Why did an expedited train leave after passenger/freight work? ### Why was I fined for an expedited train?
Expedite means it departs in the Stage it arrived, but the departure waits until Shift Change so the Expedite does not change when a train leaves — it leaves when the Mainline rules release it, like any
train is still present for that Stage's Load/Unload phase. other. It changes where the train may be left: if a Mainline phase begins with it standing on any
track in the district but the Office, the owner is fined. The fine is charged once per Mainline
phase, however many clearance questions that phase asks.
### Can I choose the direction of an Extra or a Heavy Grade? ### Can I choose the direction of an Extra or a Heavy Grade?
@@ -470,4 +477,5 @@ lies inside one, so a table of Whistle Posts is a single Subdivision from end to
**An Office never holds more trains than it has A/D tracks.** A train the Interlocking is holding at **An Office never holds more trains than it has A/D tracks.** A train the Interlocking is holding at
the Limits takes the first track to free, ahead of anything arriving afterwards — and the train that the Limits takes the first track to free, ahead of anything arriving afterwards — and the train that
arrives to find it taken is held at its own Limits, or collides if there is no Interlocking. arrives to find it taken is held at its own Limits, or collides if there is no Interlocking. A track
freed by a departure counts too: the held train takes it at the end of that Mainline phase.
+4 -3
View File
@@ -4,9 +4,10 @@
> 2026-07-30 in `docs/Deck cards2.xlsx`, `Trains3.pdf` and `Mainline Cards.pdf`, and is transcribed > 2026-07-30 in `docs/Deck cards2.xlsx`, `Trains3.pdf` and `Mainline Cards.pdf`, and is transcribed
> in `src/engine/content.ts`. See [`implications.md`](implications.md) for the full comparison. > in `src/engine/content.ts`. See [`implications.md`](implications.md) for the full comparison.
> >
> **For what the cards say today, read [`as-built.md`](as-built.md)** — generated from > **For what the cards say today, read the generated tables in [`home-deck.md`](../home-deck.md)
> `content.ts` and checked against it by the test suite, so it cannot fall behind the way this file > and [`mainline-deck.md`](../mainline-deck.md)** — written by `npm run build:cards` from
> did. For several releases `content.ts` named *this* page as the current reference while the banner > `content.ts` and checked against it by the test suite, so they cannot fall behind the way this
> file did. For several releases `content.ts` named *this* page as the current reference while the banner
> here said otherwise, and a reader following the code landed on the v0.4.5 deck. > here said otherwise, and a reader following the code landed on the v0.4.5 deck.
> >
> Kept for the reasoning it records — the economy analysis in §7 was how we knew what questions to > Kept for the reasoning it records — the economy analysis in §7 was how we knew what questions to
-301
View File
@@ -1,301 +0,0 @@
{
"seed": 116956197,
"history": [
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "card.play",
"cardId": "c27"
},
{
"type": "card.play",
"cardId": "c30"
},
{
"type": "card.play",
"cardId": "c4"
},
{
"type": "card.play",
"cardId": "c2"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 2
},
{
"type": "card.play",
"cardId": "c197",
"placement": {
"row": 0,
"col": -1
},
"variant": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 2
},
{
"type": "card.play",
"cardId": "c163",
"placement": {
"row": 1,
"col": -1
},
"variant": 0
},
{
"type": "card.play",
"cardId": "c41",
"placement": {
"row": 1,
"col": 0
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "card.play",
"cardId": "c127",
"placement": {
"row": 0,
"col": 1
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.play",
"cardId": "c183",
"placement": {
"row": 0,
"col": 2
},
"variant": 1
},
{
"type": "card.play",
"cardId": "c150",
"placement": {
"row": 1,
"col": 2
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 1
},
{
"type": "card.play",
"cardId": "c136",
"placement": {
"row": 1,
"col": 1
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c77",
"toSlot": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c171",
"toSlot": 0
},
{
"type": "draw.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "boxcar",
"loaded": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "boxcar",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c153",
"toSlot": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.play",
"cardId": "c9"
},
{
"type": "draw.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
}
],
"rules": {
"startingHand": "sixRandom",
"revenue": {
"passengerPerCoach": 1,
"freightPerLoad": 1,
"trainPerTransit": 0
}
}
}
@@ -1,714 +0,0 @@
{
"seed": 116956197,
"history": [
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "card.play",
"cardId": "c27"
},
{
"type": "card.play",
"cardId": "c30"
},
{
"type": "card.play",
"cardId": "c4"
},
{
"type": "card.play",
"cardId": "c2"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 2
},
{
"type": "card.play",
"cardId": "c197",
"placement": {
"row": 0,
"col": -1
},
"variant": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 2
},
{
"type": "card.play",
"cardId": "c163",
"placement": {
"row": 1,
"col": -1
},
"variant": 0
},
{
"type": "card.play",
"cardId": "c41",
"placement": {
"row": 1,
"col": 0
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "card.play",
"cardId": "c127",
"placement": {
"row": 0,
"col": 1
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.play",
"cardId": "c183",
"placement": {
"row": 0,
"col": 2
},
"variant": 1
},
{
"type": "card.play",
"cardId": "c150",
"placement": {
"row": 1,
"col": 2
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 1
},
{
"type": "card.play",
"cardId": "c136",
"placement": {
"row": 1,
"col": 1
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c77",
"toSlot": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c171",
"toSlot": 0
},
{
"type": "draw.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "boxcar",
"loaded": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "boxcar",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c153",
"toSlot": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.play",
"cardId": "c9"
},
{
"type": "draw.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": -2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": 0
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 1
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": -2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 0
},
"reverse": true
},
{
"type": "switch.end"
},
{
"type": "laborer.beginUnload",
"at": {
"row": 1,
"col": 0
},
"carIndex": 0
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c162",
"toSlot": 2
},
{
"type": "draw.end"
},
{
"type": "porter.detrain",
"at": {
"row": 0,
"col": 0
}
},
{
"type": "porter.detrain",
"at": {
"row": 0,
"col": 0
}
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 2
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.clearInbound",
"at": {
"row": 0,
"col": 0
},
"index": 0
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 1
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.clearInbound",
"at": {
"row": 0,
"col": 0
},
"index": 0
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 0
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 1,
"col": 0
},
"carType": "boxcar"
},
{
"type": "laborer.startLoad",
"at": {
"row": 1,
"col": 0
}
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 0,
"col": 0
},
"carType": "coach"
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "boxcar",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "boxcar",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "boxcar",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "caboose",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.clearInbound",
"at": {
"row": 1,
"col": 0
},
"index": 0
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 0
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 0,
"col": 0
},
"carType": "coach"
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 1
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.discard",
"cardId": "c50",
"toSlot": 0
},
{
"type": "draw.end"
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 2
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": -2
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray2",
"count": 1
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": 3
},
"reverse": false,
"via": {
"row": 0,
"col": 0
}
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 1,
"col": 0
},
"reverse": true
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": 3
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": 1
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray2",
"count": 1
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": 3
},
"reverse": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "tank",
"loaded": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "tank",
"loaded": false
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 1,
"col": 0
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray2",
"count": 3
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": 3
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": -2
},
"reverse": true,
"via": {
"row": 0,
"col": 1
}
},
{
"type": "switch.move",
"trayId": "tray2",
"to": {
"row": 0,
"col": 0
},
"reverse": false
},
{
"type": "switch.end"
}
],
"rules": {
"startingHand": "sixRandom",
"revenue": {
"passengerPerCoach": 1,
"freightPerLoad": 1,
"trainPerTransit": 0
}
}
}
File diff suppressed because it is too large Load Diff
-656
View File
@@ -1,656 +0,0 @@
{
"seed": 493290760,
"history": [
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.play",
"cardId": "c138",
"placement": {
"row": 0,
"col": -1
},
"variant": 0
},
{
"type": "card.play",
"cardId": "c144",
"placement": {
"row": 0,
"col": 1
},
"variant": 0
},
{
"type": "card.play",
"cardId": "c11"
},
{
"type": "card.play",
"cardId": "c24"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 1
},
{
"type": "card.play",
"cardId": "c31"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 0,
"col": 0
},
"carType": "coach"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 0,
"col": 0
},
"carType": "coach"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 1
},
{
"type": "card.play",
"cardId": "c182",
"placement": {
"row": 0,
"col": 1
},
"variant": 1
},
{
"type": "card.play",
"cardId": "c159",
"placement": {
"row": 1,
"col": 1
},
"variant": 0
},
{
"type": "card.play",
"cardId": "c49",
"placement": {
"row": 1,
"col": 0
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "card.play",
"cardId": "c5"
},
{
"type": "draw.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "tank",
"loaded": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "tank",
"loaded": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "caboose",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": false
},
{
"type": "mainline.clearance",
"allow": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": 0
},
"reverse": true
},
{
"type": "switch.end"
},
{
"type": "porter.detrain",
"at": {
"row": 0,
"col": 0
}
},
{
"type": "porter.board",
"at": {
"row": 0,
"col": 0
}
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": -1
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 1
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": 0
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 1
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": -1
},
"reverse": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 0
},
"reverse": false
},
{
"type": "switch.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 1,
"col": 0
},
"carType": "tank"
},
{
"type": "laborer.startLoad",
"at": {
"row": 1,
"col": 0
}
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 0
},
{
"type": "card.play",
"cardId": "c194",
"placement": {
"row": 0,
"col": -2
},
"variant": 1
},
{
"type": "draw.end"
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 0
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.stockOutbound",
"at": {
"row": 0,
"col": 0
},
"carType": "coach"
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 1
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.end"
},
{
"type": "laborer.advanceLoad",
"at": {
"row": 1,
"col": 0
},
"box": 2
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromDepartment",
"slot": 1
},
{
"type": "card.play",
"cardId": "c154",
"placement": {
"row": 1,
"col": -2
},
"variant": 0
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "card.play",
"cardId": "c102",
"node": 1
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "boxcar",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "tank",
"loaded": false
},
{
"type": "newTrain.placeCar",
"trayId": "tray3",
"carType": "caboose",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "draw"
},
{
"type": "draw.fromHomeOffice"
},
{
"type": "draw.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "freightAgent"
},
{
"type": "freightAgent.end"
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "newTrain.placeCar",
"trayId": "tray2",
"carType": "coach",
"loaded": true
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": -2
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 1
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 2
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": 0
},
"reverse": true
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": 2
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": -2
},
"reverse": true
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 3
},
{
"type": "switch.dropCars",
"trayId": "tray3",
"count": 1
},
{
"type": "switch.end"
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.end"
},
{
"type": "porter.detrain",
"at": {
"row": 0,
"col": 0
}
},
{
"type": "porter.board",
"at": {
"row": 0,
"col": 0
}
},
{
"type": "loadUnload.end"
},
{
"type": "localOps.choose",
"option": "switch"
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 0,
"col": -1
},
"reverse": false
},
{
"type": "switch.move",
"trayId": "tray3",
"to": {
"row": 1,
"col": -2
},
"reverse": true
}
]
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "station-master", "name": "station-master",
"version": "0.8.2", "version": "0.8.6",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Station Master — a railroad operations game", "description": "Station Master — a railroad operations game",
+43 -18
View File
@@ -109,6 +109,39 @@ export type Rendered = { html: string; headings: Heading[] };
* `linkHref` rewrites link targets — the build uses it to send `rules.md` to `rules.html` — and * `linkHref` rewrites link targets — the build uses it to send `rules.md` to `rules.html` — and
* defaults to leaving them alone so the function is testable on its own. * defaults to leaving them alone so the function is testable on its own.
*/ */
/**
* One list at one indent level. An item is its first line plus any lines indented under it; the
* more-indented BULLETS among those are the item's own nested list and render recursively, while
* plain indented lines are wrapped continuations of its text.
*/
function listHtml(block: string[], text: (s: string) => string): string {
const first = /^(\s*)([-*+]|\d+[.)])\s+/.exec(block.find((l) => l.trim() !== '') ?? '');
if (!first) return '';
const ordered = /\d/.test(first[2]!);
const base = first[1]!.length;
const items: { text: string[]; sub: string[] }[] = [];
for (const l of block) {
const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(l);
const current = items[items.length - 1];
if (m && m[1]!.length <= base) {
items.push({ text: [m[3]!], sub: [] });
} else if (!current) {
continue;
} else if (current.sub.length > 0 || (m && m[1]!.length > base)) {
// Once a nested list has begun, everything further belongs to it, wrapped lines included.
current.sub.push(l);
} else if (l.trim() !== '') {
current.text.push(l.trim());
}
}
const tag = ordered ? 'ol' : 'ul';
return (
`<${tag}>` +
items.map((it) => `<li>${text(it.text.join(' '))}${it.sub.length > 0 ? listHtml(it.sub, text) : ''}</li>`).join('') +
`</${tag}>`
);
}
export function renderMarkdown(src: string, linkHref: (href: string) => string = (h) => h): Rendered { export function renderMarkdown(src: string, linkHref: (href: string) => string = (h) => h): Rendered {
const lines = src.replace(/\r\n/g, '\n').split('\n'); const lines = src.replace(/\r\n/g, '\n').split('\n');
const out: string[] = []; const out: string[] = [];
@@ -196,13 +229,14 @@ export function renderMarkdown(src: string, linkHref: (href: string) => string =
continue; continue;
} }
// Lists. A bullet or a number opens one; continuation lines are indented under their item. // Lists. A bullet or a number opens one; continuation lines are indented under their item, and
// a more-indented bullet under an item is a nested list, rendered by recursion (v0.8.4 — the
// comment said so before and the code appended the nested bullet to its parent as text, so the
// published home-deck page carried a literal "- " mid-sentence).
const bullet = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line); const bullet = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
if (bullet) { if (bullet) {
const ordered = /\d/.test(bullet[2]!);
const baseIndent = bullet[1]!.length; const baseIndent = bullet[1]!.length;
const items: string[] = []; const block: string[] = [];
let current: string[] | null = null;
while (i < lines.length) { while (i < lines.length) {
const l = lines[i]!; const l = lines[i]!;
if (l.trim() === '') { if (l.trim() === '') {
@@ -210,28 +244,19 @@ export function renderMarkdown(src: string, linkHref: (href: string) => string =
const next = lines[i + 1] ?? ''; const next = lines[i + 1] ?? '';
const continues = /^(\s*)([-*+]|\d+[.)])\s+/.test(next) || /^\s{2,}\S/.test(next); const continues = /^(\s*)([-*+]|\d+[.)])\s+/.test(next) || /^\s{2,}\S/.test(next);
if (!continues) break; if (!continues) break;
block.push('');
i++; i++;
continue; continue;
} }
const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(l); const m = /^(\s*)([-*+]|\d+[.)])\s+/.exec(l);
if (m && m[1]!.length <= baseIndent) { if ((m && m[1]!.length <= baseIndent) || (m && m[1]!.length > baseIndent) || /^\s{2,}\S/.test(l)) {
if (current) items.push(current.join(' ')); block.push(l);
current = [m[3]!];
i++;
continue;
}
if (m || /^\s{2,}\S/.test(l)) {
// A nested item or a wrapped continuation. Nesting is rendered by recursion on the block.
if (!current) break;
current.push(l.trim());
i++; i++;
continue; continue;
} }
break; break;
} }
if (current) items.push(current.join(' ')); ln(listHtml(block, text));
const tag = ordered ? 'ol' : 'ul';
ln(`<${tag}>${items.map((it) => `<li>${text(it)}</li>`).join('')}</${tag}>`);
continue; continue;
} }
+66 -26
View File
@@ -469,7 +469,13 @@ function mainlinePhase(s: GameState, events: GameEvent[]): AdvanceResult {
* there, not a one-time slip. A train the ordinary §8.1 rules are holding at the Office itself is * there, not a one-time slip. A train the ordinary §8.1 rules are holding at the Office itself is
* unaffected — this only bites when the train is not even in the queue to leave. * unaffected — this only bites when the train is not even in the queue to leave.
*/ */
for (const [, tray] of order) { /**
* ONCE PER PHASE, NOT ONCE PER QUESTION (v0.8.3). This function is re-entered from the top after
* every clearance, Yard Office and Red Flag ruling, and the loop below ran unguarded — so a train
* left on a siding was fined once per interruption. A pending answer is the mark of a resumption:
* it is set by the ruling and consumed further down, inside the move it belongs to.
*/
for (const [, tray] of s.clock.decisionAnswer === null ? order : []) {
if (!isExpedited(tray) || tray.position.at !== 'grid') continue; if (!isExpedited(tray) || tray.position.at !== 'grid') continue;
const area = areaAtSeat(s, tray.position.seat); const area = areaAtSeat(s, tray.position.seat);
const { coord } = tray.position; const { coord } = tray.position;
@@ -555,10 +561,41 @@ function mainlinePhase(s: GameState, events: GameEvent[]): AdvanceResult {
s.movedThisPhase.add(id); s.movedThisPhase.add(id);
} }
releaseHeldAtLimits(s, events);
s.movedThisPhase = new Set(); s.movedThisPhase = new Set();
return { events: [...events, ...enterPhase(s, 'loadUnload')], needsInput: false }; return { events: [...events, ...enterPhase(s, 'loadUnload')], needsInput: false };
} }
/**
* A TRAIN HELD AT THE LIMITS TAKES A TRACK THAT FREES — whoever freed it (v0.8.3).
*
* `arriveAtOffice` promises "held at the Limits until an A/D track frees up", and until now the
* only release was inside `arriveAtOffice` itself, for a DIFFERENT train arriving. An Office that
* emptied by departures alone kept its held train at the Limits for the rest of the game — with no
* transit, no place in `adOccupancy` and no part in the clearance check, so nothing on the board or
* in the rules could see it. Every train has now attempted its move for this Phase, so any track
* still free is genuinely free, and the held trains take them in the order they were held.
*/
function releaseHeldAtLimits(s: GameState, events: GameEvent[]): void {
for (const area of s.officeAreas.values()) {
const capacity = officeProfile(area.tier).adTracks;
while (area.heldAtLimits.length > 0 && area.adOccupancy.length < capacity) {
const id = area.heldAtLimits.shift()!;
const held = s.trays.get(id);
if (!held) continue;
area.adOccupancy.push(id);
held.position = { at: 'grid', seat: area.seat, coord: area.officeCoord };
events.push({
type: 'trainReleasedFromLimits',
trainNumber: held.trainNumber ?? 0,
office: officeProfile(area.tier).name,
owner: playerAtSeat(s, area.seat),
freedBy: null,
});
}
}
}
type MoveOutcome = 'moved' | 'held' | 'needsClearance'; type MoveOutcome = 'moved' | 'held' | 'needsClearance';
/** /**
@@ -693,7 +730,6 @@ function entryConflict(
/** Puts a train onto a Mainline card with its crossing time already computed. */ /** Puts a train onto a Mainline card with its crossing time already computed. */
function enterMainline( function enterMainline(
s: GameState,
node: Extract<DivisionNode, { kind: 'mainline' }>, node: Extract<DivisionNode, { kind: 'mainline' }>,
id: TrayId, id: TrayId,
tray: CrewTray, tray: CrewTray,
@@ -825,7 +861,7 @@ function moveTrain(s: GameState, id: TrayId, tray: CrewTray, events: GameEvent[]
if (conflict === 'held') return 'held'; if (conflict === 'held') return 'held';
if (conflict === 'collided') return 'moved'; if (conflict === 'collided') return 'moved';
enterMainline(s, node, id, tray, target); enterMainline(node, id, tray, target);
const dp = s.division.nodes[dpIndex]; const dp = s.division.nodes[dpIndex];
if (dp?.kind === 'divisionPoint') dp.holding = dp.holding.filter((t) => t !== id); if (dp?.kind === 'divisionPoint') dp.holding = dp.holding.filter((t) => t !== id);
events.push({ events.push({
@@ -889,7 +925,7 @@ function moveTrain(s: GameState, id: TrayId, tray: CrewTray, events: GameEvent[]
// The wreck's A/D track is released by `collide` itself, which is why it has to be. // The wreck's A/D track is released by `collide` itself, which is why it has to be.
if (conflict === 'collided') return 'moved'; if (conflict === 'collided') return 'moved';
enterMainline(s, node, id, tray, target); enterMainline(node, id, tray, target);
area.adOccupancy = area.adOccupancy.filter((t) => t !== id); area.adOccupancy = area.adOccupancy.filter((t) => t !== id);
events.push({ events.push({
type: 'trainHighballed', type: 'trainHighballed',
@@ -961,7 +997,7 @@ function moveTrain(s: GameState, id: TrayId, tray: CrewTray, events: GameEvent[]
if (conflict === 'collided') return 'moved'; if (conflict === 'collided') return 'moved';
node.holding = node.holding.filter((t) => t !== id); node.holding = node.holding.filter((t) => t !== id);
enterMainline(s, node, id, tray, index, true); enterMainline(node, id, tray, index, true);
events.push({ events.push({
type: 'trainHighballed', type: 'trainHighballed',
trainNumber: tray.trainNumber ?? 0, trainNumber: tray.trainNumber ?? 0,
@@ -1363,7 +1399,7 @@ function redFlagStop(
return c?.kind.kind === 'maneuver' && c.kind.key === 'redFlags'; return c?.kind.kind === 'maneuver' && c.kind.key === 'redFlags';
}); });
if (!holdsFlag) return 'proceed'; if (!holdsFlag) return 'proceed';
if (!arrivalWouldCollide(s, id, tray, dest.seat)) return 'proceed'; if (!arrivalWouldCollide(s, dest.seat)) return 'proceed';
s.clock.pendingDecision = { kind: 'redFlag', train: id, seat: dest.seat, from }; s.clock.pendingDecision = { kind: 'redFlag', train: id, seat: dest.seat, from };
return 'ask'; return 'ask';
@@ -1376,7 +1412,7 @@ function redFlagStop(
* if these two ever diverge, the prompt offers a flag against a collision that will not happen, or * if these two ever diverge, the prompt offers a flag against a collision that will not happen, or
* stays silent before one that will. * stays silent before one that will.
*/ */
function arrivalWouldCollide(s: GameState, id: TrayId, tray: CrewTray, seat: SeatIndex): boolean { function arrivalWouldCollide(s: GameState, seat: SeatIndex): boolean {
const area = areaAtSeat(s, seat); const area = areaAtSeat(s, seat);
const hasInterlocking = [...area.grid.values()].some((c) => c.enhancements.includes('interlocking')); const hasInterlocking = [...area.grid.values()].some((c) => c.enhancements.includes('interlocking'));
const full = area.adOccupancy.length >= officeProfile(area.tier).adTracks; const full = area.adOccupancy.length >= officeProfile(area.tier).adTracks;
@@ -1803,31 +1839,16 @@ function shiftChange(s: GameState, events: GameEvent[]): AdvanceResult {
} }
} }
if (s.clock.stage >= STAGES_PER_DAY) {
// Telegraph/Telephone/Radio are each usable once a Day.
for (const area of s.officeAreas.values()) area.dispatchUsedToday = [];
s.clock.day += 1;
s.clock.stage = 1;
// Captured BEFORE the reset: the Day-end dialog reports the Day that just finished, and it is
// drawn from the frame this rollover produces. See `collisionsPrevDay` in `state.ts`.
s.collisionsPrevDay = s.collisionsToday;
s.collisionsToday = 0;
events.push({ type: 'stageBegan', day: s.clock.day, stage: 1 });
rotateSeats(s, events);
const finished = checkVictory(s, events);
if (finished) return { events, needsInput: false };
} else {
s.clock.stage += 1;
events.push({ type: 'stageBegan', day: s.clock.day, stage: s.clock.stage });
}
/** /**
* §3.4 — EVERY MODE, SOLITAIRE INCLUDED: a Day's collisions against `maxCollisionsPerDay` and the * §3.4 — EVERY MODE, SOLITAIRE INCLUDED: a Day's collisions against `maxCollisionsPerDay` and the
* game's running total against `maxCollisionsTotal`. `0` disables either check. Flat, not scaled * game's running total against `maxCollisionsTotal`. `0` disables either check. Flat, not scaled
* by player count — Jesse's call, 2026-08-20: more players is more independent chances to collide, * by player count — Jesse's call, 2026-08-20: more players is more independent chances to collide,
* not a bigger shared budget. * not a bigger shared budget.
* *
* JUDGED BEFORE THE DAY ROLLS OVER (v0.8.3). This block sat below the rollover, which resets
* `collisionsToday` — so a breach reached in Stage 12 was read as zero and the last Stage of every
* Day was the one Stage the floor could not fire in. Pinned in `advance.test.ts`.
*
* SOLITAIRE WAS EXCLUDED UNTIL 2026-08-30 and nothing said so. The gate here read `mode === * SOLITAIRE WAS EXCLUDED UNTIL 2026-08-30 and nothing said so. The gate here read `mode ===
* 'competitive' || mode === 'coop'`, while `SOLO_CONFIG` carried both limits and the New Game * 'competitive' || mode === 'coop'`, while `SOLO_CONFIG` carried both limits and the New Game
* dialog offered them as live settings — so a solitaire player could set a collision limit, read * dialog offered them as live settings — so a solitaire player could set a collision limit, read
@@ -1860,6 +1881,25 @@ function shiftChange(s: GameState, events: GameEvent[]): AdvanceResult {
} }
} }
if (s.clock.stage >= STAGES_PER_DAY) {
// Telegraph/Telephone/Radio are each usable once a Day.
for (const area of s.officeAreas.values()) area.dispatchUsedToday = [];
s.clock.day += 1;
s.clock.stage = 1;
// Captured BEFORE the reset: the Day-end dialog reports the Day that just finished, and it is
// drawn from the frame this rollover produces. See `collisionsPrevDay` in `state.ts`.
s.collisionsPrevDay = s.collisionsToday;
s.collisionsToday = 0;
events.push({ type: 'stageBegan', day: s.clock.day, stage: 1 });
rotateSeats(s, events);
const finished = checkVictory(s, events);
if (finished) return { events, needsInput: false };
} else {
s.clock.stage += 1;
events.push({ type: 'stageBegan', day: s.clock.day, stage: s.clock.stage });
}
return { events: [...events, ...enterPhase(s, 'localOps')], needsInput: false }; return { events: [...events, ...enterPhase(s, 'localOps')], needsInput: false };
} }
+76 -23
View File
@@ -16,7 +16,6 @@
import { import {
FREIGHT_PROFILES, FREIGHT_PROFILES,
LABORER_ACTIONS_PER_LOAD,
MAX_CONSIST, MAX_CONSIST,
REALIGNMENTS, REALIGNMENTS,
consistSize, consistSize,
@@ -65,7 +64,6 @@ import {
pooled, pooled,
railFacingOf, railFacingOf,
seatOf, seatOf,
spaceOn,
standingSides, standingSides,
trackOrder, trackOrder,
turnOf, turnOf,
@@ -125,6 +123,22 @@ function trayCoord(s: GameState, trayId: TrayId): GridCoord | null {
return tray.position.coord; return tray.position.coord;
} }
/**
* A TRAY THE PLAYER MAY SWITCH: one standing in THEIR OWN district. Null for a tray that does not
* exist, is off the grid, or is standing in somebody else's Office Area.
*
* Until v0.8.3 the switching intents resolved a tray with no seat test at all. `legal.ts`'s
* generator filtered by seat, `check` did not — and the server validates with `check` alone. Every
* district opens on the same coordinates, so a destination legal for your own tray at (0,0) was
* "legal" for a rival's tray at THEIR (0,0), and `trayMoved` then charged the Moves to the rival's
* turn. Invisible in solitaire, where there is nobody else's district to reach into.
*/
function ownTray(s: GameState, player: PlayerIndex, trayId: TrayId): CrewTray | null {
const tray = s.trays.get(trayId);
if (!tray || tray.position.at !== 'grid' || tray.position.seat !== seatOf(s, player)) return null;
return tray;
}
/** A tray sitting on the Office card occupies an A/D track (§2.1). */ /** A tray sitting on the Office card occupies an A/D track (§2.1). */
/** /**
* Exported for `advance.ts`'s Yard Office walk (Gitea#5), which has to ask the SAME occupancy * Exported for `advance.ts`'s Yard Office walk (Gitea#5), which has to ask the SAME occupancy
@@ -133,10 +147,19 @@ function trayCoord(s: GameState, trayId: TrayId): GridCoord | null {
*/ */
export function occupancyFor(s: GameState, player: PlayerIndex, self: TrayId): Occupancy { export function occupancyFor(s: GameState, player: PlayerIndex, self: TrayId): Occupancy {
const area = areaOf(s, player); const area = areaOf(s, player);
const seat = seatOf(s, player);
return { return {
// IN THIS DISTRICT. Every Office Area is laid out on the same coordinates, so a coordinate match
// alone found a rival's crew standing "here" — a phantom that blocked Moves and the Yard Office
// walk in any game with more than one seat (v0.8.3).
trayAt: (c) => { trayAt: (c) => {
for (const [id, tray] of s.trays) { for (const [id, tray] of s.trays) {
if (tray.position.at === 'grid' && tray.position.coord.row === c.row && tray.position.coord.col === c.col) { if (
tray.position.at === 'grid' &&
tray.position.seat === seat &&
tray.position.coord.row === c.row &&
tray.position.coord.col === c.col
) {
return id; return id;
} }
} }
@@ -622,7 +645,7 @@ function passengerWork(
* crew is unaffected by all of them. * crew is unaffected by all of them.
*/ */
/** Which district a tray is standing in; 0 when it is out on the Division. */ /** Which district a tray is standing in; 0 when it is out on the Division. */
function trayySeat(tray: CrewTray): SeatIndex { function traySeat(tray: CrewTray): SeatIndex {
return tray.position.at === 'grid' ? tray.position.seat : 0; return tray.position.at === 'grid' ? tray.position.seat : 0;
} }
@@ -895,7 +918,7 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (!inPhase(s, 'localOps')) return 'WRONG_PHASE'; if (!inPhase(s, 'localOps')) return 'WRONG_PHASE';
if (turnOf(s, player).option !== 'switch') return 'OPTION_NOT_CHOSEN'; if (turnOf(s, player).option !== 'switch') return 'OPTION_NOT_CHOSEN';
if (turnOf(s, player).movesRemaining < 1) return 'NO_MOVES_REMAINING'; if (turnOf(s, player).movesRemaining < 1) return 'NO_MOVES_REMAINING';
const tray = s.trays.get(i.trayId); const tray = ownTray(s, player, i.trayId);
if (!tray) return 'NO_SUCH_TRAY'; if (!tray) return 'NO_SUCH_TRAY';
const from = trayCoord(s, i.trayId); const from = trayCoord(s, i.trayId);
if (!from) return 'ILLEGAL_MOVE'; if (!from) return 'ILLEGAL_MOVE';
@@ -954,7 +977,7 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
case 'switch.dropCars': { case 'switch.dropCars': {
if (!inPhase(s, 'localOps')) return 'WRONG_PHASE'; if (!inPhase(s, 'localOps')) return 'WRONG_PHASE';
if (turnOf(s, player).option !== 'switch') return 'OPTION_NOT_CHOSEN'; if (turnOf(s, player).option !== 'switch') return 'OPTION_NOT_CHOSEN';
const tray = s.trays.get(i.trayId); const tray = ownTray(s, player, i.trayId);
if (!tray) return 'NO_SUCH_TRAY'; if (!tray) return 'NO_SUCH_TRAY';
const noSwitch = switchingRefusal(tray); const noSwitch = switchingRefusal(tray);
if (noSwitch) return noSwitch; if (noSwitch) return noSwitch;
@@ -1003,7 +1026,7 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
if (!inPhase(s, 'localOps')) return 'WRONG_PHASE'; if (!inPhase(s, 'localOps')) return 'WRONG_PHASE';
if (turnOf(s, player).option !== 'switch') return 'OPTION_NOT_CHOSEN'; if (turnOf(s, player).option !== 'switch') return 'OPTION_NOT_CHOSEN';
if (turnOf(s, player).movesRemaining < 1) return 'NO_MOVES_REMAINING'; if (turnOf(s, player).movesRemaining < 1) return 'NO_MOVES_REMAINING';
const tray = s.trays.get(i.trayId); const tray = ownTray(s, player, i.trayId);
if (!tray) return 'NO_SUCH_TRAY'; if (!tray) return 'NO_SUCH_TRAY';
const noSwitch = switchingRefusal(tray); const noSwitch = switchingRefusal(tray);
if (noSwitch) return noSwitch; if (noSwitch) return noSwitch;
@@ -1125,7 +1148,7 @@ export function check(s: GameState, player: PlayerIndex, i: Intent): RejectionCo
const card = s.cards.get(i.cardId); const card = s.cards.get(i.cardId);
if (!card || !(s.decks.hands.get(player) ?? []).includes(i.cardId)) return 'NO_SUCH_CARD'; if (!card || !(s.decks.hands.get(player) ?? []).includes(i.cardId)) return 'NO_SUCH_CARD';
if (card.kind.kind !== 'maneuver' || card.kind.key !== 'flyingSwitch') return 'WRONG_INTENT'; if (card.kind.kind !== 'maneuver' || card.kind.key !== 'flyingSwitch') return 'WRONG_INTENT';
const tray = s.trays.get(i.trayId); const tray = ownTray(s, player, i.trayId);
if (!tray) return 'NO_SUCH_TRAY'; if (!tray) return 'NO_SUCH_TRAY';
const here = trayCoord(s, i.trayId); const here = trayCoord(s, i.trayId);
if (!here) return 'CANNOT_DROP_HERE'; if (!here) return 'CANNOT_DROP_HERE';
@@ -1553,7 +1576,7 @@ function checkPlay(
return target && target.kind === 'mainline' ? null : 'NOT_CONNECTED'; return target && target.kind === 'mainline' ? null : 'NOT_CONNECTED';
} }
if (!placement) return 'NO_PLACEMENT'; if (!placement) return 'NO_PLACEMENT';
return checkEnhancementPlacement(s, area, card.kind.key, placement); return checkEnhancementPlacement(area, card.kind.key, placement);
} }
case 'mainlineModifier': case 'mainlineModifier':
@@ -1562,7 +1585,7 @@ function checkPlay(
// copy uses the enhancement's grid placement rather than going onto a Mainline card. // copy uses the enhancement's grid placement rather than going onto a Mainline card.
if (card.kind.key === 'facingPointLocksMainline') { if (card.kind.key === 'facingPointLocksMainline') {
if (!placement) return 'NO_PLACEMENT'; if (!placement) return 'NO_PLACEMENT';
return checkEnhancementPlacement(s, area, 'facingPointLocks', placement); return checkEnhancementPlacement(area, 'facingPointLocks', placement);
} }
// The rest are laid on a Mainline card, which is not a grid coordinate — see // The rest are laid on a Mainline card, which is not a grid coordinate — see
// `mainline.modify`. // `mainline.modify`.
@@ -1805,7 +1828,6 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
const from = trayCoord(s, i.trayId)!; const from = trayCoord(s, i.trayId)!;
const dests = destinationsFor(s, player, i.trayId, from, i.reverse); const dests = destinationsFor(s, player, i.trayId, from, i.reverse);
const dest = selectDestination(dests, i.to, i.via)!; const dest = selectDestination(dests, i.to, i.via)!;
const tray = s.trays.get(i.trayId)!;
// The port the crew pulls out THROUGH — the same one `destinationsFor` explored from, so the // The port the crew pulls out THROUGH — the same one `destinationsFor` explored from, so the
// cut it recouples on the way out is the cut the walk counted. // cut it recouples on the way out is the cut the walk counted.
const facingNow = facingPort(s, i.trayId); const facingNow = facingPort(s, i.trayId);
@@ -1990,11 +2012,23 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
// empty spot." Only when taking the last card actually empties the pile; refilling on every // empty spot." Only when taking the last card actually empties the pile; refilling on every
// draw would grow the Departments without limit and drain the Home Office deck into them. // draw would grow the Departments without limit and drain the Home Office deck into them.
const refill = s.decks.homeOffice[s.decks.homeOffice.length - 1]; const refill = s.decks.homeOffice[s.decks.homeOffice.length - 1];
if (pile.length === 1 && refill) { if (pile.length === 1) {
events.push({ type: 'departmentRefilled', slot: i.slot, cardId: refill }); if (refill) events.push({ type: 'departmentRefilled', slot: i.slot, cardId: refill });
const sweep = reshuffleIfDepleted(s, 1); /**
* THE SWEEP DESCRIBES THE TABLE AFTER THE DRAW AND THE REFILL, not before (v0.8.3).
*
* This used to call `reshuffleIfDepleted` on the state as it stood, so the sweep collected
* the card being drawn — still on its pile — and missed the refill card — still on the
* deck. The reducers then dealt the drawn card into the new deck while the refill card,
* moved onto a pile the reshuffle wiped a moment later, left the game: one card in two
* places, one card in none. Proven by counting, and pinned in `apply.test.ts`.
*/
const deckAfter = s.decks.homeOffice.length - (refill ? 1 : 0);
if (deckAfter <= 0) {
const sweep = sweepDeck(s, { exclude: [pile[pile.length - 1]!], include: refill ? [refill] : [] });
if (sweep) events.push(sweep); if (sweep) events.push(sweep);
} }
}
return events; return events;
} }
@@ -2119,7 +2153,7 @@ function execute(s: GameState, player: PlayerIndex, i: Intent): GameEvent[] {
i.from === 'menAtWork' i.from === 'menAtWork'
? { type: workTrack(f)[i.index]!.type, loaded: true } ? { type: workTrack(f)[i.index]!.type, loaded: true }
: (i.from === 'outbound' ? f.outboundBox : f.inboundBox)[i.index]!; : (i.from === 'outbound' ? f.outboundBox : f.inboundBox)[i.index]!;
return [{ type: 'facilityUnjammed', player, at: i.at, from: i.from, stock }]; return [{ type: 'facilityUnjammed', player, at: i.at, from: i.from, index: i.index, stock }];
} }
case 'newTrain.startExtra': { case 'newTrain.startExtra': {
@@ -2417,7 +2451,7 @@ export function reduce(s: GameState, e: GameEvent): void {
* front of `stock` is a drop being undone, so it is refunded on the square it was left on * front of `stock` is a drop being undone, so it is refunded on the square it was left on
* instead of being charged again at the far end. * instead of being charged again at the far end.
*/ */
const owner = playerAtSeat(s, trayySeat(tray)); const owner = playerAtSeat(s, traySeat(tray));
const taken = e.recoupled ? e.stock.slice(e.recoupled.stock.length) : e.stock; const taken = e.recoupled ? e.stock.slice(e.recoupled.stock.length) : e.stock;
spendFreightBudget(s, owner, tray, e.at, taken); spendFreightBudget(s, owner, tray, e.at, taken);
if (e.recoupled) refundFreightBudget(s, owner, tray, e.recoupled.at, e.recoupled.stock); if (e.recoupled) refundFreightBudget(s, owner, tray, e.recoupled.at, e.recoupled.stock);
@@ -2440,7 +2474,7 @@ export function reduce(s: GameState, e: GameEvent): void {
*/ */
tray.engineAt = e.engineAt; tray.engineAt = e.engineAt;
// "Spends one move in the yard" — the sort costs a Move. // "Spends one move in the yard" — the sort costs a Move.
const sorter = turnOf(s, playerAtSeat(s, trayySeat(tray))); const sorter = turnOf(s, playerAtSeat(s, traySeat(tray)));
sorter.movesRemaining = Math.max(0, sorter.movesRemaining - 1); sorter.movesRemaining = Math.max(0, sorter.movesRemaining - 1);
break; break;
} }
@@ -2487,7 +2521,7 @@ export function reduce(s: GameState, e: GameEvent): void {
// cars set out to the east leave it where it was. // cars set out to the east leave it where it was.
card.standingWest = onWestSide ? k + cut.length : k; card.standingWest = onWestSide ? k + cut.length : k;
} }
spendFreightBudget(s, playerAtSeat(s, trayySeat(tray)), tray, e.at, e.stock); spendFreightBudget(s, playerAtSeat(s, traySeat(tray)), tray, e.at, e.stock);
break; break;
} }
@@ -2715,12 +2749,20 @@ export function reduce(s: GameState, e: GameEvent): void {
case 'facilityUnjammed': { case 'facilityUnjammed': {
const f = facilityAt(s, e.player, e.at)!; const f = facilityAt(s, e.player, e.at)!;
/**
* THE BOX THE PLAYER NAMED (v0.8.3). The event used to carry no index, so this cleared the
* FIRST load on MEN | AT | WORK and the first car of the right type in a box — the same
* "westmost car" fault `unloadBegan` once had. With an inbound tank on MEN and a stranded
* hopper on WORK, unjamming the hopper deleted the tank load and sent a loaded hopper to
* the yard, and the jam stayed. Events are regenerated on replay, so old saves carry it.
*/
if (e.from === 'menAtWork') { if (e.from === 'menAtWork') {
const idx = workTrack(f).findIndex((l) => l !== null); const track = workTrack(f);
if (idx >= 0) workTrack(f)[idx] = null; const idx = track[e.index] ? e.index : track.findIndex((l) => l !== null);
if (idx >= 0) track[idx] = null;
} else { } else {
const box = e.from === 'outbound' ? f.outboundBox : f.inboundBox; const box = e.from === 'outbound' ? f.outboundBox : f.inboundBox;
const idx = box.findIndex((c) => c.type === e.stock.type); const idx = box[e.index]?.type === e.stock.type ? e.index : box.findIndex((c) => c.type === e.stock.type);
if (idx >= 0) box.splice(idx, 1); if (idx >= 0) box.splice(idx, 1);
} }
s.yards.classificationYard.push(pooled(e.stock)); s.yards.classificationYard.push(pooled(e.stock));
@@ -3139,7 +3181,6 @@ export function watertowersRemovable(area: OfficeArea): GridCoord[] {
* - ABS Signals → a Mainline card, not the Office Area * - ABS Signals → a Mainline card, not the Office Area
*/ */
export function checkEnhancementPlacement( export function checkEnhancementPlacement(
s: GameState,
area: OfficeArea, area: OfficeArea,
key: string, key: string,
placement: GridCoord, placement: GridCoord,
@@ -3257,11 +3298,23 @@ function isSpentTimetabledTrain(s: GameState, id: CardId): boolean {
function reshuffleIfDepleted(s: GameState, taking: number): GameEvent | null { function reshuffleIfDepleted(s: GameState, taking: number): GameEvent | null {
if (s.decks.homeOffice.length > taking) return null; if (s.decks.homeOffice.length > taking) return null;
return sweepDeck(s, { exclude: [], include: [] });
}
/**
* §6.2's reshuffle: the Salvage Yard and the three Departments come back as one deck.
*
* `exclude` names cards the events queued ahead of this one are taking OFF the Departments (a card
* being drawn), `include` the ones they are putting ON (a refill from the deck) — so the sweep
* matches the table the reducer will find, not the one the caller is looking at.
*/
function sweepDeck(s: GameState, adjust: { exclude: CardId[]; include: CardId[] }): GameEvent | null {
const collected = [ const collected = [
// The Salvage Yard, less the trains whose slots are already filled — see above. // The Salvage Yard, less the trains whose slots are already filled — see above.
...s.decks.salvageYard.filter((id) => !isSpentTimetabledTrain(s, id)), ...s.decks.salvageYard.filter((id) => !isSpentTimetabledTrain(s, id)),
// Every Department in full: a discarded train was never played, so it is still runnable. // Every Department in full: a discarded train was never played, so it is still runnable.
...s.decks.departments.flat(), ...s.decks.departments.flat().filter((id) => !adjust.exclude.includes(id)),
...adjust.include,
]; ];
if (collected.length === 0) return null; if (collected.length === 0) return null;
const rng = createRng(s.rngState); const rng = createRng(s.rngState);
+35 -13
View File
@@ -1226,6 +1226,17 @@ export type HouseRules = {
extraStart: ExtraStartRule; extraStart: ExtraStartRule;
/** Which Office every player opens on — see `StartingOffice`. */ /** Which Office every player opens on — see `StartingOffice`. */
startingOffice: StartingOffice; startingOffice: StartingOffice;
/**
* WHETHER THE SECOND SECTION CARD IS IN THE DECK (Q9, one copy).
*
* Not a table's choice — there is no dial for it — but a fact about how the game was DEALT, kept
* here for the same reason `startingOffice` is: the deal has to be replayable. The card went into
* the deck in v0.8.2, after that release's save check had been run, and a deck one card larger
* shuffles into a different order from the same seed — so every save on the test server refused
* at move 3 under 0.8.2 while its release notes said three would resume. `withSavedDeal` sets
* this false for a save that predates the card; everything dealt since carries it as true.
*/
secondSectionCard: boolean;
/** /**
* §6.2 — MAY A TIMETABLED TRAIN BE THROWN AWAY? (Gitea#9, superseding Gitea#6.) * §6.2 — MAY A TIMETABLED TRAIN BE THROWN AWAY? (Gitea#9, superseding Gitea#6.)
* *
@@ -1262,6 +1273,7 @@ export type HouseRuleOverrides = {
extraStart?: ExtraStartRule; extraStart?: ExtraStartRule;
discardTimetabled?: boolean; discardTimetabled?: boolean;
startingOffice?: StartingOffice; startingOffice?: StartingOffice;
secondSectionCard?: boolean;
}; };
/** The dialog's range. Zero is a real setting: it switches an economy off so the others can be read. */ /** The dialog's range. Zero is a real setting: it switches an economy off so the others can be read. */
@@ -1287,6 +1299,7 @@ export const DEFAULT_HOUSE_RULES: HouseRules = {
* harder setting for a table that wants it. * harder setting for a table that wants it.
*/ */
startingOffice: 'depot', startingOffice: 'depot',
secondSectionCard: true,
}; };
/** /**
@@ -1306,8 +1319,9 @@ export const LEGACY_HOUSE_RULES: HouseRules = {
// These games predate Gitea#6 as well as Gitea#9: a train card could simply be discarded. `true` // These games predate Gitea#6 as well as Gitea#9: a train card could simply be discarded. `true`
// is what they were played under, and a replay that discards a Timetabled train needs it. // is what they were played under, and a replay that discards a Timetabled train needs it.
discardTimetabled: true, discardTimetabled: true,
// Every game before 2026-09-23 opened on a Whistle Post. // Every game before 2026-09-23 opened on a Whistle Post, from a deck with no Second Section card.
startingOffice: 'whistlePost', startingOffice: 'whistlePost',
secondSectionCard: false,
}; };
/** A whole, valid rule set from a config that may carry none, some, or out-of-range values. */ /** A whole, valid rule set from a config that may carry none, some, or out-of-range values. */
@@ -1329,28 +1343,36 @@ export function houseRules(config: { houseRules?: HouseRuleOverrides }): HouseRu
extraStart: given.extraStart ?? d.extraStart, extraStart: given.extraStart ?? d.extraStart,
discardTimetabled: given.discardTimetabled ?? d.discardTimetabled, discardTimetabled: given.discardTimetabled ?? d.discardTimetabled,
startingOffice: given.startingOffice ?? d.startingOffice, startingOffice: given.startingOffice ?? d.startingOffice,
secondSectionCard: given.secondSectionCard ?? d.secondSectionCard,
}; };
} }
/** /**
* THE OPENING A SAVE THAT PREDATES THE SETTING WAS DEALT UNDER. * THE DEAL A SAVE THAT PREDATES THE 0.8.2 SETTINGS WAS DEALT UNDER.
* *
* `startingOffice` is unlike every other house rule: the others change how a game PLAYS, and * Two of the house rules change how a game is DEALT rather than how it plays, and getting either
* getting one wrong stops a replay part-way where it can be seen. This one changes how the game is * wrong does not stop a replay part-way where it can be seen — it deals a different railroad from
* DEALT — a different Office, and a deck with four more cards in it — so a save replayed under the * intent one, silently. `startingOffice` is a different Office and a deck with four more cards in
* wrong opening is a different railroad from intent one, and the failure is silent. * it; `secondSectionCard` is a deck one card larger, which the same seed shuffles into a different
* order. Every game saved before 2026-09-23 opened on a Whistle Post from a deck without the
* Second Section card, and its `houseRules` cannot say so.
* *
* Every game saved before 2026-09-23 opened on a Whistle Post and its `houseRules` cannot say so. * So a saved config that names house rules but not `startingOffice` — the settings form has named
* So a saved config that names house rules but not this one gets what it was played under. * it on every config written since the setting existed — gets both of what it was played under.
* A config with no house rules at all is a fresh game, not an old save, and is left alone; so is
* one that names the opening, in either direction.
* *
* APPLIED ON THE REPLAY PATHS ONLY, never inside `houseRules()`. A preset, the setup form and the * APPLIED ON THE REPLAY PATHS ONLY (`configFor` in `web/game.ts`, `tryResumeSession` in
* lobby all build configs that name some rules and not others, and they mean today's default — * `server/session.ts`), never in `houseRules()` above: putting the legacy default in the resolver
* putting this in the resolver made a fresh Cutthroat game deal Whistle Posts and read as Custom. * made a fresh game deal the old railroad and read as "Custom" in the lobby.
*/ */
export function withSavedOpening<T extends { houseRules?: HouseRuleOverrides }>(config: T): T { export function withSavedDeal<T extends { houseRules?: HouseRuleOverrides }>(config: T): T {
const given = config.houseRules; const given = config.houseRules;
if (!given || given.startingOffice !== undefined) return config; if (!given || given.startingOffice !== undefined) return config;
return { ...config, houseRules: { ...given, startingOffice: 'whistlePost' } }; return {
...config,
houseRules: { ...given, startingOffice: 'whistlePost', secondSectionCard: given.secondSectionCard ?? false },
};
} }
/** What the dialog calls each option, in the order it offers them. */ /** What the dialog calls each option, in the order it offers them. */
+3 -2
View File
@@ -139,7 +139,8 @@ export type GameEvent =
trainNumber: number; trainNumber: number;
office: string; office: string;
owner: SeatIndex; owner: SeatIndex;
freedBy: number; /** The train whose arrival freed the track — or null when a departure freed it (v0.8.3). */
freedBy: number | null;
} }
| { type: 'cardDrawn'; player: PlayerIndex; source: 'homeOffice' | 'department'; slot?: number; cardId: CardId } | { type: 'cardDrawn'; player: PlayerIndex; source: 'homeOffice' | 'department'; slot?: number; cardId: CardId }
/** /**
@@ -181,7 +182,7 @@ export type GameEvent =
// -- freight agent // -- freight agent
| { type: 'stockToOutbound'; player: PlayerIndex; at: GridCoord; stock: RollingStock } | { type: 'stockToOutbound'; player: PlayerIndex; at: GridCoord; stock: RollingStock }
| { type: 'inboundCleared'; player: PlayerIndex; at: GridCoord; stock: RollingStock } | { type: 'inboundCleared'; player: PlayerIndex; at: GridCoord; stock: RollingStock }
| { type: 'facilityUnjammed'; player: PlayerIndex; at: GridCoord; from: string; stock: RollingStock } | { type: 'facilityUnjammed'; player: PlayerIndex; at: GridCoord; from: string; index: number; stock: RollingStock }
// -- trains // -- trains
/** /**
* §7 — a Timetabled Train card played from hand is scheduled by a 1D12 roll. `rngState` carries * §7 — a Timetabled Train card played from hand is scheduled by a 1D12 roll. `rngState` carries
+1 -1
View File
@@ -4,7 +4,7 @@
* An intent is a PROPOSAL. It may be rejected. Contrast with an event (events.ts), which is a fact. * An intent is a PROPOSAL. It may be rejected. Contrast with an event (events.ts), which is a fact.
*/ */
import type { CarType, Direction, Hand, OfficeTier, TrackGeometry } from './content.ts'; import type { CarType, Direction, OfficeTier } from './content.ts';
import type { CardId, GridCoord, PlayerIndex, SeatIndex, TrayId } from './state.ts'; import type { CardId, GridCoord, PlayerIndex, SeatIndex, TrayId } from './state.ts';
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+1 -4
View File
@@ -12,7 +12,7 @@
* If you find yourself writing a rule here, it belongs in apply.ts. * If you find yourself writing a rule here, it belongs in apply.ts.
*/ */
import type { CarType, Hand, TrackGeometry } from './content.ts'; import type { CarType } from './content.ts';
import { enhancementRule, mainlineProfile } from './content.ts'; import { enhancementRule, mainlineProfile } from './content.ts';
import { check, areaOf, destinationsFor, withRouteCache } from './apply.ts'; import { check, areaOf, destinationsFor, withRouteCache } from './apply.ts';
import type { Intent } from './intents.ts'; import type { Intent } from './intents.ts';
@@ -191,9 +191,6 @@ export function legalSwitchingActions(s: GameState, player: PlayerIndex): Intent
return withRouteCache(s, () => switchCandidates(s, player).filter((i) => check(s, player, i) === null)); return withRouteCache(s, () => switchCandidates(s, player).filter((i) => check(s, player, i) === null));
} }
export function isLegal(s: GameState, player: PlayerIndex, i: Intent): boolean {
return check(s, player, i) === null;
}
/** /**
* Candidate generation. Over-generates freely — `check` is the authority, so a candidate that * Candidate generation. Over-generates freely — `check` is the authority, so a candidate that
-6
View File
@@ -67,9 +67,3 @@ export function createRng(seed: number): Rng {
}; };
} }
/** Restore an RNG mid-stream, for rebuilding a game from a snapshot. */
export function restoreRng(state: number): Rng {
// mulberry32 advances from its state before drawing, and createRng seeds state directly,
// so restoring is just seeding with the saved state.
return createRng(state);
}
+4 -3
View File
@@ -19,7 +19,6 @@ import {
OPENING_DEALS, OPENING_DEALS,
MAINLINE_DECK, MAINLINE_DECK,
houseRules, houseRules,
mainlineProfile,
TRACK_CARDS, TRACK_CARDS,
ROLLING_STOCK_SUPPLY, ROLLING_STOCK_SUPPLY,
STAGES_PER_DAY, STAGES_PER_DAY,
@@ -59,6 +58,8 @@ export function buildDeck(
mode: GameConfig['mode'] = 'competitive', mode: GameConfig['mode'] = 'competitive',
pvpCardsAllowed = false, pvpCardsAllowed = false,
startingOffice: StartingOffice = 'whistlePost', startingOffice: StartingOffice = 'whistlePost',
/** False only for a save that predates the card — see `HouseRules.secondSectionCard`. */
secondSectionCard = true,
): Card[] { ): Card[] {
/** /**
* THE 22 OPPONENT-DIRECTED CARDS ARE OUT OF EVERY DECK REGARDLESS OF `pvpCardsAllowed`, for now. * THE 22 OPPONENT-DIRECTED CARDS ARE OUT OF EVERY DECK REGARDLESS OF `pvpCardsAllowed`, for now.
@@ -116,7 +117,7 @@ export function buildDeck(
* Jesse's ruling, 2026-09-23: the action requires the card. Dealing it is the other half — gating * Jesse's ruling, 2026-09-23: the action requires the card. Dealing it is the other half — gating
* on a card the deck never holds would delete the mechanic rather than fix it. * on a card the deck never holds would delete the mechanic rather than fix it.
*/ */
for (let i = 0; i < SECOND_SECTION.copies; i++) push({ kind: 'secondSection' }); if (secondSectionCard) for (let i = 0; i < SECOND_SECTION.copies; i++) push({ kind: 'secondSection' });
if (opponentCardsInDeck) { if (opponentCardsInDeck) {
for (const c of SPACE_USE_CARDS) { for (const c of SPACE_USE_CARDS) {
for (let i = 0; i < c.copies; i++) push({ kind: 'spaceUse', key: c.key }); for (let i = 0; i < c.copies; i++) push({ kind: 'spaceUse', key: c.key });
@@ -369,7 +370,7 @@ export function createGame(opts: SetupOptions): GameState {
*/ */
const rules = houseRules(config); const rules = houseRules(config);
const deal = OPENING_DEALS[rules.startingHand]; const deal = OPENING_DEALS[rules.startingHand];
const deck = buildDeck(config.mode, config.pvpCardsAllowed, rules.startingOffice); const deck = buildDeck(config.mode, config.pvpCardsAllowed, rules.startingOffice, rules.secondSectionCard);
const cards = new Map<CardId, Card>(); const cards = new Map<CardId, Card>();
for (const c of deck) cards.set(c.id, c); for (const c of deck) cards.set(c.id, c);
+134 -14
View File
@@ -18,7 +18,7 @@
*/ */
import { createServer } from 'node:http'; import { createServer } from 'node:http';
import type { IncomingMessage, ServerResponse } from 'node:http'; import type { IncomingMessage, Server, ServerResponse } from 'node:http';
import { createReadStream } from 'node:fs'; import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises'; import { stat } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path'; import { extname, join, normalize } from 'node:path';
@@ -97,14 +97,57 @@ const MIME: Record<string, string> = {
const HEARTBEAT_MS = 20_000; const HEARTBEAT_MS = 20_000;
async function readJson(req: IncomingMessage): Promise<unknown> { /**
* THE LARGEST BODY ANY ROUTE HERE HAS A USE FOR, with room to spare (v0.8.4). The biggest thing a
* client sends is a `GameConfig` on `/api/lobby/create` — a few hundred bytes. `readJson` used to
* buffer whatever arrived, before any secret was checked, so anyone who could reach the port could
* exhaust the process's memory with one POST. D14 expects this box to be reachable.
*/
const MAX_BODY_BYTES = 64 * 1024;
/** A refusal with a status — thrown from anywhere in a handler and answered by the one catch. */
class HttpError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
async function readJson(req: IncomingMessage): Promise<Record<string, unknown>> {
const declared = Number(req.headers['content-length'] ?? 0);
if (declared > MAX_BODY_BYTES) throw new HttpError(413, 'body too large');
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer); let size = 0;
for await (const chunk of req) {
size += (chunk as Buffer).length;
if (size > MAX_BODY_BYTES) throw new HttpError(413, 'body too large');
chunks.push(chunk as Buffer);
}
const text = Buffer.concat(chunks).toString('utf8'); const text = Buffer.concat(chunks).toString('utf8');
return text.trim() === '' ? {} : JSON.parse(text); if (text.trim() === '') return {};
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
// A malformed body is the caller's mistake, answered as one — it used to surface as a 500.
throw new HttpError(400, 'body is not JSON');
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new HttpError(400, 'expected a JSON object');
return parsed as Record<string, unknown>;
} }
function sendJson(res: ServerResponse, status: number, body: unknown): void { function sendJson(res: ServerResponse, status: number, body: unknown): void {
/**
* NEVER A SECOND HEAD (v0.8.4). The SSE routes and `serveStatic` write their head and go on; a
* throw after that reached the handler's catch, which called this, and `writeHead` on a response
* whose head was sent throws `ERR_HTTP_HEADERS_SENT` — inside a `.catch`, with nothing above it,
* so Node exited on the unhandled rejection. One bad stream write was a whole-server crash.
*/
if (res.headersSent) {
res.end();
return;
}
const text = JSON.stringify(body); const text = JSON.stringify(body);
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) }); res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) });
res.end(text); res.end(text);
@@ -149,7 +192,11 @@ async function serveStatic(
'Content-Length': info.size, 'Content-Length': info.size,
'Cache-Control': buildTagged ? 'public, max-age=31536000, immutable' : 'no-cache', 'Cache-Control': buildTagged ? 'public, max-age=31536000, immutable' : 'no-cache',
}); });
createReadStream(full).pipe(res); // A read that fails mid-stream (file replaced by a deploy, disk error) closes the response rather
// than raising an error nothing listens for.
createReadStream(full)
.on('error', () => res.destroy())
.pipe(res);
} catch { } catch {
res.writeHead(404, { 'Content-Type': 'text/plain' }); res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('not found'); res.end('not found');
@@ -175,7 +222,8 @@ type LobbyPreview = {
seated: { seat: number; who: string | null; bot: boolean }[]; seated: { seat: number; who: string | null; bot: boolean }[];
}; };
export function startServer(opts: ServerOptions): void { /** Returns the listening server — a test binds port 0 and reads the port back off it. */
export function startServer(opts: ServerOptions): Server {
const games = opts.initialGames; const games = opts.initialGames;
const lobbies = opts.initialLobbies; const lobbies = opts.initialLobbies;
const sessions = opts.initialSessions; const sessions = opts.initialSessions;
@@ -283,8 +331,29 @@ export function startServer(opts: ServerOptions): void {
async function persistSession(ps: PlayerSession): Promise<void> { async function persistSession(ps: PlayerSession): Promise<void> {
sessions.set(ps.token, ps); sessions.set(ps.token, ps);
const all = [...sessions.values()].filter((s) => s.gameId === ps.gameId); await persistSessionsOf(ps.gameId);
await writeSessions(opts.dataDir, ps.gameId, all); }
/** Rewrites one game's `sessions.json` from what is in memory — after a token is revoked as much
* as after one is issued, or a restart would hand the seat back to a browser that left it. */
async function persistSessionsOf(gameId: string): Promise<void> {
const all = [...sessions.values()].filter((s) => s.gameId === gameId);
await writeSessions(opts.dataDir, gameId, all);
}
/**
* ONE INTENT AT A TIME PER GAME — `protocol.md` §5's serialisation rule, which the intent handler
* relied on Node's single thread to keep and did not (v0.8.4): the `await` on the disk write is
* an interleaving point, so two moves arriving together could both apply in memory, race their
* writes to one `.tmp`, and hand their broadcasts to the clients in the wrong order. Everything a
* move does — apply, persist, answer, broadcast — now runs as one unit behind the move before it.
*/
const gameQueues = new Map<string, Promise<unknown>>();
function inTurn<T>(gameId: string, fn: () => Promise<T>): Promise<T> {
const prev = gameQueues.get(gameId) ?? Promise.resolve();
const next = prev.then(fn, fn);
gameQueues.set(gameId, next.catch(() => undefined));
return next;
} }
const server = createServer((req, res) => { const server = createServer((req, res) => {
@@ -571,6 +640,17 @@ export function startServer(opts: ServerOptions): void {
sendJson(res, 403, { error: 'NOT_HOST' }); sendJson(res, 403, { error: 'NOT_HOST' });
return; return;
} }
/**
* THE SEAT GOES, AND SO DOES THE TOKEN THAT HELD IT (v0.8.4).
*
* Leaving used to free the chair and keep the session: the token stayed in `sessions` and
* on disk, and `joinLobby` hands a vacated chair to the next arrival. So a player who left
* (or was removed) still held a token for seat N, and once somebody else sat in seat N and
* the game began, `/api/stream` served that token the new occupant's hand and `/api/intent`
* let it move for them — and its stream connection displaced theirs. Revoked here, before
* the chair is offered to anyone.
*/
const occupant = seat === undefined ? ps : [...sessions.values()].find((s) => s.gameId === lobby.gameId && s.player === seat);
const result = leaveLobby(lobby, ps.token, seat); const result = leaveLobby(lobby, ps.token, seat);
if (result.empty) { if (result.empty) {
// Nobody human is left to start it. Everything about this lobby goes, including the code, // Nobody human is left to start it. Everything about this lobby goes, including the code,
@@ -579,6 +659,7 @@ export function startServer(opts: ServerOptions): void {
gameCodes.delete(lobby.gameCode); gameCodes.delete(lobby.gameCode);
for (const [, watcher] of lobbyConnections.get(lobby.gameId) ?? []) watcher.end(); for (const [, watcher] of lobbyConnections.get(lobby.gameId) ?? []) watcher.end();
lobbyConnections.delete(lobby.gameId); lobbyConnections.delete(lobby.gameId);
for (const [token, s] of [...sessions]) if (s.gameId === lobby.gameId) sessions.delete(token);
await deleteLobby(opts.dataDir, lobby.gameId); await deleteLobby(opts.dataDir, lobby.gameId);
// The row goes with the lobby rather than being marked: a game that never started is not a // The row goes with the lobby rather than being marked: a game that never started is not a
// game an administrator has any use for a record of. // game an administrator has any use for a record of.
@@ -586,6 +667,12 @@ export function startServer(opts: ServerOptions): void {
sendJson(res, 200, { ok: true, closed: true }); sendJson(res, 200, { ok: true, closed: true });
return; return;
} }
if (occupant && result.lobby !== lobby) {
sessions.delete(occupant.token);
lobbyConnections.get(lobby.gameId)?.get(occupant.token)?.end();
lobbyConnections.get(lobby.gameId)?.delete(occupant.token);
await persistSessionsOf(lobby.gameId);
}
await persistLobby(result.lobby); await persistLobby(result.lobby);
broadcastLobby(lobby.gameId); broadcastLobby(lobby.gameId);
sendJson(res, 200, { ok: true }); sendJson(res, 200, { ok: true });
@@ -690,7 +777,9 @@ export function startServer(opts: ServerOptions): void {
// `lobby`, because it may have changed (another join, another bot toggle) since connect. // `lobby`, because it may have changed (another join, another bot toggle) since connect.
const current = lobbies.get(lobby.gameId); const current = lobbies.get(lobby.gameId);
if (current && current.hostToken === token) { if (current && current.hostToken === token) {
void persistLobby(reassignHost(current, token)).then(() => broadcastLobby(lobby.gameId)); persistLobby(reassignHost(current, token))
.then(() => broadcastLobby(lobby.gameId))
.catch((err: unknown) => console.error(`reassigning the host of ${lobby.gameId} failed:`, err));
} }
}); });
return; return;
@@ -756,8 +845,15 @@ export function startServer(opts: ServerOptions): void {
* The administrative export at `/api/games/<id>/save` is gated on the admin secret, which a player * The administrative export at `/api/games/<id>/save` is gated on the admin secret, which a player
* does not have and should not need: a save is the seed and the moves, and every one of those moves * does not have and should not need: a save is the seed and the moves, and every one of those moves
* is already on this player's screen. So the seat's own session token is the gate, exactly as it is * is already on this player's screen. So the seat's own session token is the gate, exactly as it is
* for `/api/stream` and `/api/intent` — it proves which game and which chair, and nothing else is * for `/api/stream` and `/api/intent` — it proves which game and which chair. The page turns the
* disclosed. The page turns the JSON into a file (`main.ts`'s `downloadSave`). * JSON into a file (`main.ts`'s `downloadSave`).
*
* NOT WHILE A COMPETITIVE GAME IS RUNNING (Jesse's ruling, 2026-09-29, TODO #117). "Every one of
* those moves is already on this player's screen" was true of the moves and false of the SEED,
* which a save has to carry to be a save — and the seed is every rival's hand and the deck order
* for the rest of the game, the exact thing `game.ts` strips from the shared log. So a
* Competitive seat gets its save once the game is over; a Co-op table has nothing to hide from
* itself and gets it at any time, as does a one-seat game.
*/ */
if (url.pathname === '/api/save' && req.method === 'GET') { if (url.pathname === '/api/save' && req.method === 'GET') {
const ps = sessions.get(url.searchParams.get('token') ?? ''); const ps = sessions.get(url.searchParams.get('token') ?? '');
@@ -766,7 +862,13 @@ export function startServer(opts: ServerOptions): void {
sendJson(res, 404, { error: 'no such game' }); sendJson(res, 404, { error: 'no such game' });
return; return;
} }
sendJson(res, 200, { gameId: ps.gameId, save: session.exportSave() }); const save = session.exportSave();
const competitive = save.config.mode === 'competitive' && save.playerNames.length > 1;
if (competitive && save.status !== 'finished') {
sendJson(res, 403, { error: 'SAVE_AFTER_FINISH' });
return;
}
sendJson(res, 200, { gameId: ps.gameId, save });
return; return;
} }
@@ -820,11 +922,14 @@ export function startServer(opts: ServerOptions): void {
sendJson(res, 400, { error: 'expected { seq, intent }' }); sendJson(res, 400, { error: 'expected { seq, intent }' });
return; return;
} }
const result = session.intent(ps.player, body.seq, body.intent); const { seq, intent } = body;
await inTurn(ps.gameId, async () => {
const result = session.intent(ps.player, seq, intent);
if (result.accepted) { if (result.accepted) {
// Persisted BEFORE the response goes out — "accepted" should mean "durably on disk" at // Persisted BEFORE the response goes out — "accepted" should mean "durably on disk" at
// this scale, not just "applied in memory" (§12 step 14). // this scale, not just "applied in memory" (§12 step 14).
const dir = gameDir(opts.dataDir, ps.gameId); const dir = gameDir(opts.dataDir, ps.gameId);
try {
await writeGame(dir, session.exportSave(), opts.engineVersion); await writeGame(dir, session.exportSave(), opts.engineVersion);
if (result.timing) await appendTiming(dir, result.timing); if (result.timing) await appendTiming(dir, result.timing);
if (session.exportSave().status === 'finished') { if (session.exportSave().status === 'finished') {
@@ -834,17 +939,32 @@ export function startServer(opts: ServerOptions): void {
const gameCode = [...gameCodes.entries()].find(([, id]) => id === ps.gameId)?.[0] ?? ''; const gameCode = [...gameCodes.entries()].find(([, id]) => id === ps.gameId)?.[0] ?? '';
await upsertIndexEntry(opts.dataDir, { gameId: ps.gameId, gameCode, status: 'finished' }); await upsertIndexEntry(opts.dataDir, { gameId: ps.gameId, gameCode, status: 'finished' });
} }
} catch (err) {
// The move IS applied — every seat's game has moved on — so the table is told and the
// disk's failure is the operator's to see in the log. Answering 500 here told the one
// player who moved that their move was refused, while everyone else watched it happen.
console.error(`persisting ${ps.gameId} after a move failed:`, err);
}
} }
sendJson(res, 200, result.accepted ? { ok: true } : { ok: false, code: result.code }); sendJson(res, 200, result.accepted ? { ok: true } : { ok: false, code: result.code });
if (result.accepted) broadcastGame(ps.gameId, result.pushes); if (result.accepted) broadcastGame(ps.gameId, result.pushes);
});
return; return;
} }
await serveStatic(opts.distDir, url.pathname, res, url.searchParams.has('v')); await serveStatic(opts.distDir, url.pathname, res, url.searchParams.has('v'));
})().catch((err: unknown) => { })().catch((err: unknown) => {
sendJson(res, 500, { error: err instanceof Error ? err.message : 'internal error' }); if (err instanceof HttpError) {
sendJson(res, err.status, { error: err.message });
return;
}
// Logged here, not echoed: an fs error's message carries the absolute path of the data
// directory, which is the operator's to know and not the caller's.
console.error(`${req.method ?? ''} ${req.url ?? ''} failed:`, err);
sendJson(res, 500, { error: 'internal error' });
}); });
}); });
server.listen(opts.port, opts.bindAddress); server.listen(opts.port, opts.bindAddress);
return server;
} }
+15 -1
View File
@@ -61,8 +61,22 @@ for (const entry of index) {
} }
const loaded = await loadGame(gameDir(dataDir, entry.gameId)); const loaded = await loadGame(gameDir(dataDir, entry.gameId));
if (!loaded.found && loaded.corrupt) {
// One unreadable file is one game lost, not every game (v0.8.4) — see `loadGame`.
console.error(`Skipping ${entry.gameId} (${entry.gameCode}): game.json is unreadable — ${loaded.corrupt}. The file is left untouched.`);
continue;
}
if (loaded.found) { if (loaded.found) {
const resumed = tryResumeSession(loaded.saved); let resumed: ReturnType<typeof tryResumeSession>;
try {
resumed = tryResumeSession(loaded.saved);
} catch (err) {
// A save that parses but is not the shape the replay expects (no config, a history entry
// that is not an intent) throws inside the engine rather than being refused. Same answer:
// this game, not the server.
console.error(`Skipping ${entry.gameId} (${entry.gameCode}): the save could not be replayed — ${err instanceof Error ? err.message : String(err)}. The file is left untouched.`);
continue;
}
if (resumed.ok) { if (resumed.ok) {
initialGames.set(entry.gameId, resumed.session); initialGames.set(entry.gameId, resumed.session);
console.log(`Resumed ${entry.gameId} (${entry.gameCode}) — ${loaded.saved.history.length} intents replayed.`); console.log(`Resumed ${entry.gameId} (${entry.gameCode}) — ${loaded.saved.history.length} intents replayed.`);
+2 -1
View File
@@ -91,8 +91,9 @@ export function playerCountAllowed(mode: GameConfig['mode'], count: number): boo
return mode === 'solitaire' ? count === 1 : count >= 2 && count <= 4; return mode === 'solitaire' ? count === 1 : count >= 2 && count <= 4;
} }
/** The creating player is the host and takes seat 0 (`lobby-and-sessions.md` §2). */
/** /**
* The creating player is the host and takes seat 0 (`lobby-and-sessions.md` §2).
*
* THE TABLE SIZE IS FIXED WHEN THE GAME IS CREATED, and `seats.length` is it. * THE TABLE SIZE IS FIXED WHEN THE GAME IS CREATED, and `seats.length` is it.
* *
* The host says how many are playing, so the seats array is built at full length with the host in * The host says how many are playing, so the seats array is built at full length with the host in
+49 -3
View File
@@ -24,10 +24,33 @@ const INDEX_FILE = 'index.json';
type PersistedGame = SavedGame & { engineVersion: string }; type PersistedGame = SavedGame & { engineVersion: string };
/**
* ONE WRITER AT A TIME PER FILE (v0.8.4).
*
* Every write here is read-modify-write or write-then-rename with an `await` in the middle, and
* Node's single thread is no protection across an `await`: two requests for the same game could
* both be inside `atomicWrite` at once. With ONE fixed `.tmp` name per path that tore the file —
* measured at 200 rounds of two concurrent writes: every round lost one write to `rename` ENOENT,
* and six left `game.json` as invalid JSON, which the boot then died on. So the temp name is unique
* per write, and every write to a given path queues behind the one before it, which is also what
* makes `upsertIndexEntry`'s "adds or updates exactly one row" claim true under two callers.
*/
const queues = new Map<string, Promise<unknown>>();
let writeSerial = 0;
function serial<T>(key: string, fn: () => Promise<T>): Promise<T> {
const prev = queues.get(key) ?? Promise.resolve();
const next = prev.then(fn, fn);
queues.set(key, next.catch(() => undefined));
return next;
}
async function atomicWrite(path: string, text: string): Promise<void> { async function atomicWrite(path: string, text: string): Promise<void> {
const tmp = `${path}.tmp`; await serial(path, async () => {
const tmp = `${path}.${process.pid}.${++writeSerial}.tmp`;
await writeFile(tmp, text); await writeFile(tmp, text);
await rename(tmp, path); await rename(tmp, path);
});
} }
export async function writeGame(dataDir: string, saved: SavedGame, engineVersion: string): Promise<void> { export async function writeGame(dataDir: string, saved: SavedGame, engineVersion: string): Promise<void> {
@@ -37,7 +60,8 @@ export async function writeGame(dataDir: string, saved: SavedGame, engineVersion
} }
export type LoadResult = export type LoadResult =
| { found: false } /** `corrupt` names the parse error when the file is there and is not JSON — see `loadGame`. */
| { found: false; corrupt?: string }
/** The version that wrote the file, for diagnostics — it is no longer what decides. */ /** The version that wrote the file, for diagnostics — it is no longer what decides. */
| { found: true; saved: SavedGame; storedVersion: string }; | { found: true; saved: SavedGame; storedVersion: string };
@@ -61,7 +85,21 @@ export async function loadGame(dataDir: string): Promise<LoadResult> {
} catch { } catch {
return { found: false }; return { found: false };
} }
const payload = JSON.parse(text) as PersistedGame; /**
* A FILE THAT IS NOT JSON IS REPORTED, NOT THROWN (v0.8.4). This parse was bare, and `index.ts`
* awaited it at the top level — so one torn or half-edited `game.json` took the whole process
* down before the port opened, and StartOS restarted it into the same file: every game on the
* server unreachable because of one. The caller gets a reason to log and moves on.
*/
let payload: PersistedGame;
try {
payload = JSON.parse(text) as PersistedGame;
} catch (err) {
return { found: false, corrupt: err instanceof Error ? err.message : String(err) };
}
if (!payload || typeof payload !== 'object' || !Array.isArray(payload.history)) {
return { found: false, corrupt: 'not a saved game (no history array)' };
}
const { engineVersion, ...saved } = payload; const { engineVersion, ...saved } = payload;
return { found: true, saved, storedVersion: engineVersion }; return { found: true, saved, storedVersion: engineVersion };
} }
@@ -71,6 +109,9 @@ export async function loadGame(dataDir: string): Promise<LoadResult> {
export async function appendTiming(dataDir: string, timing: TurnTiming): Promise<void> { export async function appendTiming(dataDir: string, timing: TurnTiming): Promise<void> {
await mkdir(dataDir, { recursive: true }); await mkdir(dataDir, { recursive: true });
const path = join(dataDir, TIMINGS_FILE); const path = join(dataDir, TIMINGS_FILE);
// The read and the write are one unit under the file's queue, or two appends could each read the
// same list and one of them would be lost.
await serial(`rmw:${path}`, async () => {
let existing: TurnTiming[]; let existing: TurnTiming[];
try { try {
existing = JSON.parse(await readFile(path, 'utf8')) as TurnTiming[]; existing = JSON.parse(await readFile(path, 'utf8')) as TurnTiming[];
@@ -79,6 +120,7 @@ export async function appendTiming(dataDir: string, timing: TurnTiming): Promise
} }
existing.push(timing); existing.push(timing);
await atomicWrite(path, JSON.stringify(existing, null, 1)); await atomicWrite(path, JSON.stringify(existing, null, 1));
});
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -113,11 +155,13 @@ async function writeIndex(dataDir: string, entries: GameIndexEntry[]): Promise<v
* silently drop every other game's row the moment two writes happened close together. * silently drop every other game's row the moment two writes happened close together.
*/ */
export async function upsertIndexEntry(dataDir: string, entry: GameIndexEntry): Promise<void> { export async function upsertIndexEntry(dataDir: string, entry: GameIndexEntry): Promise<void> {
await serial(`rmw:${join(dataDir, INDEX_FILE)}`, async () => {
const entries = await readIndex(dataDir); const entries = await readIndex(dataDir);
const i = entries.findIndex((e) => e.gameId === entry.gameId); const i = entries.findIndex((e) => e.gameId === entry.gameId);
if (i >= 0) entries[i] = entry; if (i >= 0) entries[i] = entry;
else entries.push(entry); else entries.push(entry);
await writeIndex(dataDir, entries); await writeIndex(dataDir, entries);
});
} }
/** /**
@@ -126,11 +170,13 @@ export async function upsertIndexEntry(dataDir: string, entry: GameIndexEntry):
* it on the next boot or leave `index.json` pointing at nothing. * it on the next boot or leave `index.json` pointing at nothing.
*/ */
export async function removeIndexEntry(dataDir: string, gameId: string): Promise<void> { export async function removeIndexEntry(dataDir: string, gameId: string): Promise<void> {
await serial(`rmw:${join(dataDir, INDEX_FILE)}`, async () => {
const entries = await readIndex(dataDir); const entries = await readIndex(dataDir);
await writeIndex( await writeIndex(
dataDir, dataDir,
entries.filter((e) => e.gameId !== gameId), entries.filter((e) => e.gameId !== gameId),
); );
});
} }
/** Deletes a game's whole directory — its save, its turn timings, its sessions, its lobby file. */ /** Deletes a game's whole directory — its save, its turn timings, its sessions, its lobby file. */
+15 -5
View File
@@ -18,7 +18,7 @@
* checked, before `submit` is ever called — see `intent()` below. * checked, before `submit` is ever called — see `intent()` below.
*/ */
import { withSavedOpening } from '../engine/content.ts'; import { withSavedDeal } from '../engine/content.ts';
import { check } from '../engine/apply.ts'; import { check } from '../engine/apply.ts';
import { legalActions } from '../engine/legal.ts'; import { legalActions } from '../engine/legal.ts';
import type { Intent } from '../engine/intents.ts'; import type { Intent } from '../engine/intents.ts';
@@ -72,6 +72,16 @@ export type Push = {
scheduled?: number | null; scheduled?: number | null;
announcement?: string | null; announcement?: string | null;
justDrawn?: string | null; justDrawn?: string | null;
/**
* THE LAST INTENT `seq` THIS SEAT HAD ACCEPTED — on the connect push only (v0.8.4).
*
* The client numbers its intents from 1 per page load, and this host remembers the seat's last
* accepted number for the life of the game and answers a repeat with "already applied" (§5). So
* a seat that had made one move, reloaded, and clicked again sent `seq: 1` a second time: the
* server said ok and did nothing, the page redrew nothing, and the click looked dead. Telling the
* client where the count stands lets it continue from there instead of starting over.
*/
lastSeq?: number;
/** /**
* ORDERED PRESENTATION STEPS — v0.8.0, TODO #13. * ORDERED PRESENTATION STEPS — v0.8.0, TODO #13.
* *
@@ -316,8 +326,7 @@ function buildSession(
* `lobby-and-sessions.md` §5's turn clock exists to learn how long HUMANS take, and a bot decides * `lobby-and-sessions.md` §5's turn clock exists to learn how long HUMANS take, and a bot decides
* in zero wall-clock time by definition. Called once at construction (a resume could land exactly * in zero wall-clock time by definition. Called once at construction (a resume could land exactly
* on a bot's turn) and once after every accepted human intent. * on a bot's turn) and once after every accepted human intent.
*/ *
/**
* §3.3, EXTENDED PLAY (Gitea#11) — the bots' half of a unanimous vote. * §3.3, EXTENDED PLAY (Gitea#11) — the bots' half of a unanimous vote.
* *
* "Bots will not disagree with the human. Humans get to vote first. If all humans vote yes, then * "Bots will not disagree with the human. Humans get to vote first. If all humans vote yes, then
@@ -415,6 +424,7 @@ function buildSession(
// connect IS the history, which is what lets the Frame stop carrying a second copy. // connect IS the history, which is what lets the Frame stop carrying a second copy.
sentLines.delete(seat); sentLines.delete(seat);
const push = pushFor(seat, null); const push = pushFor(seat, null);
push.lastSeq = lastSeq.get(seat) ?? 0;
/** /**
* The baseline for this client's step queue (v0.8.0). `game.display.last` is the exact frame * The baseline for this client's step queue (v0.8.0). `game.display.last` is the exact frame
* the shared delta chain has reached, so the next step merges onto it; before any step has * the shared delta chain has reached, so the next step merges onto it; before any step has
@@ -528,9 +538,9 @@ export type ResumeFailure = { stoppedAt: number; of: number; intent: string; cod
export function tryResumeSession(saved: SavedGame): { ok: true; session: GameSession } | { ok: false; failure: ResumeFailure } { export function tryResumeSession(saved: SavedGame): { ok: true; session: GameSession } | { ok: false; failure: ResumeFailure } {
// A save written before `startingOffice` existed opened on a Whistle Post and cannot say so — // A save written before `startingOffice` existed opened on a Whistle Post and cannot say so —
// replaying it under today's Depot default would deal a different railroad. See `withSavedOpening`. // replaying it under today's Depot default would deal a different railroad. See `withSavedDeal`.
const { game, stopped } = fromMultiplayerSave( const { game, stopped } = fromMultiplayerSave(
saved.seed, withSavedOpening(saved.config), saved.playerNames, saved.history, saved.seed, withSavedDeal(saved.config), saved.playerNames, saved.history,
); );
if (stopped) { if (stopped) {
return { return {
-8
View File
@@ -113,14 +113,6 @@ export function divisionSvg(nodes: DivisionView[], roster?: DivisionRoster | nul
const CHIP_Y = RAIL_Y - 10; const CHIP_Y = RAIL_Y - 10;
const BELOW_Y = RAIL_Y + 13; const BELOW_Y = RAIL_Y + 13;
const GAP = 6; const GAP = 6;
/**
* ONE FIXED SLOT PER A/D TRACK, so the Office Running Track cell is drawn wide enough to hold
* them without spilling onto its neighbours (docs/plans/switching-paths.md — "The Roster Pass").
* Sized by CAPACITY, not by how many are occupied right now: a cell drawn for the trains it HAS
* holds still as they come and go, where sizing by occupancy moved the East Division Point (and
* everything past it) sideways every time an A/D track filled or cleared.
*/
const CHIP_W = 54;
/** /**
* Room for the buffer stops. THE LABELS NO LONGER LIVE OUT HERE. * Room for the buffer stops. THE LABELS NO LONGER LIVE OUT HERE.
* *
+1 -56
View File
@@ -91,19 +91,6 @@ function because(reason: string, intent: Intent): Intent {
return intent; return intent;
} }
/**
* KNOBS FOR A/B MEASUREMENT, and nothing else.
*
* A heuristic change has to be measured against the bot it replaces, over the SAME deals — and
* editing the bot between runs makes that impossible to do honestly, because the two sides of the
* comparison never exist at once. Every flag here is off by default, so `makeDeveloperBot({})` is
* byte-identical to the bot that came before this existed.
*
* TEMPORARY BY CONSTRUCTION. When a flag measures well it becomes the default and the flag is
* deleted in the same commit; when it measures badly it is deleted with its finding recorded in the
* changelog. What must not happen is a bot that accumulates switches nobody can account for — a
* heuristic with no measurement attached is exactly what this machinery exists to prevent.
*/
/** /**
* ABLATIONS, for re-measuring the heuristics that are now the bot's default play. * ABLATIONS, for re-measuring the heuristics that are now the bot's default play.
* *
@@ -356,40 +343,13 @@ function committedTrains(s: GameState): number {
* *
* §7 lets you play as many train cards as you draw, and a train that arrives with nowhere to stand * §7 lets you play as many train cards as you draw, and a train that arrives with nowhere to stand
* is an automatic collision (Gap 2d) — so the two rules together make a train card actively harmful * is an automatic collision (Gap 2d) — so the two rules together make a train card actively harmful
* once the A/D tracks are spoken for. Off unless `trainCapSlack` is set. * once the A/D tracks are spoken for. `noTrainCap` switches the cap off for re-measurement.
*/ */
function trainWouldOverfillTheOffice(s: GameState, player: PlayerIndex, tweaks: BotTweaks): boolean { function trainWouldOverfillTheOffice(s: GameState, player: PlayerIndex, tweaks: BotTweaks): boolean {
if (tweaks.noTrainCap) return false; if (tweaks.noTrainCap) return false;
return committedTrains(s) >= officeProfile(areaOf(s, player).tier).adTracks; return committedTrains(s) >= officeProfile(areaOf(s, player).tier).adTracks;
} }
/**
* Would running here leave the engine buried among its own cars?
*
* Cars met on a FORWARD move couple onto the nose (§A.3), which pushes the engine back through its
* own train — `carsCoupled` moves `engineAt` by the number taken. So the engine ends up buried
* whenever it had cars behind it already and picks up more in front, and §8.2 then refuses to let
* the train leave the Office. Only trains care: a local crew has nowhere it must depart from.
*
* Asked of the engine's own destination list, so the count is the count that will really couple.
*/
function wouldBuryTheEngine(
s: GameState,
player: PlayerIndex,
move: Extract<Intent, { type: 'switch.move' }>,
): boolean {
const tray = s.trays.get(move.trayId);
if (!tray || tray.trainNumber === null) return false;
if (tray.position.at !== 'grid') return false;
if (move.reverse) return false; // cars taken while backing up couple BEHIND the engine
const len = tray.consist.length;
if (len === 0 || tray.engineAt >= len) return false; // nothing behind the engine to bury it against
const dest = destinationsFor(s, player, move.trayId, tray.position.coord, false).find(
(d) => d.coord.row === move.to.row && d.coord.col === move.to.col,
);
return (dest?.couples.length ?? 0) > 0;
}
function chooseLocalOption( function chooseLocalOption(
s: GameState, s: GameState,
@@ -1427,8 +1387,6 @@ function followThrough(
(i): i is Extract<Intent, { type: 'draw.fromDepartment' }> => (i): i is Extract<Intent, { type: 'draw.fromDepartment' }> =>
i.type === 'draw.fromDepartment' && isWorthTaking(s, player, i.slot, tweaks), i.type === 'draw.fromDepartment' && isWorthTaking(s, player, i.slot, tweaks),
); );
// Best-ranked pile rather than the first that qualifies: an Office card and a train card
// both "qualify", and only one of them stops the collisions.
// Best-ranked pile, not the first that qualifies. Measured as a near no-op — an Office card // Best-ranked pile, not the first that qualifies. Measured as a near no-op — an Office card
// and a train card are face up together 1.6 decisions a game — but ranking them is what the // and a train card are face up together 1.6 decisions a game — but ranking them is what the
// ranking function is for, and a coin flip on the card that decides whether the district // ranking function is for, and a coin flip on the card that decides whether the district
@@ -1980,19 +1938,6 @@ function sidingsWorthCollecting(
return out; return out;
} }
/** Cars standing on ordinary track that some facility would actually take. */
function strandedWantedCars(s: GameState, player: PlayerIndex): { row: number; col: number }[] {
const out: { row: number; col: number }[] = [];
const tray = trayOf(s, player);
if (!tray || tray.consist.length >= MAX_CONSIST) return out;
for (const [key, card] of areaOf(s, player).grid) {
if (card.facility || card.standing.length === 0) continue;
if (!card.standing.some((c) => facilitiesWanting(s, player, c).length > 0)) continue;
const [row, col] = key.split(',').map(Number);
out.push({ row: row!, col: col! });
}
return out;
}
function trayOf(s: GameState, player: PlayerIndex) { function trayOf(s: GameState, player: PlayerIndex) {
for (const tray of s.trays.values()) { for (const tray of s.trays.values()) {
+1 -1
View File
@@ -251,7 +251,7 @@ if (isMain) {
const tweaks = parseTweaks(args); const tweaks = parseTweaks(args);
if (Object.keys(tweaks).length === 0) { if (Object.keys(tweaks).length === 0) {
console.error('nothing to compare — pass at least one tweak, e.g. trainCapSlack=1'); console.error(`nothing to compare — pass at least one ablation, e.g. noValueLays=1 (one of: ${[...BOOLEAN_TWEAKS].join(', ')})`);
process.exitCode = 1; process.exitCode = 1;
} else { } else {
console.log(formatPaired(compare(tweaks, games, length))); console.log(formatPaired(compare(tweaks, games, length)));
+5 -1
View File
@@ -553,7 +553,11 @@ export function narrate(e: GameEvent, ctx: NarrateContext = {}): Narration {
text: text:
`Train ${e.trainNumber} RELEASED from the Limits into the ${e.office}` + `Train ${e.trainNumber} RELEASED from the Limits into the ${e.office}` +
`${who ? ` at ${who}'s district` : ''} — the Interlocking had been holding it clear of a ` + `${who ? ` at ${who}'s district` : ''} — the Interlocking had been holding it clear of a ` +
`full Office, and Train ${e.freedBy} arriving freed the A/D track it was waiting for. ` + `full Office, and ${
e.freedBy === null
? 'a departure freed the A/D track it was waiting for'
: `Train ${e.freedBy} arriving freed the A/D track it was waiting for`
}. ` +
'A held train takes the first track to free, ahead of anything arriving after it.', 'A held train takes the first track to free, ahead of anything arriving after it.',
}; };
} }
+3 -6
View File
@@ -19,25 +19,22 @@
import { writeFileSync } from 'node:fs'; import { writeFileSync } from 'node:fs';
import { advance } from '../engine/advance.ts'; import { advance } from '../engine/advance.ts';
import { applyIntent, areaOf, facilityCarType, laborersLeft, portersLeft } from '../engine/apply.ts'; import { applyIntent } from '../engine/apply.ts';
import type { GameLength } from '../engine/content.ts'; import type { GameLength } from '../engine/content.ts';
import { import {
DEFAULT_MAX_COLLISIONS_PER_DAY, DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL, DEFAULT_MAX_COLLISIONS_TOTAL,
MAINLINE_PROFILES,
collectiveRevenueFloor, collectiveRevenueFloor,
lengthProfile, lengthProfile,
officeProfile,
} from '../engine/content.ts'; } from '../engine/content.ts';
import type { GameEvent } from '../engine/events.ts'; import type { GameEvent } from '../engine/events.ts';
import type { Intent } from '../engine/intents.ts';
import { legalActions } from '../engine/legal.ts'; import { legalActions } from '../engine/legal.ts';
import { createGame } from '../engine/setup.ts'; import { createGame } from '../engine/setup.ts';
import type { Facility, GameConfig, GameState } from '../engine/state.ts'; import type { GameConfig } from '../engine/state.ts';
import { actingPlayer } from '../engine/state.ts'; import { actingPlayer } from '../engine/state.ts';
import { reasonSentence } from '../web/panels.ts'; import { reasonSentence } from '../web/panels.ts';
import { developerBot, lastChoiceReason } from './bot.ts'; import { developerBot, lastChoiceReason } from './bot.ts';
import { carLabel, cuesFor, idleNote, isVisible, narrate } from './narrate.ts'; import { cuesFor, idleNote, isVisible, narrate } from './narrate.ts';
// The view-model lives in its own module so the browser build can import it without dragging in // The view-model lives in its own module so the browser build can import it without dragging in
// this file's Node dependencies. Re-exported because tests and the web app import it from here. // this file's Node dependencies. Re-exported because tests and the web app import it from here.
export type { CellView, DivisionView, FacilityView, Frame, Decision, TrainChip } from './view.ts'; export type { CellView, DivisionView, FacilityView, Frame, Decision, TrainChip } from './view.ts';
+1 -1
View File
@@ -18,7 +18,7 @@
* *
* Run with: * Run with:
* node src/sim/save-replay.ts 400 --top 3 * node src/sim/save-replay.ts 400 --top 3
* node src/sim/save-replay.ts 400 --top 3 trainCapSlack=0 * node src/sim/save-replay.ts 400 --top 3 noValueLays=1
*/ */
import { readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { readdirSync, unlinkSync, writeFileSync } from 'node:fs';
+2 -2
View File
@@ -889,14 +889,14 @@ export function describeDecision(
groups.set(o.type, list); groups.set(o.type, list);
} }
const rejected = [...groups.entries()] const rejected = [...groups.entries()]
.map(([kind, list]) => ({ kind, count: list.length, detail: sampleDetail(s, kind, list) })) .map(([kind, list]) => ({ kind, count: list.length, detail: sampleDetail(s, list) }))
.sort((a, b) => b.count - a.count); .sort((a, b) => b.count - a.count);
return { actor, chose: describeIntent(s, chosen), why, rejected, totalOptions: options.length }; return { actor, chose: describeIntent(s, chosen), why, rejected, totalOptions: options.length };
} }
/** A short, concrete example of what a group of rejected options would have done. */ /** A short, concrete example of what a group of rejected options would have done. */
function sampleDetail(s: GameState, kind: string, list: Intent[]): string { function sampleDetail(s: GameState, list: Intent[]): string {
// Deduplicate by DESCRIPTION. Orientation variants and repeated copies of a card describe // Deduplicate by DESCRIPTION. Orientation variants and repeated copies of a card describe
// identically, so the raw list reads "play Overpass at (0,0)" three times over and hides the // identically, so the raw list reads "play Overpass at (0,0)" three times over and hides the
// actual range of choices — the opposite of what this panel is for. // actual range of choices — the opposite of what this panel is for.
+29 -14
View File
@@ -37,24 +37,24 @@ import { collectStep, newCollector } from '../sim/display-step.ts';
import type { DisplayCollector } from '../sim/display-step.ts'; import type { DisplayCollector } from '../sim/display-step.ts';
// Import from the view module, NOT replay.ts — replay.ts writes files and reads process.argv, // Import from the view module, NOT replay.ts — replay.ts writes files and reads process.argv,
// which would pull node:fs into a browser bundle. // which would pull node:fs into a browser bundle.
import { cardDescription, cardName, currentActorOfState, describeIntent, geometryLabel, simpleCardName, snapshot, trainName, variantLabel } from '../sim/view.ts'; import { cardDescription, cardName, currentActorOfState, describeIntent, simpleCardName, snapshot, trainName, variantLabel } from '../sim/view.ts';
import { import {
DEFAULT_DAYS, DEFAULT_DAYS,
DEFAULT_HOUSE_RULES, DEFAULT_HOUSE_RULES,
DEFAULT_MAX_COLLISIONS_PER_DAY, DEFAULT_MAX_COLLISIONS_PER_DAY,
DEFAULT_MAX_COLLISIONS_TOTAL, DEFAULT_MAX_COLLISIONS_TOTAL,
LEGACY_HOUSE_RULES, LEGACY_HOUSE_RULES,
withSavedOpening, withSavedDeal,
collectiveRevenueFloor, collectiveRevenueFloor,
houseRules, houseRules,
industryProfile, industryProfile,
mainlineProfile, mainlineProfile,
trainProfile, trainProfile,
} from '../engine/content.ts'; } from '../engine/content.ts';
import type { Hand, HouseRuleOverrides, TrackGeometry } from '../engine/content.ts'; import type { CarType, Hand, HouseRuleOverrides, TrackGeometry } from '../engine/content.ts';
import type { Port } from '../engine/track.ts'; import type { Port } from '../engine/track.ts';
import { connectionsFor, joins, neighbour, variantsFor } from '../engine/track.ts'; import { connectionsFor, joins, neighbour, variantsFor } from '../engine/track.ts';
import { areaOf, destinationsFor, selectDestination, trainNeedingCars } from '../engine/apply.ts'; import { acceptsCar, areaOf, destinationsFor, selectDestination, trainNeedingCars } from '../engine/apply.ts';
import type { Frame } from '../sim/view.ts'; import type { Frame } from '../sim/view.ts';
/** /**
@@ -1007,16 +1007,31 @@ function consistNeeds(game: Game, trayId: string): string | null {
const have = (k: 'coach' | 'caboose' | 'freight'): number => const have = (k: 'coach' | 'caboose' | 'freight'): number =>
tray.consist.filter((c) => cat(c.type) === k).length; tray.consist.filter((c) => cat(c.type) === k).length;
/**
* ASKED OF `acceptsCar`, NOT RECOUNTED (v0.8.4). Counting by category alone promised cars the
* engine would then refuse: with the caboose already coupled, nothing may go on behind it
* (§A.3), so "Still needs 2 boxcar" was printed while no yard chip lit and the only offer was
* to send the train out as it stands. One sample car per category settles it the same way
* `advance.ts`'s make-up report does.
*/
const sample: Record<'coach' | 'caboose' | 'freight', CarType> = {
coach: 'coach',
caboose: 'caboose',
freight: p.consist.freightTypes?.[0] ?? 'boxcar',
};
const parts: string[] = []; const parts: string[] = [];
const freight = p.consist.freight - have('freight'); let blocked = false;
const coach = p.consist.coach - have('coach'); const want = (k: 'coach' | 'caboose' | 'freight', label: (n: number) => string): void => {
const caboose = p.consist.caboose - have('caboose'); const n = (k === 'coach' ? p.consist.coach : k === 'caboose' ? p.consist.caboose : p.consist.freight) - have(k);
if (freight > 0) { if (n <= 0) return;
parts.push(`${freight} ${p.consist.freightTypes?.join('/') ?? 'freight'}${p.consist.emptiesOnly ? ' (empties only)' : ''}`); if (acceptsCar(tray, sample[k])) parts.push(label(n));
} else blocked = true;
if (coach > 0) parts.push(`${coach} coach${coach > 1 ? 'es' : ''}`); };
if (caboose > 0) parts.push(`${caboose} caboose`); want('freight', (n) => `${n} ${p.consist.freightTypes?.join('/') ?? 'freight'}${p.consist.emptiesOnly ? ' (empties only)' : ''}`);
return parts.length > 0 ? parts.join(' + ') : null; want('coach', (n) => `${n} coach${n > 1 ? 'es' : ''}`);
want('caboose', (n) => `${n} caboose`);
if (parts.length > 0) return parts.join(' + ');
return blocked ? 'nothing more — the caboose is on, and nothing couples behind it' : null;
} }
/** /**
@@ -1524,7 +1539,7 @@ export function toSave(game: Game): Save {
* in force then — never the current defaults. * in force then — never the current defaults.
*/ */
function configFor(save: Save, config: GameConfig): GameConfig { function configFor(save: Save, config: GameConfig): GameConfig {
return withSavedOpening({ ...config, houseRules: save.rules ?? LEGACY_HOUSE_RULES }); return withSavedDeal({ ...config, houseRules: save.rules ?? LEGACY_HOUSE_RULES });
} }
/** /**
+2 -2
View File
@@ -421,7 +421,7 @@ export function runLobby(handlers: LobbyHandlers, resume?: { token: string; game
// -- seating -------------------------------------------------------------------------------- // -- seating --------------------------------------------------------------------------------
function renderSeating(lobby: Lobby, you: PlayerIndex, token: string): void { function renderSeating(lobby: Lobby, token: string): void {
$('lb-gamecode').textContent = lobby.gameCode; $('lb-gamecode').textContent = lobby.gameCode;
const isHost = lobby.hostToken === token; const isHost = lobby.hostToken === token;
@@ -566,7 +566,7 @@ export function runLobby(handlers: LobbyHandlers, resume?: { token: string; game
handlers.onReady({ token, gameId, seat: push.you, gameCode: push.lobby.gameCode }); handlers.onReady({ token, gameId, seat: push.you, gameCode: push.lobby.gameCode });
return; return;
} }
renderSeating(push.lobby, push.you, token); renderSeating(push.lobby, token);
}; };
/** /**
+15 -2
View File
@@ -149,8 +149,8 @@ function saveSettings(patch: Partial<Settings>): void {
} }
/** /**
* The game, behind the Session boundary — `LocalSession` (solitaire, `?seat=` absent from the URL) * The game, behind the Session boundary — `LocalSession` (solitaire) or `RemoteSession` (a seat
* or `RemoteSession` (`?seat=` present, Phase 2). Typed as the common `Session` surface; every * this browser holds in `localStorage`, or a claim link; `?seat=` is no longer a route). Typed as the common `Session` surface; every
* LocalSession-only touch (undo, local saves, dealing a new game) goes through `isLocal` below rather * LocalSession-only touch (undo, local saves, dealing a new game) goes through `isLocal` below rather
* than assuming, since `session` may now be either. * than assuming, since `session` may now be either.
*/ */
@@ -1497,6 +1497,19 @@ function render(): void {
const f = session.view(); const f = session.view();
const menu = session.menu(); const menu = session.menu();
noteFirstFrame(f, rejoiningRemote); noteFirstFrame(f, rejoiningRemote);
/**
* A COMPETITIVE SAVE WAITS FOR THE END (Jesse's ruling, TODO #117). The file carries the seed,
* which is every rival's hand, so `/api/save` refuses it while the game runs — and the button
* says so here rather than silently doing nothing when clicked.
*/
const saveBtn = document.getElementById('savefile') as HTMLButtonElement | null;
if (saveBtn && !isLocal(session)) {
const locked = f.mode === 'competitive' && f.status !== 'finished';
saveBtn.disabled = locked;
saveBtn.title = locked
? 'In a Competitive game the save file carries the whole deal, so it can be downloaded once the game is over'
: 'Download this game as a save file you can replay or share';
}
// Which squares the selected card or track piece may go on. Highlighting them is what turns the // Which squares the selected card or track piece may go on. Highlighting them is what turns the
// coordinate list into a board: you pick the thing, then click where it goes. // coordinate list into a board: you pick the thing, then click where it goes.
+44 -5
View File
@@ -6,8 +6,8 @@
* *
* - `LocalSession` runs the engine in this browser. Solitaire, exactly as it has always worked, * - `LocalSession` runs the engine in this browser. Solitaire, exactly as it has always worked,
* with no server involved at any point. * with no server involved at any point.
* - `RemoteSession` (not built yet — see `docs/architecture/multiplayer.md` Phase 2) will hold no * - `RemoteSession` (`docs/architecture/multiplayer.md` Phase 2, built) holds no authoritative
* authoritative state at all. It cannot: it has neither the deck order nor the other players' * state at all. It cannot: it has neither the deck order nor the other players'
* hands, and if it did the game would be cheatable. * hands, and if it did the game would be cheatable.
* *
* So this interface is deliberately the SMALLER of the two — everything a remote client could * So this interface is deliberately the SMALLER of the two — everything a remote client could
@@ -282,6 +282,8 @@ type Push = {
scheduled?: number | null; scheduled?: number | null;
announcement?: string | null; announcement?: string | null;
justDrawn?: string | null; justDrawn?: string | null;
/** Where the server's count of this seat's accepted intents stands — connect push only (v0.8.4). */
lastSeq?: number;
}; };
/** /**
@@ -322,7 +324,19 @@ export function createRemoteSession(
let scheduled: number | null = null; let scheduled: number | null = null;
let announcement: string | null = null; let announcement: string | null = null;
let justDrawnCard: string | null = null; let justDrawnCard: string | null = null;
/**
* NUMBERED FROM WHERE THE SERVER SAYS, NOT FROM 1 (v0.8.4).
*
* This started at 1 on every page load, and the server remembers a seat's last accepted number
* for the life of the game and answers a repeat with "already applied" (`protocol.md` §5). So a
* seat that had made one move, reloaded, and clicked again sent `seq: 1` twice: the server said
* ok, did nothing, pushed nothing, and the click looked dead. The connect push now carries the
* server's count and this continues from it — never backwards, in case a submit is in flight
* across a reconnect.
*/
let nextSeq = 1; let nextSeq = 1;
/** One submit in flight at a time — see `submit`. */
let inFlight = false;
const listeners = new Set<() => void>(); const listeners = new Set<() => void>();
const changed = (): void => { const changed = (): void => {
for (const fn of [...listeners]) fn(); for (const fn of [...listeners]) fn();
@@ -355,7 +369,15 @@ export function createRemoteSession(
}); });
}; };
source.onmessage = (ev: MessageEvent<string>) => { source.onmessage = (ev: MessageEvent<string>) => {
const push = JSON.parse(ev.data) as Push; let push: Push;
try {
push = JSON.parse(ev.data) as Push;
} catch {
// A push that is not JSON is dropped rather than thrown out of an event handler nothing
// catches; the next push carries a full delta chain from what this seat was last sent.
return;
}
if (push.lastSeq !== undefined) nextSeq = Math.max(nextSeq, push.lastSeq + 1);
// A presence-only push (no `frame`) carries `menu: null` too, but that is not news about this // A presence-only push (no `frame`) carries `menu: null` too, but that is not news about this
// seat's turn — only a push that actually came from the game (always carries a real `frame`, // seat's turn — only a push that actually came from the game (always carries a real `frame`,
// per `session.ts`'s `Push`) updates the board or the menu. // per `session.ts`'s `Push`) updates the board or the menu.
@@ -402,16 +424,33 @@ export function createRemoteSession(
actor: () => need().actor, actor: () => need().actor,
handPlayable: () => (menu?.hand ?? []).map((h) => h.playNow !== null), handPlayable: () => (menu?.hand ?? []).map((h) => h.playNow !== null),
async submit(intent: Intent): Promise<boolean> { async submit(intent: Intent): Promise<boolean> {
/**
* ONE AT A TIME (v0.8.4). The page redraws the SAME menu the instant a submit is sent — the
* new one only arrives with the push — so a second click before the round trip posted a
* second, fresh `seq` for the same option, and the server, which de-duplicates on `seq`
* alone, applied it again when it was still legal: two cards drawn, two Moves spent, two cars
* coupled. A click that lands while one is in flight is dropped; the push is milliseconds away.
*/
if (inFlight) return false;
inFlight = true;
const seq = nextSeq++; const seq = nextSeq++;
try {
const res = await fetch(`/api/intent?${qs}`, { const res = await fetch(`/api/intent?${qs}`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ seq, intent }), body: JSON.stringify({ seq, intent }),
}); });
const result = (await res.json()) as { ok: boolean; code?: string }; const result = (await res.json()) as { ok?: boolean; code?: string };
// The visible update arrives via the SSE push (broadcast to every seat, including this one), // The visible update arrives via the SSE push (broadcast to every seat, including this one),
// not from this response — this only reports whether the rules accepted it. // not from this response — this only reports whether the rules accepted it.
return result.ok; return result.ok === true;
} catch {
// A network failure or a non-JSON answer used to reject out of a `void`ed promise — an
// unhandled rejection and nothing on screen. False is honest: the move was not confirmed.
return false;
} finally {
inFlight = false;
}
}, },
subscribe(fn: () => void) { subscribe(fn: () => void) {
listeners.add(fn); listeners.add(fn);
+1 -1
View File
@@ -242,6 +242,7 @@ export function createStepQueue(
behind: () => pending.filter((s) => dwell(s) > 0).length, behind: () => pending.filter((s) => dwell(s) > 0).length,
showing: () => last, showing: () => last,
lit: () => litPiles, lit: () => litPiles,
pendingLines: () => pending.reduce((n, s) => n + s.lines.length, 0),
/** /**
* STILL SHOWING SOMETHING, not just still holding something back. * STILL SHOWING SOMETHING, not just still holding something back.
* *
@@ -253,7 +254,6 @@ export function createStepQueue(
* `dueAt` is non-null exactly while the step on screen has time left, so the two together mean * `dueAt` is non-null exactly while the step on screen has time left, so the two together mean
* "there is more to come, or what is up has not had its moment yet". * "there is more to come, or what is up has not had its moment yet".
*/ */
pendingLines: () => pending.reduce((n, s) => n + s.lines.length, 0),
flashing: () => flashedCards, flashing: () => flashedCards,
busy: () => pending.length > 0 || dueAt !== null, busy: () => pending.length > 0 || dueAt !== null,
}; };
+71 -1
View File
@@ -12,7 +12,6 @@ import { applyIntent, areaOf, check, isBeingMadeUp } from '../src/engine/apply.t
import { EXPEDITE_FAULT_PENALTY, HAND_LIMIT, MAX_CONSIST, STAGES_PER_DAY, TOTAL_ROLLING_STOCK } from '../src/engine/content.ts'; import { EXPEDITE_FAULT_PENALTY, HAND_LIMIT, MAX_CONSIST, STAGES_PER_DAY, TOTAL_ROLLING_STOCK } from '../src/engine/content.ts';
import { legalActions } from '../src/engine/legal.ts'; import { legalActions } from '../src/engine/legal.ts';
import { createGame } from '../src/engine/setup.ts'; import { createGame } from '../src/engine/setup.ts';
import { developerBot } from '../src/sim/bot.ts';
import type { CrewTray, DivisionNode, GameConfig, GameState } from '../src/engine/state.ts'; import type { CrewTray, DivisionNode, GameConfig, GameState } from '../src/engine/state.ts';
import { coordKey, railFacingOf } from '../src/engine/state.ts'; import { coordKey, railFacingOf } from '../src/engine/state.ts';
@@ -1704,3 +1703,74 @@ describe('a train sorted to the nose is judged by §8.2, not by where the engine
assert.match(why, /caboose must be at the rear/, `the hold did not say why: ${why}`); assert.match(why, /caboose must be at the rear/, `the hold did not say why: ${why}`);
}); });
}); });
// ---------------------------------------------------------------------------
// v0.8.3 — audit findings (2026-09-29)
// ---------------------------------------------------------------------------
describe('the collision floor at the end of a Day (v0.8.3)', () => {
it('fires on a breach reached in Stage 12, before the Day rolls over', () => {
/**
* `shiftChange` reset `collisionsToday` at the Day rollover and only THEN asked whether the Day
* had breached the limit — so a third wreck in Stage 12 was read as zero, and the one Stage of
* the Day in which the floor could not fire was the last one. The tests above all set `stage`
* to 1, which never crosses the rollover.
*/
const s = game(1, { mode: 'competitive', maxCollisionsPerDay: 2 });
s.collisionsToday = 2;
s.clock.stage = STAGES_PER_DAY;
s.clock.phase = 'shiftChange';
advance(s);
assert.equal(s.status, 'finished', 'a breach in the last Stage of the Day went unpunished');
assert.equal(s.outcome!.result, 'loss');
assert.equal(s.outcome!.reason, 'collisionFloor');
});
});
describe('the Expedite fault is charged once per Mainline Phase (v0.8.3)', () => {
it('does not charge again when the phase resumes after a clearance ruling', () => {
/**
* The Q3 fault loop ran unguarded at the top of `mainlinePhase`, and the phase is re-entered
* from the top after every clearance, Yard Office or Red Flag question — so an Expedited train
* left on a siding was fined once per QUESTION rather than once per Phase.
*/
const s = game(7, { days: 5 });
for (const n of s.division.nodes) if (n.kind === 'mainline') n.card = 'plains';
const area = areaOf(s, 0);
// The Expedited train, parked off the station: one fault is due.
s.trays.set('expedited', {
id: 'expedited', trainNumber: 6, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', facing: 'e',
position: { at: 'grid', seat: 0, coord: { row: area.officeCoord.row, col: area.officeCoord.col + 1 } }, movesUsed: 0,
});
// A departing train that will put a clearance question to the Superintendent mid-phase.
s.trays.set('leaving', {
id: 'leaving', trainNumber: 12, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', facing: 'e', position: { at: 'grid', seat: 0, coord: area.officeCoord }, movesUsed: 0,
});
area.adOccupancy.push('leaving');
const office = s.division.nodes.findIndex((n) => n.kind === 'office' && n.seat === 0);
const ahead = s.division.nodes.findIndex((n, i) => i > office && n.kind === 'mainline');
const node = s.division.nodes[ahead];
assert.equal(node?.kind, 'mainline');
s.trays.set('ahead', {
id: 'ahead', trainNumber: 9, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', facing: 'e', position: { at: 'mainline', index: ahead }, movesUsed: 0,
});
if (node?.kind === 'mainline') node.transits.push({ tray: 'ahead', stagesRemaining: 2, stagesTotal: 2, direction: 'east' });
s.clock.phase = 'mainline';
const before = s.players[0]!.revenue;
const first = advance(s);
assert.ok(first.needsInput, 'no clearance question was put, so the phase never resumed');
assert.equal(first.events.filter((e) => e.type === 'expediteFault').length, 1);
// Hold the departing train, so the only Revenue that can move is the fault's.
const ruling = legalActions(s, s.clock.superintendent).find((i) => i.type === 'mainline.clearance' && !i.allow);
assert.ok(ruling, 'no clearance ruling on offer');
assert.ok(applyIntent(s, s.clock.superintendent, ruling).ok);
const resumed = advance(s);
assert.ok(!resumed.events.some((e) => e.type === 'expediteFault'), 'the fault was charged a second time');
assert.equal(s.players[0]!.revenue, before - EXPEDITE_FAULT_PENALTY, 'more than one fault was charged');
});
});
+110 -2
View File
@@ -14,7 +14,7 @@ import { legalActions } from '../src/engine/legal.ts';
import { createGame } from '../src/engine/setup.ts'; import { createGame } from '../src/engine/setup.ts';
import type { CrewTray, GameConfig, GameState, GridCoord, TrackCard } from '../src/engine/state.ts'; import type { CrewTray, GameConfig, GameState, GridCoord, TrackCard } from '../src/engine/state.ts';
import { carsOn, coordKey, railFacingOf, spaceOn, turnOf } from '../src/engine/state.ts'; import { carsOn, coordKey, railFacingOf, spaceOn, turnOf } from '../src/engine/state.ts';
import { cardDescription, snapshot } from '../src/sim/view.ts'; import { snapshot } from '../src/sim/view.ts';
const config: GameConfig = { const config: GameConfig = {
mode: 'solitaire', mode: 'solitaire',
@@ -1243,7 +1243,6 @@ describe('a Modifier only goes beside a host that can use it (regression)', () =
// REPORTED from playtesting: two Ice Houses in one district. Industries have been barred from // REPORTED from playtesting: two Ice Houses in one district. Industries have been barred from
// doubling up since Q4, but a Modifier is a different card kind and had no such check at all. // doubling up since Q4, but a Modifier is a different card kind and had no such check at all.
const s = game(); const s = game();
const area = areaOf(s, 0);
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' }); applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const copies = [...s.cards.entries()] const copies = [...s.cards.entries()]
@@ -2480,3 +2479,112 @@ describe('backing up over a cut to something beyond it takes both (v0.4.9d repor
empty(s, at(0, 1), at(0, 0)); empty(s, at(0, 1), at(0, 0));
}); });
}); });
// ---------------------------------------------------------------------------
// v0.8.3 — audit findings (2026-09-29)
// ---------------------------------------------------------------------------
describe('a Department draw that empties the Home Office deck (v0.8.3)', () => {
/**
* THE DRAWN CARD WAS DUPLICATED AND THE REFILL CARD DESTROYED.
*
* `draw.fromDepartment` queued `departmentRefilled` and then asked `reshuffleIfDepleted` to sweep
* the Departments — from the state BEFORE either event had been reduced. So the sweep collected
* the card being drawn (still on its pile) and missed the refill card (still on the deck), and
* the reducers then dealt the drawn card into the new deck while the refill card, moved onto a
* pile the reshuffle immediately wiped, left the game. The Home Office path was covered by the
* tests above; this path was not.
*/
it('neither duplicates the drawn card nor loses the refill card', () => {
const s = game();
const all = [...s.decks.homeOffice];
s.decks.salvageYard = all.slice(0, 40);
s.decks.homeOffice = all.slice(40, 41); // exactly one card left: the refill card
const refill = s.decks.homeOffice[0]!;
const drawn = s.decks.departments[0]![s.decks.departments[0]!.length - 1]!;
s.decks.departments[0] = [drawn]; // a single card, so taking it empties the pile
const everywhere = (): string[] => [
...s.decks.homeOffice,
...s.decks.departments.flat(),
...s.decks.salvageYard,
...[...s.decks.hands.values()].flat(),
];
const before = everywhere().length;
applyIntent(s, 0, { type: 'localOps.choose', option: 'draw' });
const r = applyIntent(s, 0, { type: 'draw.fromDepartment', slot: 0 });
assert.ok(r.ok);
assert.ok(r.events.some((e) => e.type === 'deckReshuffled'), 'the deck ran out and was not reshuffled');
const after = everywhere();
assert.equal(after.length, before, 'the reshuffle created or destroyed cards');
assert.equal(new Set(after).size, after.length, 'a card ended up in two places');
assert.ok(s.decks.hands.get(0)!.includes(drawn), 'the drawn card is not in hand');
assert.equal(after.filter((id) => id === drawn).length, 1, 'the drawn card was dealt back into the deck too');
assert.equal(after.filter((id) => id === refill).length, 1, 'the refill card left the game');
assert.ok(s.decks.departments.every((p) => p.length === 1), 'the Departments were not re-dealt one deep');
});
});
describe('unjamming the box the player named (v0.8.3)', () => {
/**
* `facilityUnjammed` cleared the FIRST load on MEN | AT | WORK, whatever index the intent named,
* because the event never carried the index — the same shape as the "westmost car" fault
* `unloadBegan` once had. With one load on the track it could not be seen.
*/
it('clears the named MEN | AT | WORK load, not the first one', () => {
const s = game();
const area = areaOf(s, 0);
area.grid.set('-1,0', {
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true, standing: [], standingWest: 0, modifiers: [], enhancements: [],
facility: {
kind: 'freight', subtype: 'mineTipple',
allows: { outbound: true, inbound: true },
outboundBox: [], inboundBox: [], capacity: { outbound: 1, inbound: 1 },
// An inbound tank load on MEN, a stranded outbound hopper on WORK.
menAtWork: [{ type: 'tank', dir: 'in' }, null, { type: 'hopper', dir: 'out' }],
industryTrack: { cars: [] },
laborers: 1, porters: 0, usedThisStage: { laborers: 0, porters: 0 },
},
} as never);
s.clock.phase = 'localOps';
s.clock.currentActor = 0;
turnOf(s, 0).option = 'freightAgent';
const yardBefore = s.yards.classificationYard.length;
const r = applyIntent(s, 0, { type: 'freightAgent.unjam', at: { row: -1, col: 0 }, from: 'menAtWork', index: 2 });
assert.ok(r.ok, 'the jam could not be cleared');
const f = area.grid.get('-1,0')!.facility as { menAtWork: ({ type: string } | null)[] };
assert.ok(f.menAtWork[0], 'the tank load on MEN was cleared instead of the hopper on WORK');
assert.equal(f.menAtWork[2], null, 'the hopper on WORK is still there');
const returned = s.yards.classificationYard[yardBefore];
assert.equal(returned?.type, 'hopper', `a ${returned?.type} went to the Classification Yard, not the hopper`);
});
it('clears the named car in a green or red box, not the first of its type', () => {
const s = game();
const area = areaOf(s, 0);
area.grid.set('-1,0', {
geometry: { kind: 'facility', facility: 'mineTipple' },
baseOperationalRail: true, standing: [], standingWest: 0, modifiers: [], enhancements: [],
facility: {
kind: 'freight', subtype: 'mineTipple',
allows: { outbound: true, inbound: false },
outboundBox: [{ type: 'hopper', loaded: true, origin: 1 }, { type: 'hopper', loaded: true, origin: 2 }],
inboundBox: [], capacity: { outbound: 2, inbound: 0 },
menAtWork: [null, null, null],
industryTrack: { cars: [] },
laborers: 1, porters: 0, usedThisStage: { laborers: 0, porters: 0 },
},
} as never);
s.clock.phase = 'localOps';
s.clock.currentActor = 0;
turnOf(s, 0).option = 'freightAgent';
const r = applyIntent(s, 0, { type: 'freightAgent.unjam', at: { row: -1, col: 0 }, from: 'outbound', index: 1 });
assert.ok(r.ok);
const f = area.grid.get('-1,0')!.facility!;
assert.deepEqual(f.outboundBox.map((c) => c.origin), [1], 'the wrong car left the box');
});
});
+57
View File
@@ -941,3 +941,60 @@ describe('defensive enhancements', () => {
assert.equal(hasDistrictEnhancement(areaOf(s, 0), 'waterColumn'), false); assert.equal(hasDistrictEnhancement(areaOf(s, 0), 'waterColumn'), false);
}); });
}); });
// ---------------------------------------------------------------------------
// v0.8.3 — audit findings (2026-09-29)
// ---------------------------------------------------------------------------
describe('a train held at the Limits is released when a track frees (v0.8.3)', () => {
it('takes a free A/D track at the end of the Mainline Phase without waiting for another arrival', () => {
/**
* The only release was inside `arriveAtOffice` for a DIFFERENT train — so an Office that
* emptied by departures alone kept the held train at its Limits for the rest of the game,
* invisible: no transit, not in `adOccupancy`, not counted by the clearance check.
*/
const s = game();
const area = areaOf(s, 0);
const card = straight();
card.enhancements.push('interlocking');
addCard(s, at(0, 2), card);
s.trays.set('waiting', {
id: 'waiting', trainNumber: 8, trainIsExtra: false, engineAt: 0,
consist: [], direction: 'east', position: { at: 'mainline', index: 1 }, movesUsed: 0,
} as never);
area.heldAtLimits = ['waiting'];
area.adOccupancy = []; // the Office cleared, and nothing is arriving
s.timetable = s.timetable.map(() => null);
s.clock.phase = 'mainline';
const r = advance(s);
assert.ok(area.adOccupancy.includes('waiting'), 'the held train is still at the Limits with the Office empty');
assert.deepEqual(area.heldAtLimits, []);
assert.deepEqual(s.trays.get('waiting')!.position, { at: 'grid', seat: 0, coord: area.officeCoord });
const released = r.events.find((e) => e.type === 'trainReleasedFromLimits');
assert.ok(released, 'the release is silent');
const line = narrate(released as never, { playerName: () => 'A' });
assert.match(line.text, /RELEASED from the Limits/, line.text);
});
it('still waits while the Office is full', () => {
const s = game();
const area = areaOf(s, 0);
s.trays.set('waiting', {
id: 'waiting', trainNumber: 8, trainIsExtra: false, engineAt: 0,
consist: [], direction: 'east', position: { at: 'mainline', index: 1 }, movesUsed: 0,
} as never);
area.heldAtLimits = ['waiting'];
area.adOccupancy = ['blocker'];
s.trays.set('blocker', {
id: 'blocker', trainNumber: null, trainIsExtra: false, engineAt: 0,
consist: [], direction: 'east', position: { at: 'grid', seat: 0, coord: area.officeCoord }, movesUsed: 0,
} as never);
s.timetable = s.timetable.map(() => null);
s.clock.phase = 'mainline';
advance(s);
assert.deepEqual(area.heldAtLimits, ['waiting']);
assert.ok(!area.adOccupancy.includes('waiting'));
});
});
+1 -1
View File
@@ -231,7 +231,7 @@ describe('the game conserves Rolling Stock', () => {
for (let t = 0; t < 50_000; t++) { for (let t = 0; t < 50_000; t++) {
const before = census(s); const before = census(s);
const pumped = pump(s); pump(s);
/** /**
* A COLLISION DESTROYS NO CAR, and this used to assume it destroyed all of them. * A COLLISION DESTROYS NO CAR, and this used to assume it destroyed all of them.
* *
+15
View File
@@ -110,4 +110,19 @@ describe('the documentation renderer', () => {
assert.ok(!/BEGIN CARDS/.test(out), `${name}.md leaked a build marker onto the page`); assert.ok(!/BEGIN CARDS/.test(out), `${name}.md leaked a build marker onto the page`);
} }
}); });
it('nests a more-indented bullet as a list inside its item (v0.8.4)', () => {
/**
* The code said "nesting is rendered by recursion" and appended the nested bullet to the parent
* as text, so the published home-deck page read "…knows. - ABS Signals is the exception…" with
* a literal dash mid-sentence.
*/
const out = html(['- parent', ' continues here.', ' - child one', ' wraps too', ' - child two', '- second'].join('\n'));
assert.equal(
out.trim(),
'<ul><li>parent continues here.<ul><li>child one wraps too</li><li>child two</li></ul></li><li>second</li></ul>',
);
assert.doesNotMatch(html(readFileSync(join(import.meta.dirname, '..', 'docs', 'home-deck.md'), 'utf8')), /\. - <strong>/);
});
}); });
+73 -2
View File
@@ -11,12 +11,12 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { advance, pump } from '../src/engine/advance.ts'; import { advance, pump } from '../src/engine/advance.ts';
import { applyIntent, areaAtSeat, areaOf, check } from '../src/engine/apply.ts'; import { applyIntent, areaAtSeat, areaOf, check, occupancyFor } from '../src/engine/apply.ts';
import { STAGES_PER_DAY, STAGES_PER_SHIFT, crewTrayCount } from '../src/engine/content.ts'; import { STAGES_PER_DAY, STAGES_PER_SHIFT, crewTrayCount } from '../src/engine/content.ts';
import { createGame } from '../src/engine/setup.ts'; import { createGame } from '../src/engine/setup.ts';
import { legalActions } from '../src/engine/legal.ts'; import { legalActions } from '../src/engine/legal.ts';
import type { GameConfig, GameState, PlayerIndex } from '../src/engine/state.ts'; import type { GameConfig, GameState, PlayerIndex } from '../src/engine/state.ts';
import { coordKey, playerAtSeat, playerLeftOf, seatOf, subdivisions } from '../src/engine/state.ts'; import { coordKey, playerAtSeat, playerLeftOf, seatOf, subdivisions, turnOf } from '../src/engine/state.ts';
import { developerBot, playGame } from '../src/sim/bot.ts'; import { developerBot, playGame } from '../src/sim/bot.ts';
import { snapshot } from '../src/sim/view.ts'; import { snapshot } from '../src/sim/view.ts';
import { divisionSvg } from '../src/sim/board-svg.ts'; import { divisionSvg } from '../src/sim/board-svg.ts';
@@ -979,3 +979,74 @@ describe('Employee Rotation (Appendix B)', () => {
for (const name of ['Alice', 'Bob', 'Carol']) assert.match(line, new RegExp(name)); for (const name of ['Alice', 'Bob', 'Carol']) assert.match(line, new RegExp(name));
}); });
}); });
// ---------------------------------------------------------------------------
// v0.8.3 — audit findings (2026-09-29): a player's switching stays in their own district
// ---------------------------------------------------------------------------
describe("switching is confined to the actor's own district (v0.8.3)", () => {
/**
* `check` resolved the tray with no seat test at all: the legal-move GENERATOR filtered trays by
* seat, `check` did not, and the server validates with `check` alone. Every district opens on the
* same coordinates, so a destination legal for a tray of your own at (0,0) was "legal" for a
* rival's tray at THEIR (0,0) — and `trayMoved` then charged the Moves to the rival.
*/
const placeOwn = (s: GameState, owner: PlayerIndex, id: string): void => {
const area = areaOf(s, owner);
s.trays.set(id, {
id, trainNumber: null, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', position: { at: 'grid', seat: seatOf(s, owner), coord: area.officeCoord }, movesUsed: 0,
});
};
const switching = (s: GameState, player: PlayerIndex): void => {
s.clock.phase = 'localOps';
s.clock.currentActor = player;
applyIntent(s, player, { type: 'localOps.choose', option: 'switch' });
assert.equal(turnOf(s, player).option, 'switch', 'could not choose Switch');
};
it("refuses a switch.move on a rival's tray that would have been legal on your own", () => {
const s = game(2);
// Find a move the actor could make with a tray of THEIR OWN standing at the Office.
placeOwn(s, 0, 'mine');
switching(s, 0);
const own = legalActions(s, 0).find((i) => i.type === 'switch.move' && i.trayId === 'mine');
assert.ok(own && own.type === 'switch.move', 'no switching move to test with');
s.trays.delete('mine');
// Now the same move named against seat 1's tray, standing at seat 1's Office.
placeOwn(s, 1, 'theirs');
const movesBefore = turnOf(s, 0).movesRemaining;
const theirMovesBefore = turnOf(s, 1).movesRemaining;
const code = check(s, 0, { ...own, trayId: 'theirs' });
assert.equal(code, 'NO_SUCH_TRAY', `a rival's tray was accepted (${code ?? 'null'})`);
assert.ok(!applyIntent(s, 0, { ...own, trayId: 'theirs' }).ok, 'the move was applied');
assert.equal(turnOf(s, 0).movesRemaining, movesBefore);
assert.equal(turnOf(s, 1).movesRemaining, theirMovesBefore, "the rival's Moves were charged");
assert.deepEqual(s.trays.get('theirs')!.position, { at: 'grid', seat: seatOf(s, 1), coord: areaOf(s, 1).officeCoord });
});
it("refuses dropCars and sortConsist on a rival's tray too", () => {
const s = game(2);
placeOwn(s, 0, 'mine'); // Switch is only on offer with a tray of your own to switch
placeOwn(s, 1, 'theirs');
s.trays.get('theirs')!.consist.push({ type: 'boxcar', loaded: false });
switching(s, 0);
assert.equal(check(s, 0, { type: 'switch.dropCars', trayId: 'theirs', count: 1 }), 'NO_SUCH_TRAY');
assert.equal(check(s, 0, { type: 'switch.sortConsist', trayId: 'theirs', order: [0] }), 'NO_SUCH_TRAY');
});
it("does not see a rival's crew as standing in your district", () => {
/**
* `occupancyFor().trayAt` matched on coordinates alone, so a crew at seat 0's (0,2) blocked
* seat 1's (0,2) as "another train standing here". Invisible in solitaire.
*/
const s = game(2);
const spot = { row: areaOf(s, 0).officeCoord.row, col: areaOf(s, 0).officeCoord.col + 2 };
s.trays.set('crew0', {
id: 'crew0', trainNumber: null, trainIsExtra: false, engineAt: 0, consist: [],
direction: 'east', position: { at: 'grid', seat: seatOf(s, 0), coord: spot }, movesUsed: 0,
});
assert.equal(occupancyFor(s, 0, 'other').trayAt(spot), 'crew0', 'the owner cannot see their own crew');
assert.equal(occupancyFor(s, 1, 'other').trayAt(spot), null, "a rival's crew is standing in the wrong district");
});
});
+81
View File
@@ -0,0 +1,81 @@
/**
* The browser's half of the multiplayer transport, driven with a fake `EventSource` and `fetch`.
* `createRemoteSession` is pure otherwise — no DOM — so it runs here as it does in the page.
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { createRemoteSession } from '../src/web/session.ts';
type Fake = { onmessage: ((ev: { data: string }) => void) | null; emit(data: unknown): void; close(): void };
function fakeTransport(): { source: () => Fake; bodies: () => { seq: number }[]; fail: (on: boolean) => void } {
let last: Fake | null = null;
const bodies: { seq: number }[] = [];
let failing = false;
const g = globalThis as unknown as Record<string, unknown>;
g['EventSource'] = class {
onmessage: ((ev: { data: string }) => void) | null = null;
onerror: (() => void) | null = null;
constructor() {
last = this;
}
emit(data: unknown): void {
this.onmessage?.({ data: JSON.stringify(data) });
}
close(): void {}
};
g['fetch'] = async (_url: string, init?: { body?: string }) => {
if (init?.body) bodies.push(JSON.parse(init.body) as { seq: number });
await new Promise((r) => setTimeout(r, 5));
if (failing) throw new Error('network down');
return { ok: true, status: 200, json: async () => ({ ok: true }) };
};
return { source: () => last!, bodies: () => bodies, fail: (on) => (failing = on) };
}
const connectPush = (lastSeq: number): unknown => ({ frame: null, menu: null, lines: [], lastSeq });
describe('the remote session (v0.8.4)', () => {
it('continues the intent count from where the server says, not from 1', async () => {
const t = fakeTransport();
const s = createRemoteSession('tok', 0);
t.source().emit(connectPush(7));
await s.submit({ type: 'draw.end' });
assert.deepEqual(t.bodies().map((b) => b.seq), [8], 'the first intent after a reload re-used a number the server had already applied');
// A later reconnect never moves the count backwards.
t.source().emit(connectPush(3));
await s.submit({ type: 'draw.end' });
assert.deepEqual(t.bodies().map((b) => b.seq), [8, 9]);
});
it('drops a second submit while the first is still in flight', async () => {
const t = fakeTransport();
const s = createRemoteSession('tok', 0);
t.source().emit(connectPush(0));
const [a, b] = await Promise.all([s.submit({ type: 'draw.end' }), s.submit({ type: 'draw.end' })]);
assert.equal(a, true);
assert.equal(b, false, 'a double-click posted twice');
assert.equal(t.bodies().length, 1, 'two intents went over the wire for one click');
// And the next one, after the round trip, goes through as normal.
assert.equal(await s.submit({ type: 'draw.end' }), true);
assert.equal(t.bodies().length, 2);
});
it('answers false, not an unhandled rejection, when the network fails', async () => {
const t = fakeTransport();
const s = createRemoteSession('tok', 0);
t.source().emit(connectPush(0));
t.fail(true);
assert.equal(await s.submit({ type: 'draw.end' }), false);
t.fail(false);
assert.equal(await s.submit({ type: 'draw.end' }), true, 'the session did not recover after a failed submit');
});
it('drops a push that is not JSON instead of throwing out of the handler', () => {
const t = fakeTransport();
createRemoteSession('tok', 0);
assert.doesNotThrow(() => t.source().onmessage?.({ data: '{not json' }));
});
});
+1 -1
View File
@@ -68,7 +68,7 @@ const SAMPLES: GameEvent[] = [
{ type: 'freightAgentIdled', player: 0 }, { type: 'freightAgentIdled', player: 0 },
{ type: 'trainReleasedFromLimits', trainNumber: 8, office: 'Whistle Post', owner: 0, freedBy: 14 }, { type: 'trainReleasedFromLimits', trainNumber: 8, office: 'Whistle Post', owner: 0, freedBy: 14 },
{ type: 'inboundCleared', player: 0, at: { row: 1, col: 0 }, stock: { type: 'hopper', loaded: true } }, { type: 'inboundCleared', player: 0, at: { row: 1, col: 0 }, stock: { type: 'hopper', loaded: true } },
{ type: 'facilityUnjammed', player: 0, at: { row: 1, col: 0 }, from: 'menAtWork', stock: { type: 'hopper', loaded: true } }, { type: 'facilityUnjammed', player: 0, at: { row: 1, col: 0 }, from: 'menAtWork', index: 0, stock: { type: 'hopper', loaded: true } },
{ type: 'trainScheduled', player: 0, trainNumber: 4, roll: 7, slot: 6, rngState: 1 }, { type: 'trainScheduled', player: 0, trainNumber: 4, roll: 7, slot: 6, rngState: 1 },
{ type: 'carPlacedOnTrain', player: 0, trayId: 't0', stock: { type: 'coach', loaded: false }, trainNumber: 10, isExtra: false }, { type: 'carPlacedOnTrain', player: 0, trayId: 't0', stock: { type: 'coach', loaded: false }, trainNumber: 10, isExtra: false },
{ type: 'carPassed', player: 0, trayId: 't0', trainNumber: 10, isExtra: false }, { type: 'carPassed', player: 0, trayId: 't0', trainNumber: 10, isExtra: false },
+190
View File
@@ -0,0 +1,190 @@
/**
* The HTTP layer, driven end to end over a real socket. `startServer` binds port 0 on a temp data
* directory; nothing here reads the built site, so `distDir` is a directory with nothing in it.
*
* Added in v0.8.4, when four faults in `http.ts` turned out to be uncovered because no test had ever
* stood the server up: a leaver's token surviving the leave, an unbounded body, a torn save under
* concurrent moves, and a crash on an error after the SSE head was sent.
*/
import { describe, it, after, before } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Server } from 'node:http';
import type { GameConfig } from '../../src/engine/state.ts';
import { startServer } from '../../src/server/http.ts';
const SECRET = 'test-secret';
const config: GameConfig = {
mode: 'competitive',
days: 5,
minCombinedRevenue: 0,
maxCollisionsPerDay: 0,
maxCollisionsTotal: 0,
pvpCardsAllowed: false,
houseRules: { startingOffice: 'whistlePost' },
optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false },
};
let server: Server;
let base = '';
let dataDir = '';
before(async () => {
dataDir = await mkdtemp(join(tmpdir(), 'station-master-http-'));
server = startServer({
port: 0,
bindAddress: '127.0.0.1',
joinSecret: SECRET,
distDir: dataDir,
dataDir,
engineVersion: 'test',
initialGames: new Map(),
initialLobbies: new Map(),
initialSessions: new Map(),
});
await new Promise<void>((resolve) => server.once('listening', resolve));
const addr = server.address();
if (!addr || typeof addr === 'string') throw new Error('no port');
base = `http://127.0.0.1:${addr.port}`;
});
after(async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
// A write queued behind the last move may still be landing; retry rather than race it.
await rm(dataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
});
const post = async (path: string, body: unknown): Promise<{ status: number; json: Record<string, unknown> }> => {
const res = await fetch(base + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
return { status: res.status, json: (await res.json()) as Record<string, unknown> };
};
const get = async (path: string): Promise<number> => (await fetch(base + path)).status;
/** The first SSE message on a stream, then the stream is dropped. */
async function firstPush(path: string): Promise<Record<string, unknown>> {
const res = await fetch(base + path);
assert.equal(res.status, 200, `${path} answered ${res.status}`);
const reader = res.body!.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { value, done } = await reader.read();
if (done) throw new Error('stream ended before a push');
buffer += decoder.decode(value, { stream: true });
const m = /data: (.*)\n\n/.exec(buffer);
if (m) {
await reader.cancel();
return JSON.parse(m[1]!) as Record<string, unknown>;
}
}
}
type Seat = { token: string; player: number; gameId: string; gameCode: string };
async function table(): Promise<{ host: Seat; guest: Seat }> {
const created = await post('/api/lobby/create', { secret: SECRET, config, displayName: 'Host', players: 2 });
assert.equal(created.status, 200, JSON.stringify(created.json));
const host = created.json as unknown as Seat;
const joined = await post('/api/lobby/join', { secret: SECRET, gameCode: host.gameCode, displayName: 'Guest' });
assert.equal(joined.status, 200, JSON.stringify(joined.json));
return { host, guest: joined.json as unknown as Seat };
}
describe('the HTTP layer (v0.8.4)', () => {
it('revokes the token of a player who leaves, so it cannot play the seat the next arrival takes', async () => {
const { host, guest } = await table();
const left = await post('/api/lobby/leave', { token: guest.token });
assert.equal(left.status, 200);
// The leaver's token is dead at once — for the lobby and for the game that follows.
assert.equal(await get(`/api/lobby/stream?token=${guest.token}`), 404, 'a leaver can still watch the lobby');
const again = await post('/api/lobby/join', { secret: SECRET, gameCode: host.gameCode, displayName: 'Newcomer' });
assert.equal(again.status, 200);
assert.equal(again.json['player'], guest.player, 'the vacated chair was not the one re-offered');
const started = await post('/api/lobby/start', { token: host.token });
assert.equal(started.status, 200, JSON.stringify(started.json));
assert.equal(await get(`/api/session?token=${guest.token}`), 404, 'the leaver still holds a seat in the running game');
assert.equal(await get(`/api/stream?token=${guest.token}`), 404, "the leaver can read the newcomer's stream");
const move = await post(`/api/intent?token=${guest.token}`, { seq: 1, intent: { type: 'localOps.choose', option: 'draw' } });
assert.equal(move.status, 404, 'the leaver can move for the newcomer');
// And the newcomer's own token works.
assert.equal(await get(`/api/session?token=${again.json['token'] as string}`), 200);
// On disk too, so a restart does not hand the seat back.
const onDisk = JSON.parse(await readFile(join(dataDir, 'games', host.gameId, 'sessions.json'), 'utf8')) as { token: string }[];
assert.ok(!onDisk.some((s) => s.token === guest.token), 'the revoked token is still in sessions.json');
});
it('lets the host remove a player, revoking that token the same way', async () => {
const { host, guest } = await table();
const removed = await post('/api/lobby/leave', { token: host.token, seat: guest.player });
assert.equal(removed.status, 200, JSON.stringify(removed.json));
assert.equal(await get(`/api/lobby/stream?token=${guest.token}`), 404);
assert.equal(await get(`/api/lobby/stream?token=${host.token}`), 200, 'the host lost their own seat');
});
it('refuses an oversized body before reading it, and a malformed one with 400', async () => {
const big = await fetch(base + '/api/claim', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: 'x'.repeat(200_000) }),
});
assert.equal(big.status, 413);
const bad = await fetch(base + '/api/lobby/join', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{not json' });
assert.equal(bad.status, 400);
const notObject = await fetch(base + '/api/lobby/join', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: 'null' });
assert.equal(notObject.status, 400);
});
it('tells a connecting seat where its intent count stands', async () => {
const { host, guest } = await table();
assert.equal((await post('/api/lobby/start', { token: host.token })).status, 200);
const hostPush = await firstPush(`/api/stream?token=${host.token}`);
const actor = hostPush['menu'] !== null ? host : guest;
assert.equal(hostPush['lastSeq'], 0);
const move = await post(`/api/intent?token=${actor.token}`, { seq: 1, intent: { type: 'localOps.choose', option: 'draw' } });
assert.deepEqual(move.json, { ok: true });
const reconnect = await firstPush(`/api/stream?token=${actor.token}`);
assert.equal(reconnect['lastSeq'], 1, 'the reconnect push does not carry the count');
});
it('hands a Competitive seat its save only once the game is over, and a Co-op seat at any time', async () => {
// Jesse's ruling on TODO #117: the seed in a save is every rival's hand, so a Competitive
// download waits for the end; a co-operative table has nothing to hide from itself.
const { host } = await table();
assert.equal((await post('/api/lobby/start', { token: host.token })).status, 200);
const refused = await fetch(base + `/api/save?token=${host.token}`);
assert.equal(refused.status, 403, 'a running Competitive game handed out its seed');
assert.deepEqual(await refused.json(), { error: 'SAVE_AFTER_FINISH' });
const coop = await post('/api/lobby/create', { secret: SECRET, config: { ...config, mode: 'coop' }, displayName: 'Host', players: 2 });
const coopHost = coop.json as unknown as Seat;
assert.equal((await post('/api/lobby/join', { secret: SECRET, gameCode: coopHost.gameCode, displayName: 'Guest' })).status, 200);
assert.equal((await post('/api/lobby/start', { token: coopHost.token })).status, 200);
const allowed = await fetch(base + `/api/save?token=${coopHost.token}`);
assert.equal(allowed.status, 200, 'a Co-op seat could not download its save');
const body = (await allowed.json()) as { save: { seed: number } };
assert.equal(typeof body.save.seed, 'number');
});
it('applies a burst of concurrent moves one at a time and leaves the save readable', async () => {
const { host, guest } = await table();
assert.equal((await post('/api/lobby/start', { token: host.token })).status, 200);
const hostPush = await firstPush(`/api/stream?token=${host.token}`);
const actor = hostPush['menu'] !== null ? host : guest;
// Three moves that are legal only in this order, fired together.
const intents = [
{ type: 'localOps.choose', option: 'draw' },
{ type: 'draw.fromHomeOffice' },
{ type: 'draw.end' },
];
const results = await Promise.all(intents.map((intent, i) => post(`/api/intent?token=${actor.token}`, { seq: i + 1, intent })));
assert.ok(results.every((r) => r.status === 200), 'a concurrent move was answered with an error');
const save = JSON.parse(await readFile(join(dataDir, 'games', host.gameId, 'game.json'), 'utf8')) as { history: unknown[] };
assert.ok(save.history.length >= 1, 'no move reached the save');
assert.equal(save.history.length, results.filter((r) => r.json['ok'] === true).length, 'the save and the answers disagree');
});
});
+1 -1
View File
@@ -242,7 +242,7 @@ describe('playerCountAllowed', () => {
describe('game codes', () => { describe('game codes', () => {
it('skips codes the caller marks taken', () => { it('skips codes the caller marks taken', () => {
let calls = 0; let calls = 0;
const code = freshGameCode((c) => { const code = freshGameCode(() => {
calls++; calls++;
return calls < 3; // taken twice, free on the third return calls < 3; // taken twice, free on the third
}); });
+55 -1
View File
@@ -6,7 +6,8 @@ import { join } from 'node:path';
import type { GameConfig } from '../../src/engine/state.ts'; import type { GameConfig } from '../../src/engine/state.ts';
import type { SavedGame } from '../../src/server/session.ts'; import type { SavedGame } from '../../src/server/session.ts';
import { appendTiming, loadGame, writeGame } from '../../src/server/persistence.ts'; import { appendTiming, loadGame, readIndex, upsertIndexEntry, writeGame } from '../../src/server/persistence.ts';
import { writeFile } from 'node:fs/promises';
const config: GameConfig = { const config: GameConfig = {
mode: 'competitive', mode: 'competitive',
@@ -101,4 +102,57 @@ describe('game persistence (Phase 3)', () => {
const timings = JSON.parse(text) as unknown[]; const timings = JSON.parse(text) as unknown[];
assert.equal(timings.length, 2); assert.equal(timings.length, 2);
})); }));
// -- v0.8.4: concurrent writers ---------------------------------------------------------------
it('two hundred concurrent writes to one save leave it valid and never throw (v0.8.4)', () =>
withTempDir(async (dir) => {
/**
* One fixed `.tmp` per path, and no queue: measured at 200 rounds of two concurrent writes,
* every round lost one to `rename` ENOENT and six left the file as invalid JSON. Boot then
* died on it. Unique temp names and a per-path queue are the fix; this is the measurement.
*/
const writes: Promise<void>[] = [];
for (let i = 0; i < 200; i++) {
const grown: SavedGame = { ...saved, history: Array.from({ length: i + 1 }, () => ({ type: 'draw.end' })) };
writes.push(writeGame(dir, grown, '1.2.3'));
}
await Promise.all(writes);
const result = await loadGame(dir);
assert.equal(result.found, true, 'the save is unreadable after concurrent writes');
if (result.found) assert.equal(result.saved.history.length, 200, 'the last write did not win');
await assert.rejects(() => readFile(join(dir, 'game.json.tmp')));
}));
it('two concurrent index upserts both land (v0.8.4)', () =>
withTempDir(async (dir) => {
await Promise.all([
upsertIndexEntry(dir, { gameId: 'a', gameCode: 'AAA-1', status: 'active' }),
upsertIndexEntry(dir, { gameId: 'b', gameCode: 'BBB-2', status: 'lobby' }),
]);
const rows = await readIndex(dir);
assert.deepEqual(rows.map((r) => r.gameId).sort(), ['a', 'b'], 'a concurrent upsert lost a row');
}));
it('two concurrent timing appends both land (v0.8.4)', () =>
withTempDir(async (dir) => {
await Promise.all([
appendTiming(dir, { player: 0, phase: 'localOps', day: 1, stage: 1, startedAt: 1, endedAt: 2 }),
appendTiming(dir, { player: 1, phase: 'localOps', day: 1, stage: 1, startedAt: 2, endedAt: 3 }),
]);
const timings = JSON.parse(await readFile(join(dir, 'turn-timings.json'), 'utf8')) as unknown[];
assert.equal(timings.length, 2);
}));
it('reports a save that is not JSON instead of throwing (v0.8.4)', () =>
withTempDir(async (dir) => {
await writeFile(join(dir, 'game.json'), '{"seed": 42, "hist');
const result = await loadGame(dir);
assert.equal(result.found, false);
if (!result.found) assert.ok(result.corrupt, 'a torn file was reported as merely missing');
await writeFile(join(dir, 'game.json'), '{"seed": 42}');
const shape = await loadGame(dir);
assert.equal(shape.found, false);
if (!shape.found) assert.match(shape.corrupt ?? '', /history/);
}));
}); });
+21
View File
@@ -611,3 +611,24 @@ describe('narration reaches a seat exactly once, by one path (#97)', () => {
assert.deepEqual(third.lines, opening.lines, 'a reconnect is the full log, every time'); assert.deepEqual(third.lines, opening.lines, 'a reconnect is the full log, every time');
}); });
}); });
describe('the intent sequence across a reconnect (v0.8.4)', () => {
it('tells a connecting seat the last seq it had accepted, so a reloaded page continues the count', () => {
const session = createSession(42, config, ['Alice', 'Bob']);
const first = session.connect(0 as PlayerIndex);
assert.equal(first.lastSeq, 0, 'a seat that has moved nothing should be told 0');
const actor = (first.menu !== null ? 0 : 1) as PlayerIndex;
const r = session.intent(actor, 1, { type: 'localOps.choose', option: 'draw' });
assert.ok(r.accepted);
// A reload: the client starts its own count from 1 again unless told otherwise.
const again = session.connect(actor);
assert.equal(again.lastSeq, 1, 'the reconnect push does not say where the count stands');
// The repeat the old client would have sent — silently swallowed as a resend.
const repeat = session.intent(actor, 1, { type: 'draw.fromHomeOffice' });
assert.ok(repeat.accepted && repeat.pushes.size === 0, 'seq 1 should still read as an idempotent resend');
// Continuing from lastSeq + 1 is a real move.
const next = session.intent(actor, 2, { type: 'draw.fromHomeOffice' });
assert.ok(next.accepted && next.pushes.size > 0, 'seq 2 was not applied');
});
});
+26 -6
View File
@@ -7,7 +7,7 @@ import { describe, it } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import type { CarType } from '../src/engine/content.ts'; import type { CarType } from '../src/engine/content.ts';
import { DEFENCE_ONLY_CARDS, DEFENCE_ONLY_COPIES, MODIFIER_PROFILES, OPENING_OTHER, OPENING_TRACK, SOLITAIRE_DECK_SIZE, TRACK_CARDS, TRACK_IN_DECK, withSavedOpening } from '../src/engine/content.ts'; import { DEFENCE_ONLY_CARDS, DEFENCE_ONLY_COPIES, MODIFIER_PROFILES, OPENING_OTHER, OPENING_TRACK, SOLITAIRE_DECK_SIZE, TRACK_CARDS, TRACK_IN_DECK, withSavedDeal } from '../src/engine/content.ts';
import { import {
DECK_SIZE, DECK_SIZE,
EXTRA_TRAINS, EXTRA_TRAINS,
@@ -680,16 +680,36 @@ describe('the starting Office, and the deck that goes with it', () => {
it('replays a save written before the setting as the Whistle Post game it was', () => { it('replays a save written before the setting as the Whistle Post game it was', () => {
/** /**
* The one house rule that changes how a game is DEALT rather than how it plays, so replaying it * The one house rule that changes how a game is DEALT rather than how it plays, so replaying it
* under the wrong opening is a different railroad from intent one — silently. `withSavedOpening` * under the wrong opening is a different railroad from intent one — silently. `withSavedDeal`
* fills it for a save that names other rules and cannot name this one. * fills it for a save that names other rules and cannot name this one.
*/ */
const saved: { houseRules: { startingHand: 'sixRandom'; startingOffice?: 'depot' | 'whistlePost' } } = const saved: { houseRules: { startingHand: 'sixRandom'; startingOffice?: 'depot' | 'whistlePost'; secondSectionCard?: boolean } } =
{ houseRules: { startingHand: 'sixRandom' } }; { houseRules: { startingHand: 'sixRandom' } };
assert.equal(withSavedOpening(saved).houseRules.startingOffice, 'whistlePost'); assert.equal(withSavedDeal(saved).houseRules.startingOffice, 'whistlePost');
// ...and from a deck without the Second Section card, which went in at the same time (v0.8.3).
assert.equal(withSavedDeal(saved).houseRules.secondSectionCard, false);
// A config that names it is left exactly as it is, in both directions. // A config that names it is left exactly as it is, in both directions.
assert.equal(withSavedOpening({ houseRules: { startingOffice: 'depot' as const } }).houseRules.startingOffice, 'depot'); assert.equal(withSavedDeal({ houseRules: { startingOffice: 'depot' as const } }).houseRules.startingOffice, 'depot');
assert.ok(!('secondSectionCard' in withSavedDeal({ houseRules: { startingOffice: 'depot' as const } }).houseRules));
// And a config with no house rules at all is a fresh game, not an old save. // And a config with no house rules at all is a fresh game, not an old save.
assert.deepEqual(withSavedOpening({}), {}); assert.deepEqual(withSavedDeal({}), {});
});
it('deals the same deck a pre-0.8.2 save was dealt from — no Second Section card (v0.8.3)', () => {
/**
* The card went into the deck in v0.8.2 after that release's save check had been run. A deck one
* card larger shuffles into a different order from the same seed, so every save on the test
* server refused at move 3 while the release notes said three would resume. Pinned here: the
* legacy deal has no such card and the fresh deal has exactly one.
*/
const count = (g: ReturnType<typeof createGame>): number =>
[...g.cards.values()].filter((c) => c.kind.kind === 'secondSection').length;
const fresh = createGame({ id: 'f', seed: 7, config: { ...solitaireConfig, houseRules: {} } as never, playerNames: ['A'] });
assert.equal(count(fresh), 1, 'a fresh deal should carry one Second Section card');
const legacy = createGame({
id: 'l', seed: 7, config: withSavedDeal({ ...solitaireConfig, houseRules: { startingHand: 'sixRandom' } }) as never, playerNames: ['A'],
});
assert.equal(count(legacy), 0, 'a pre-0.8.2 save was dealt from a deck with no Second Section card');
}); });
}); });
-1
View File
@@ -9,7 +9,6 @@ import assert from 'node:assert/strict';
import { pump } from '../src/engine/advance.ts'; import { pump } from '../src/engine/advance.ts';
import { createGame } from '../src/engine/setup.ts'; import { createGame } from '../src/engine/setup.ts';
import { applyIntent, check, refillDivisionYardIfEmpty } from '../src/engine/apply.ts'; import { applyIntent, check, refillDivisionYardIfEmpty } from '../src/engine/apply.ts';
import { TOTAL_ROLLING_STOCK } from '../src/engine/content.ts';
import type { GameConfig, GameState, OfficeArea } from '../src/engine/state.ts'; import type { GameConfig, GameState, OfficeArea } from '../src/engine/state.ts';
import type { Intent } from '../src/engine/intents.ts'; import type { Intent } from '../src/engine/intents.ts';
import { connectionsFor, exitsFrom, hasPort, joins, neighbour, opposite, variantsFor } from '../src/engine/track.ts'; import { connectionsFor, exitsFrom, hasPort, joins, neighbour, opposite, variantsFor } from '../src/engine/track.ts';
-1
View File
@@ -31,7 +31,6 @@ const config: GameConfig = {
optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false }, optionalRules: { reducedVisibility: false, employeeRotation: false, emergencyToolbox: false },
}; };
const game = (seed = 5): GameState => createGame({ id: 'g', seed, config, playerNames: ['p'] }); const game = (seed = 5): GameState => createGame({ id: 'g', seed, config, playerNames: ['p'] });
const at = (row: number, col: number): GridCoord => ({ row, col });
const straight = (standing: RollingStock[] = []): TrackCard => ({ const straight = (standing: RollingStock[] = []): TrackCard => ({
geometry: { kind: 'track', geometry: 'straight' }, geometry: { kind: 'track', geometry: 'straight' },
+39 -13
View File
@@ -8,7 +8,7 @@
import { describe, it } from 'node:test'; import { describe, it } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { turnOf } from '../src/engine/state.ts'; import { turnOf } from '../src/engine/state.ts';
import { areaOf, check } from '../src/engine/apply.ts'; import { acceptsCar as acceptsCarOf, areaOf, check } from '../src/engine/apply.ts';
import type { Game } from '../src/web/game.ts'; import type { Game } from '../src/web/game.ts';
import { execFileSync } from 'node:child_process'; import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { existsSync, readFileSync, readdirSync } from 'node:fs';
@@ -22,7 +22,7 @@ import { cardDescription, cardName, describeIntent, variantLabel } from '../src/
import { variantsFor } from '../src/engine/track.ts'; import { variantsFor } from '../src/engine/track.ts';
import { BOARD_CSS, divisionSvg, officeSvg } from '../src/sim/board-svg.ts'; import { BOARD_CSS, divisionSvg, officeSvg } from '../src/sim/board-svg.ts';
import type { DivisionView } from '../src/sim/view.ts'; import type { DivisionView } from '../src/sim/view.ts';
import { ENHANCEMENT_RULES, STAGES_PER_DAY, mainlineProfile } from '../src/engine/content.ts'; import { ENHANCEMENT_RULES, STAGES_PER_DAY, mainlineProfile, trainProfile } from '../src/engine/content.ts';
import { dayEndHtml, facilitiesHtml, pilesHtml, resultsHtml, timetableHtml } from '../src/web/panels.ts'; import { dayEndHtml, facilitiesHtml, pilesHtml, resultsHtml, timetableHtml } from '../src/web/panels.ts';
import { TURNCHART_CSS, turnChartHtml } from '../src/sim/turnchart.ts'; import { TURNCHART_CSS, turnChartHtml } from '../src/sim/turnchart.ts';
import { fieldSelectors } from '../src/web/settings-form.ts'; import { fieldSelectors } from '../src/web/settings-form.ts';
@@ -1794,17 +1794,6 @@ describe('the static build', () => {
}; };
assert.ok(clickFirst(actions, 'button.act'), 'no action button rendered'); assert.ok(clickFirst(actions, 'button.act'), 'no action button rendered');
// Specifically the PLAY verb: a hand usually holds cards that can only be discarded, and
// discarding highlights the Department piles rather than the board.
const clickVerb = (el: Record<string, unknown>, verb: string): boolean => {
const fn = el['querySelectorAll'] as (s: string) => Record<string, unknown>[];
const target = fn
.call(el, 'button.cardact')
.find((n) => (n['dataset'] as Record<string, string>)['verb'] === verb);
if (!target) return false;
(target['onclick'] as (() => void) | null)?.();
return true;
};
/** /**
* TRY EVERY PLAY BUTTON, NOT JUST THE FIRST — a card offering "play" does not necessarily play * TRY EVERY PLAY BUTTON, NOT JUST THE FIRST — a card offering "play" does not necessarily play
* ONTO THE BOARD. * ONTO THE BOARD.
@@ -2459,6 +2448,43 @@ describe('the static build', () => {
} }
}); });
it('never lists a car in "still needs" that the engine would refuse (v0.8.4)', () => {
/**
* `consistNeeds` counted by category on its own and could promise cars `acceptsCar` refuses —
* nothing couples behind a caboose (§A.3), and a card narrows which freight it takes. It asks
* `acceptsCar` per category now, so this holds every line of the panel to the engine's answer,
* and the reverse: a category the engine still takes is never left off.
*/
let panels = 0;
for (const seed of [430, 99, 270861860]) {
const game = newGame(seed);
for (let i = 0; i < 600 && currentActor(game) !== null; i++) {
const menu = actionMenu(game);
if (menu.makeUp) {
const tray = game.state.trays.get(menu.makeUp.trayId)!;
const profile = trainProfile(tray.trainNumber ?? 0, tray.trainIsExtra)!;
const needs = menu.makeUp.needs ?? '';
const categories = [
{ name: 'freight', sample: profile.consist.freightTypes?.[0] ?? 'boxcar', re: /boxcar|hopper|reefer|tank|freight/ },
{ name: 'coach', sample: 'coach', re: /coach/ },
{ name: 'caboose', sample: 'caboose', re: /\d caboose/ },
] as const;
for (const c of categories) {
const listed = c.re.test(needs);
const takes = acceptsCarOf(tray, c.sample);
if (listed) assert.ok(takes, `seed ${seed}: the panel lists ${c.name} the engine refuses: "${needs}"`);
const wanted = (c.name === 'coach' ? profile.consist.coach : c.name === 'caboose' ? profile.consist.caboose : profile.consist.freight) > tray.consist.filter((x) => (x.type === 'coach' ? 'coach' : x.type === 'caboose' ? 'caboose' : 'freight') === c.name).length;
if (takes && wanted) assert.ok(listed, `seed ${seed}: the engine still takes a ${c.name} the panel does not list: "${needs}"`);
}
panels++;
}
const { options } = actionGroups(game);
if (options.length === 0 || !submit(game, options[0]!)) break;
}
}
assert.ok(panels > 0, 'no seed reached a train being made up');
});
it('keys each make-up car to the yard chip that shows it', () => { it('keys each make-up car to the yard chip that shows it', () => {
// Ten buttons reading "add loaded hopper" when the Division Yard is already on screen showing // Ten buttons reading "add loaded hopper" when the Division Yard is already on screen showing
// exactly those cars by type and load state. The yard is the surface. // exactly those cars by type and load state. The yard is the surface.
+2
View File
@@ -10,6 +10,8 @@
"noUncheckedIndexedAccess": true, "noUncheckedIndexedAccess": true,
"noImplicitOverride": true, "noImplicitOverride": true,
"exactOptionalPropertyTypes": true, "exactOptionalPropertyTypes": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true, "noEmit": true,
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,