# Stackhouse — implementation handoff

Version 1.0.0 · 1 December 2026

## What exists

A dependency-free HTML/CSS/JavaScript prototype, an isolated deterministic game engine, automated tests, a simulator, and a complete rulebook. The live prototype supports one-device pass-and-play for 2–8 people or one human with practice bots. It has configurable stacking, drawing, hand size, hidden handoffs, colour selection, browser autosave, per-round scoring, and a debug-state export.

It does **not** implement network rooms, join codes, WebSockets, cloud saved matches, secure hidden information, spectators, human reconnect, multi-round scoreboards, or production-scale enormous hand rendering. Those are explicitly specified below for implementation. No fake join button is presented.

## Run locally

Use a current Node.js installation for tests; no package install is required.

```sh
npm test
npm run simulate
npm run dev
```

Open http://127.0.0.1:8080 in a modern browser. Serve over HTTP; ES modules do not reliably work by double-clicking `index.html`. System fonts are the fallback when optional Google Fonts cannot load. The application logic has no third-party dependencies.

## Repository layout

| Path | Responsibility |
|---|---|
| `dist/index.html` | Table, handoff/setup/colour/rules dialogs |
| `dist/style.css` | Responsive table and card styling |
| `dist/engine.js` | Rule state, legal moves, deck construction, seeded shuffle, reducer |
| `dist/app.js` | DOM rendering, controls, bot scheduling, local save, export |
| `docs/RULES.md` | Authoritative complete semantics |
| `docs/IMPLEMENTATION.md` | This build plan and contract |
| `docs/VERIFICATION.md` | Observed checks and limits |
| `docs/simulation-results.json` | Actual stress-run summaries |
| `tests/engine.test.mjs` | Targeted regression and invariants |
| `tests/simulate.mjs` | Reproducible bot stress harness |
| `CODEX_START_PROMPT.md` | Starting prompt for a future implementation session |

The deployed `dist/RULES.md` and `dist/IMPLEMENTATION.md` are copies for in-app downloads. Keep them synchronized with `docs/`. The distributable source archive omits credentials, Git internals, and the live Site identity.

## Engine contract

`newGame(players, settings, seed)` returns a serializable state. `legal(state, card)` checks an owned card against the current phase. `act(state, action)` clones the input, validates the action, applies all effects, and returns the new state. Invalid actions throw without modifying the input. `botAction(state)` selects one simple legal action. `check(state)` asserts core invariants. Helpers `take` and `mint` mutate an internal state during construction/transition and should never be exposed as client actions.

```ts
type Color = 'red' | 'yellow' | 'green' | 'blue';
type Kind = 'number' | 'skip' | 'reverse' | 'draw2' | 'wild' | 'draw4';
type Card = { id: string; color: Color | null; kind: Kind; value: number | null };
type Rules = {
  stacking: 'same' | 'ladder' | 'mixed';
  drawMode: 'one' | 'until';
  handSize: 7 | 10 | 14;
};
type Action =
  | { type: 'play'; player: number; cardId: string; color?: Color }
  | { type: 'draw'; player: number }
  | { type: 'pass'; player: number };
```

Important state fields: `version`, `rules`, `seed`, `rng`, `nextId`, `batches`, `recycles`, `deck`, `discard`, `players`, `current`, `direction`, `color`, `pending`, `lastDraw`, `drawnId`, `turn`, `revision`, `winner`, `points`, `maxDebt`, and a capped text `log`. `revision` increments once per accepted action; `turn` increments when turn advancement occurs. They are not interchangeable. Winner is `null` during play; seat zero is a valid winner, so never test winner truthiness.

### Derived phases

| Condition, in priority order | Phase | Accepted actions |
|---|---|---|
| `winner !== null` | ROUND_OVER | None |
| `pending > 0` | STACK_RESPONSE | Eligible draw-card play; accept full pickup |
| `drawnId !== null` | DRAW_DECISION | Play that card; keep/pass |
| Otherwise | NORMAL_TURN | Legal play; voluntary draw |

Colour picking is UI-only until a play includes its chosen colour; no partial mutation or intermediate authoritative wild state is required. Handoffs and bot pause are UI-only too.

### Resolution order

1. Reject ended round, wrong actor, absent card, illegal move, or missing wild colour.
2. Move exactly one card from hand to discard; update active colour.
3. Apply draw-debt addition, if any.
4. If actor has zero cards, settle final debt to next seat, compute score, declare winner, stop.
5. Otherwise emit automatic one-card call when applicable.
6. Apply Skip/Reverse turn advancement, or ordinary advancement.
7. Advance revision; persist and render only the complete result.

For a draw action, either resolve all outstanding debt and advance, or draw according to the normal-draw mode and enter DRAW_DECISION only if the last card is legal. Payment and expansion happen in the same logical action.

### Core invariants

- Every issued card appears exactly once among draw pile, discard pile, and hands.
- Total card count equals `108 × batches`; no duplicate IDs.
- At least one discard exists after setup; active colour is one of four choices.
- Pending debt is a nonnegative even integer. Pending debt has a latest draw type; a resolved debt has none.
- Only the active seat acts. A drawn-card decision limits play to `drawnId`.
- Cards change zones, never identities or faces. Wild selection changes `state.color`, not `card.color`.
- A successful action is atomic; a rejected action cannot partially deal or shuffle.
- No turn begins after ROUND_OVER. Rules never change in a running round.

The prototype's Xorshift32 PRNG makes tests reproducible; it is **not cryptographically secure**. The browser stores the full state, so this is not an anti-cheat multiplayer engine as shipped. Keep the rule semantics; upgrade randomness and trust boundaries for network play.

## Recommended implementation for phones around a family table

Use a single authoritative server per room, a web client for each phone, and an optional read-only table display. The room owner chooses the settings, family members join, everyone marks ready, and the host deals. Freeze a canonical rules JSON and rules version at deal time.

A simple persistent WebSocket room actor is a suitable deployment shape. Keep engine code framework-independent. The exact backend/framework can follow the hosting stack chosen in the next coding session; this handoff does not require a particular vendor or new dependencies.

### Room states and lifecycle

`LOBBY → IN_ROUND → ROUND_COMPLETE → LOBBY_FOR_NEXT_ROUND`, with explicit `PAUSED` and `CLOSED` states. Host starts only when every occupied seat is ready and there are 2–8 seats. Players cannot join an active round as new seats; allow spectators only if that feature is deliberately implemented. Rotate the first seat between rounds. Maintain round wins separately from points; recommend a first-to-three-wins match.

Default disconnection behaviour: preserve seat and cards, pause when that seat must act, and show reconnect status. Do not auto-forfeit or replace a player on a short timeout. The host may explicitly choose bot takeover after the disconnected player's seat is reserved, with a visible event to everyone. Takeover must preserve the exact hand, debt, and phase. On reconnection, hand control back at a turn boundary. Specify and test this before enabling it.

If the host disconnects, preserve the server room. Elect the longest-present connected human as host only for administrative controls; this must not confer power to inspect hands. Idle room expiry must have a stated TTL and clear UI. Expiry must not invent a winner.

### Network commands

```json
{
  "roomId": "opaque-room-id",
  "roundId": "opaque-round-id",
  "clientActionId": "uuid",
  "expectedRevision": 42,
  "command": { "type": "play", "cardId": "opaque-card-id", "color": "blue" }
}
```

Authenticate the session and derive its seat on the server. Never trust a client-supplied seat, score, hand, chosen debt, shuffle, or rules override. Reject stale revisions with an authoritative snapshot; deduplicate `clientActionId` so reconnect/retry cannot play or draw twice. Validate schema/size and current phase before invoking the reducer. Serialize commands within a room; do not let simultaneous requests race the same revision.

Use an opaque join code for discovery plus a separate per-player reconnect token. Do not embed all authority into a guessable short code. Rate-limit room discovery and joining. Protect the creator controls; starting, resetting, and changing future-round settings are host actions. A player cannot abandon someone else's turn by submitting a client reset.

### Public and private projections

Public: room/round/revision, seat display names, each hand count, active seat/direction, top discard, active colour, pending debt, latest draw type, phase, declared calls, supply counters, public events, and completed scores.

Private: only the receiving player's cards, that player's allowed actions, and reconnect identity. A player's projection must not contain any opponent's cards, remaining draw order, future card IDs, RNG seed/state, or full debug logs. Do not reuse the current full-state export endpoint for a live public replay. Spectators receive public state only; the host is not a privileged spectator of secret hands.

Use a server-private CSPRNG shuffle and nonpredictable card IDs in production. Persist the shuffle outcomes or server RNG stream privately to replay authoritative actions. Expose an audit replay only after a round ends if everyone has agreed; never publish current hidden information to prove fairness.

### Persistence and events

Use room snapshots plus append-only structured events: `RoundStarted`, `CardPlayed`, `ColourChosen`, `DebtIncreased`, `CardsDrawn`, `DiscardRecycled`, `DeckBatchCreated`, `TurnAdvanced`, `OneCardAnnounced`, `RoundWon`, `RoomPaused`, and `SeatReconnected`. Private events containing card identities remain server-private. The prototype's human-readable, last-100-move log is not this complete event stream.

Persist new state, revision, action deduplication record, and events in one transaction. A crash after accepting a pickup must not redraw a different set on retry. On reconnect, send the latest private projection and any missed public events. Key state migrations by exact rules version; do not reinterpret an old round under newer mechanics.

## Handling enormous hands without changing the rules

The prototype uses arrays, DOM buttons per card, synchronous draws, and `structuredClone` per action. A 1,000-card draw is tested at engine level; huge browser hands are not performance-certified. Physical memory and JavaScript's safe integer range are finite despite uncapped gameplay rules.

Production improvements:

1. Virtualize large hand lists and offer grouped counts plus expand-to-select; use stable instance IDs when a duplicate face is played.
2. Execute expensive pickups in a worker or server job, chunking internal work while keeping the action logically atomic and the room locked to that action.
3. Show one summary animation for a pickup; do not animate a thousand individual cards. Respect reduced motion.
4. Persist a pending-operation checkpoint if work can survive a restart. Notify clients of progress without exposing partial hands or allowing a new action prematurely.
5. Use overflow-checked arithmetic. If an operational limit is reached, pause with a recoverable capacity message and preserve the debt. Never silently cap, discard, forgive, or truncate a legal pickup.
6. Track performance by issued-card count, serialized snapshot size, action latency, and hand-render time. Set engineering budgets separately from gameplay limits.

## UX contract

- Main task is the full card table, not a marketing landing page.
- Present only legal cards as interactive, but keep all owned faces legible. Use text labels as well as colour.
- Place accumulated pickup beside the discard and on the acceptance button: “Pick up 18”.
- Confirm destructive new-table intent in setup; opening setup alone never loses the round.
- Tell the player when only the just-drawn card may be played.
- Show whose turn it is and the active colour independently of the top wild face.
- Keep large hands horizontally scrollable in the prototype; add sorting/filtering and virtualization for production.
- Pause bots during dialogs. Never show another human's hand before readiness confirmation.
- Use keyboard-operable buttons, focus indicators, labelled controls, and concise screen-reader turn announcements. Test actual screen readers before claiming conformance.

## Scope order for the next build

1. Preserve all current rules and port tests without changing semantics.
2. Add host/create/join/ready flow and authoritative seat identity.
3. Implement per-seat private projections, serialized commands, and idempotency.
4. Add durable snapshots/events and reconnect with exact revision recovery.
5. Add multi-round scoreboards, rotate first seat, and match completion.
6. Test a family on 2, 4, and 6 phones, including reconnect during a stack and during wild selection.
7. Add hand virtualization and resource-pausing behaviour after correctness is proven.
8. Only then experiment with card-density presets, manual calls, or new action cards behind explicit versioned rules.

## Future-rule acceptance gates

A new rule must define setup impact, legal trigger, target, colour, pending-debt compatibility, two-player behaviour, last-card behaviour, draw-decision behaviour, interruption behaviour, and scoring. It must include positive/negative tests and a replay fixture. Avoid combining manual challenges, jump-ins, reflection, and provisional wins in the first network release; each adds competing timing windows.

## Human playtest protocol

Play three default seven-card rounds with 2–4 people, then three Escalation rounds. Note elapsed real minutes, largest hand, biggest debt, turns spent only drawing, rule questions, and whether losing players felt able to recover. Ask each person whether they want another round. Keep children’s actual names and recordings out of shared diagnostics.

Compare one changed rule at a time. Use Draw until playable only after the default session; stop if a player finds it tedious. The bot results justify a conservative default but cannot establish enjoyment, fairness, age suitability, or ideal game length. Predefine desired round length with the family instead of treating simulated action counts as minutes.


## Handoff release 1.1.0 additions

Gameplay is unchanged. START_HERE.md indexes the expanded knowledge. scripts/dev.mjs adds a portable local server; reference/projections.mjs provides a tested whitelist for public/private views; contracts/ contains proposed network and runtime rules schemas. docs/MULTIPLAYER_CONTRACT.md specifies command sequencing and deduplication. docs/BUILD_PLAN.md defines milestone acceptance. The schema and reference module are not integrated multiplayer. See docs/HANDOFF_VERIFICATION.md for the new checks.
