Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e47cd3d400 | ||
|
|
4d222a7eba | ||
|
|
6f2a8dff09 |
+152
@@ -19,6 +19,158 @@ page as `v0.1.0 · <sha> · <date>`, so what is deployed can always be identifie
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ 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
|
||||||
|
|
||||||
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
|
||||||
@@ -606,6 +606,11 @@ 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**.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Reference — measurements, rulings and rejected approaches
|
## Reference — measurements, rulings and rejected approaches
|
||||||
@@ -2041,7 +2046,9 @@ 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.
|
||||||
@@ -2108,6 +2115,82 @@ placeholder said. **The balance question the entry was really guarding is #70**
|
|||||||
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.
|
||||||
|
|
||||||
|
|
||||||
## 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
|
||||||
|
|||||||
@@ -328,8 +328,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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -151,8 +151,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
@@ -1,6 +1,6 @@
|
|||||||
# Station Master — Components and Markers
|
# Station Master — Components and Markers
|
||||||
|
|
||||||
**Version 0.8.2** · 2026-09-23
|
**Version 0.8.4** · 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
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
# Station Master — Home Deck
|
# Station Master — Home Deck
|
||||||
|
|
||||||
**Version 0.8.2** · 2026-09-23
|
**Version 0.8.4** · 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,6 +1,6 @@
|
|||||||
# Station Master — Mainline Deck
|
# Station Master — Mainline Deck
|
||||||
|
|
||||||
**Version 0.8.2** · 2026-09-23
|
**Version 0.8.4** · 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.
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
# Station Master — Quickstart
|
# Station Master — Quickstart
|
||||||
|
|
||||||
**Version 0.8.2** · 2026-09-23
|
**Version 0.8.4** · 2026-09-29
|
||||||
|
|
||||||
For a player who has never played.
|
For a player who has never played.
|
||||||
|
|
||||||
|
|||||||
+12
-9
@@ -1,6 +1,6 @@
|
|||||||
# Station Master — Rules
|
# Station Master — Rules
|
||||||
|
|
||||||
**Version 0.8.2** · 2026-09-23
|
**Version 0.8.4** · 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).
|
||||||
|
|
||||||
@@ -406,10 +406,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 +472,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.
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "station-master",
|
"name": "station-master",
|
||||||
"version": "0.8.2",
|
"version": "0.8.4",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Station Master — a railroad operations game",
|
"description": "Station Master — a railroad operations game",
|
||||||
|
|||||||
+43
-18
@@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+61
-20
@@ -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';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1803,31 +1840,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 +1882,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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+71
-14
@@ -125,6 +125,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 +149,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -895,7 +920,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 +979,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 +1028,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 +1150,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';
|
||||||
@@ -1990,10 +2015,22 @@ 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);
|
/**
|
||||||
if (sweep) events.push(sweep);
|
* 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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return events;
|
return events;
|
||||||
}
|
}
|
||||||
@@ -2119,7 +2156,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': {
|
||||||
@@ -2715,12 +2752,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));
|
||||||
@@ -3257,11 +3302,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
@@ -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. */
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
+4
-2
@@ -59,6 +59,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 +118,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 +371,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);
|
||||||
|
|
||||||
|
|||||||
+133
-26
@@ -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;
|
||||||
@@ -820,31 +909,49 @@ 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;
|
||||||
if (result.accepted) {
|
await inTurn(ps.gameId, async () => {
|
||||||
// Persisted BEFORE the response goes out — "accepted" should mean "durably on disk" at
|
const result = session.intent(ps.player, seq, intent);
|
||||||
// this scale, not just "applied in memory" (§12 step 14).
|
if (result.accepted) {
|
||||||
const dir = gameDir(opts.dataDir, ps.gameId);
|
// Persisted BEFORE the response goes out — "accepted" should mean "durably on disk" at
|
||||||
await writeGame(dir, session.exportSave(), opts.engineVersion);
|
// this scale, not just "applied in memory" (§12 step 14).
|
||||||
if (result.timing) await appendTiming(dir, result.timing);
|
const dir = gameDir(opts.dataDir, ps.gameId);
|
||||||
if (session.exportSave().status === 'finished') {
|
try {
|
||||||
// `upsertIndexEntry` replaces the WHOLE row for this `gameId`, so the code has to be
|
await writeGame(dir, session.exportSave(), opts.engineVersion);
|
||||||
// carried forward here rather than left blank — `gameCodes` is the only place still
|
if (result.timing) await appendTiming(dir, result.timing);
|
||||||
// holding it once a lobby's own record is gone.
|
if (session.exportSave().status === 'finished') {
|
||||||
const gameCode = [...gameCodes.entries()].find(([, id]) => id === ps.gameId)?.[0] ?? '';
|
// `upsertIndexEntry` replaces the WHOLE row for this `gameId`, so the code has to be
|
||||||
await upsertIndexEntry(opts.dataDir, { gameId: ps.gameId, gameCode, status: 'finished' });
|
// carried forward here rather than left blank — `gameCodes` is the only place still
|
||||||
|
// holding it once a lobby's own record is gone.
|
||||||
|
const gameCode = [...gameCodes.entries()].find(([, id]) => id === ps.gameId)?.[0] ?? '';
|
||||||
|
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
@@ -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.`);
|
||||||
|
|||||||
+69
-23
@@ -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 () => {
|
||||||
await writeFile(tmp, text);
|
const tmp = `${path}.${process.pid}.${++writeSerial}.tmp`;
|
||||||
await rename(tmp, path);
|
await writeFile(tmp, text);
|
||||||
|
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,14 +109,18 @@ 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);
|
||||||
let existing: TurnTiming[];
|
// The read and the write are one unit under the file's queue, or two appends could each read the
|
||||||
try {
|
// same list and one of them would be lost.
|
||||||
existing = JSON.parse(await readFile(path, 'utf8')) as TurnTiming[];
|
await serial(`rmw:${path}`, async () => {
|
||||||
} catch {
|
let existing: TurnTiming[];
|
||||||
existing = [];
|
try {
|
||||||
}
|
existing = JSON.parse(await readFile(path, 'utf8')) as TurnTiming[];
|
||||||
existing.push(timing);
|
} catch {
|
||||||
await atomicWrite(path, JSON.stringify(existing, null, 1));
|
existing = [];
|
||||||
|
}
|
||||||
|
existing.push(timing);
|
||||||
|
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> {
|
||||||
const entries = await readIndex(dataDir);
|
await serial(`rmw:${join(dataDir, INDEX_FILE)}`, async () => {
|
||||||
const i = entries.findIndex((e) => e.gameId === entry.gameId);
|
const entries = await readIndex(dataDir);
|
||||||
if (i >= 0) entries[i] = entry;
|
const i = entries.findIndex((e) => e.gameId === entry.gameId);
|
||||||
else entries.push(entry);
|
if (i >= 0) entries[i] = entry;
|
||||||
await writeIndex(dataDir, entries);
|
else entries.push(entry);
|
||||||
|
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> {
|
||||||
const entries = await readIndex(dataDir);
|
await serial(`rmw:${join(dataDir, INDEX_FILE)}`, async () => {
|
||||||
await writeIndex(
|
const entries = await readIndex(dataDir);
|
||||||
dataDir,
|
await writeIndex(
|
||||||
entries.filter((e) => e.gameId !== gameId),
|
dataDir,
|
||||||
);
|
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. */
|
||||||
|
|||||||
+14
-3
@@ -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.
|
||||||
*
|
*
|
||||||
@@ -415,6 +425,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 +539,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 {
|
||||||
|
|||||||
+5
-1
@@ -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.',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+28
-13
@@ -44,17 +44,17 @@ import {
|
|||||||
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 });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+49
-10
@@ -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++;
|
||||||
const res = await fetch(`/api/intent?${qs}`, {
|
try {
|
||||||
method: 'POST',
|
const res = await fetch(`/api/intent?${qs}`, {
|
||||||
headers: { 'Content-Type': 'application/json' },
|
method: 'POST',
|
||||||
body: JSON.stringify({ seq, intent }),
|
headers: { 'Content-Type': 'application/json' },
|
||||||
});
|
body: JSON.stringify({ seq, intent }),
|
||||||
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),
|
const result = (await res.json()) as { ok?: boolean; code?: string };
|
||||||
// not from this response — this only reports whether the rules accepted it.
|
// The visible update arrives via the SSE push (broadcast to every seat, including this one),
|
||||||
return result.ok;
|
// not from this response — this only reports whether the rules accepted it.
|
||||||
|
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);
|
||||||
|
|||||||
@@ -1704,3 +1704,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');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -2480,3 +2480,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');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -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'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -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>/);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -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
@@ -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 },
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
/**
|
||||||
|
* 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('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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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/);
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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
@@ -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');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+39
-2
@@ -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';
|
||||||
@@ -2459,6 +2459,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.
|
||||||
|
|||||||
Reference in New Issue
Block a user