summaryrefslogtreecommitdiff
path: root/PLAN.md
blob: 6ff72944689b13e283505d1c7cb571362782a8d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# X-Haven Web — Implementation Plan

**Status:** APPROVED — implementation in progress (Phase 0 started 2026-11-08).
**Last updated:** 2026-11-08

Progress is tracked in this file: mark steps `- [x]` as they are completed and record
milestones in §6. The reference app (`FrosthavenAssistant/`) is read-only; all new code
lives in `server/` and `web/`.

---

## 1. Goals

Re-architect X-haven Assistant as a **server-driven web app** (intent in `README.md`):

- The web server owns **all** game state and is the single source of truth.
- Player browsers submit **input only** — they carry no game state.
- **Spectator** clients open the same page, read-only.
- **Secret per-player data** (canonically: initiative values) is gated **by the server, per
  connection**, until the draw action reveals it to everyone.
- **Full feature parity** with the reference app, with a **faithful reproduction** of its
  look and layout (restyled for the browser).

## 2. Decisions

| Topic | Decision | Rationale |
|---|---|---|
| Server language | **Dart** (single package, WebSocket server) | ~12k lines of game logic (commands, state, methods, line parser) already exist in Dart and port nearly 1:1; the test suite ports too |
| Client | **TypeScript + Svelte 5** (Vite-built static SPA) | decided; SPA served by the Dart server, no Node runtime in production |
| Transport | **WebSocket** (single endpoint), JSON messages | server push + player input; no need for the old `S3nD:[EOM]` TCP framing |
| State sync | **full-state push on every action** + monotonic index + full resync on reconnect | proven model from the reference app (`{i,d,e,s}` envelope); state is a few KB, tables are small |
| Command execution | **server is the only executor** — clients send command name + args | matches "clients send input only"; cleaner than the reference app's client-executes-server-arbitrates model |
| Deployment | one server process = one game (as today); default port **4567** | faithful to the original |
| License | **AGPLv3** (inherited — ports reference-app code and ships its data/art assets) | upstream license |
| Old server package | `frosthaven_assistant_server` (GameServer/TCP protocol) is **superseded** — we reuse its *concepts* (monotonic index, full-state push, resync, ping), not its code | the new protocol is native to WebSocket |

## 3. Architecture

### 3.1 Repo layout

```
whaven/
├── PLAN.md                    # this file (progress tracked here)
├── server/                    # Dart package: the game server (all game logic lives here)
│   ├── bin/main.dart          # entry: load data + save, serve static, open WS
│   ├── lib/
│   │   ├── core/              # ported game logic (from frosthaven_assistant/lib/Resource/)
│   │   │   ├── models/        # from lib/Model/ (immutable campaign/scenario/monster models)
│   │   │   ├── state/         # GameState + part files → plain fields + toJson/fromJson
│   │   │   ├── commands/      # all 84 command files + registry (wire name + args ↔ ctor)
│   │   │   ├── methods/       # game/round/scenario/character/monster/deck/element methods
│   │   │   ├── line_builder/  # Frosthaven ability-line parser
│   │   │   ├── game_data.dart # loads server/assets/data from disk (was rootBundle)
│   │   │   └── action_handler.dart
│   │   ├── net/               # WS server, protocol codec, sessions, roles, visibility
│   │   └── persist/           # save/load (single save now, multi-save in Phase 6)
│   ├── test/                  # ported test suite + new protocol/session/secret tests
│   └── assets/                # COPIED from reference app: data/, images/, i18n/, fonts/
├── web/                       # Svelte SPA (TypeScript)
│   └── src/
│       ├── lib/
│       │   ├── protocol/      # WS client, message types, reconnect + resync
│       │   ├── state/         # stores: game state, session/seats, connection status
│       │   ├── i18n/          # UI strings (ported .arb) + in-game ability-text translations
│       │   └── components/    # faithful UI: top/bottom bar, main list, rows, cards,
│       │                      # decks, initiative widget, menus (dialogs)
│       └── routes/            # the single game page
└── (FrosthavenAssistant/ — read-only reference, gitignored)
```

### 3.2 Server game core (port of `Resource/`)

- `ValueNotifier`s are dropped — the server no longer needs local observers; browsers receive
  state over WebSocket. Everything else keeps the reference app's structure.
- The `_StateModifier` capability token pattern is **kept**: commands remain the only
  mutation path.
- **Command registry (new):** every command gains a wire descriptor — a short name plus
  serializable args — so the server can execute incoming player input
  (e.g. `{name:"draw", args:{}}`). The reference app builds commands directly in UI code and
  has no registry; this is the main structural addition to the port.
- `ActionHandler`: execute command → increment index → record `describe()` → snapshot into
  undo history (250 deep) → persist to disk → broadcast per-connection state to all sessions.
  `undo`/`redo` run server-side on request.
- `GameData` loads from `server/assets/data/` on disk (test data from the testData mirror).

### 3.3 Sessions, roles, ownership

- Each connection gets a **persistent session id** (cookie) — survives page refresh, so a
  player keeps their seat.
- Roles:
  - **Spectator** (default): receives state; cannot submit commands.
  - **Player**: a session that claims a character. The session that issues
    `AddCharacterCommand` owns the new character; previously-added characters can be
    claimed via a `claim` message.
- A character has **at most one owning session**. When the owner's session disconnects, the
  character becomes unclaimed and any player session may claim it.
- Any player may request undo/redo (the server plays the "host" role of the reference app).
- Seat assignments (who owns which character) are broadcast as `seats` messages; the UI uses
  them to enable inputs only on the owning player's screen.

### 3.4 Secret data model (server-gated per connection)

Generalizes the reference app's UI-only `??` mask (where every device actually held all
initiative values) into real server-side gating:

- State is serialized **per connection**: `serializeState(state, session)`.
  - During `chooseInitiative`: each character's initiative value is included **only** in the
    serialization sent to its owning session; every other connection (players and
    spectators) receives `??`/null.
  - Once `playTurns` starts (the `DrawCommand` transition): initiative is public in every
    serialization.
- Implemented as a small **visibility layer** inside the serializer — a list of rules
  `(secret field, owner, revealed-when)`. Initiative is rule #1; any future secret is added
  as a new rule rather than a special case.
- Secrets never exist on any connection other than the owner's — a strict improvement over
  the reference app.

### 3.5 Wire protocol (WebSocket, JSON)

Client → server:

```jsonc
{ "t": "hello", "v": 1 }                  // first message (session id comes from cookie)
{ "t": "claim", "characterId": "..." }    // claim a character seat
{ "t": "cmd",   "name": "draw", "args": {} }  // execute command (players only)
{ "t": "undo" }     { "t": "redo" }       // players only
{ "t": "ping" }
```

Server → client:

```jsonc
{ "t": "welcome", "v": 1, "session": "...", "role": "player|spectator",
  "index": 42, "description": "…", "event": {…}, "state": {…}, "seats": {…} }
{ "t": "update",  "index": 43, "description": "…", "event": {…}, "state": {…} }  // per-connection state
{ "t": "seats",   "seats": {…} }
{ "t": "error",   "code": "rejected|badRequest|…", "message": "…" }
{ "t": "pong" }
```

- `state` is a full JSON snapshot, **already masked for that connection** (3.4) — the
  equivalent of the reference app's `{i, d, e, s}` envelope.
- The index is strictly monotonic; the server executes commands sequentially in arrival
  order. A command that fails validation (e.g. a second draw) is rejected with an `error`
  to the sender only — no client-side lockouts needed (replaces the reference app's
  300 ms draw-button lockout).
- Reconnect: the client re-sends `hello` with its session cookie → the server answers with
  a full `welcome` (latest state). No command replay, no drift recovery protocol needed.
- Protocol version in the handshake (reference app precedent); mismatches get a clear error.

### 3.6 Persistence

- After **every** action (faithful to the reference app): write the authoritative snapshot —
  GameState JSON + description history + seat ownership — to `server/saves/`.
- On startup: restore the most recent save. Multi-save + character saves land in Phase 6.

## 4. Phased plan

**M1** engine runs headless · **M2** multiplayer + secrets over WS · **M3** playable in a
browser · **M4** card play complete · **M5** full feature set · **M6** settings/saves/locale
parity · **M7** release.

Note on effort: the engine port (Phase 1) is mechanical but large (~12k lines + test
suite). The UI phases (3–5) are the biggest chunk overall — reproducing ~19k lines of
Flutter UI faithfully in Svelte.

### Phase 0 — Scaffolding ✅ (2026-11-08)

- [x] `server/` Dart package (SDK ≥ 3.11, matching the reference app): `bin/main.dart`,
      pubspec, analysis options
- [x] `web/` Vite + Svelte 5 + TypeScript project; dev server proxies WS to the Dart server
- [x] Copy assets from the reference app into `server/assets/`: `data/` (editions, rooms,
      summons — 3.3 MB JSON), `images/` (66 MB PNG), `i18n/` (in-game text, 10 locales),
      `fonts/` (+ `testData/` for the Phase 1 test loader)
- [x] `LICENSE` (AGPLv3) + root `README.md` updated to describe the web app and how to run it
- [x] `.gitignore` additions (Dart: `.dart_tool/`, `pubspec.lock`, `saves/`; web:
      `node_modules/`, `dist/`)
- [x] CI script: `dart analyze && dart test` for the server; `tsc && vitest && vite build` for
      the web app (web typecheck is `svelte-check`, the Svelte-appropriate equivalent of `tsc`
      that also checks `.svelte` files)
- [x] Smoke: server serves the built SPA at `/` and answers a WS `hello` with `welcome`
      (verified: `curl /healthz`, `curl /` → SPA, WS hello → welcome from a real client)

Tooling notes (fixed during implementation):
- Web deps pinned to a compatible set: vite 8 + `@sveltejs/vite-plugin-svelte` 7 + vitest 5 +
  svelte-check 4 (svelte-check 4.7's config loader requires the plugin 7 `vite-plugin-svelte:config`
  plugin name; plugin 5 + vite 6 is an incompatible combination).
- Server logging uses `package:logging` — `Logger` is no longer in `dart:developer`/`dart:io`
  in SDK 3.13.

### Phase 1 — Game core on the server (headless)

Port of the complete engine — all of it, so later phases are UI-only:

- [x] `lib/Model/` → `server/lib/core/models/`
- [x] `Resource/line_builder/` (ability-line parser)
- [x] `Resource/game_data.dart` (disk-based loading) + test data loader
- [x] `Resource/state/` → GameState and all part files (plain fields + toJson/fromJson,
      keep the `GameSaveState` snapshot structure)
- [x] All 84 command files → `core/commands/` + **command registry** (wire name + args ↔
      constructor, incl. args validation)
- [x] All `*Methods` classes, `game_event.dart`, `stat_calculator.dart`, `card_stack.dart`,
      `enums.dart`
- [x] `action_handler.dart`: index, 250-deep history, save after every action, undo/redo
- [x] Port unit tests (`test/command/*`, `test/resource/*`, model tests) to the new core
- [x] Headless integration test: full round driven by command invocations — scenario setup →
      characters → initiative → draw → turns → next round → round 2

**Milestone M1** — engine runs headless; ported test suite green.

### Phase 2 — Networking, sessions, secrets

- [ ] WS server: `hello`/`welcome` handshake, protocol version check, `ping`/`pong`,
      connection lifecycle (dead-connection cleanup)
- [ ] Sessions + roles: cookie session ids, spectator default, player on claim
- [ ] Character ownership: assignment on add, `claim`, re-claim after owner disconnects,
      `seats` broadcasts
- [ ] Per-connection state serialization with the visibility layer (initiative rule) —
      **the server never sends a secret to a non-owner**
- [ ] Command execution path: player-role check → args validation → execute → per-connection
      `update` broadcast; `error` responses for rejects; undo/redo on request
- [ ] Persistence: save on every action, restore on startup
- [ ] Tests (fake WS clients): two players + one spectator — secret initiative never reaches
      non-owners; reveal on draw; reconnect resync; rejected duplicate draw; claim/lose
      seat; snapshot restored across a server restart

**Milestone M2** — complete multiplayer + server-gated secrets + persistence over WS, no UI.

### Phase 3 — Web UI: core loop

- [ ] Theme/design tokens matching the app's look (dark base, the three style themes)
- [ ] Page layout: TopBar (campaign/scenario/round info), MainList, BottomBar (draw button)
- [ ] MainList rows: CharacterRow (art, HP bar, conditions, initiative input), MonsterRow
      (art, HP, standees, state), placeholder for NoteRow
- [ ] Initiative widget: shows own value while entering, `??` for others, reveals on draw;
      input enabled only on the owning player's screen
- [ ] Menus (dialogs, faithful flows): select scenario (campaign → scenario → level/
      difficulty), add/remove character, character level, stat changes (health, max, xp,
      bless/curse/empower/enfeeble), conditions, elements (use/imbue), turn done
- [ ] Room sections: add-section menu, auto-add standees
- [ ] Player vs spectator UI: inputs only for owned characters; spectator view read-only
- [ ] Connection UX: connecting/reconnecting banner, auto-resync, offline indicator
- [ ] UI i18n: English first (ported from the app's `.arb` files); locale plumbing in place
- [ ] Client unit tests: protocol client, state stores

**Milestone M3** — playable in a browser: setup, secret initiative, draw, turns, stat
changes, room sections, spectator view. *First end-to-end moment.*

### Phase 4 — Cards and decks

- [ ] Ability-line rendering (line_builder output: tokens, emphasis, range markers) with
      in-game translations (client-side equivalent of `TranslationService`)
- [ ] Character ability decks: draw/shuffle/reorder; per-character decks
- [ ] Monster ability decks: per-monster draw/discard piles, `lastRoundDrawn`
- [ ] Modifier decks: monster/ally/per-character decks; AMD rules (imbue, +1/−1, reveal,
      special commands)
- [ ] Loot deck: draw/return/enhance, ownership, special pile, add/remove loot
- [ ] Card UI: faithful stat cards / ability cards / modifier cards / loot cards (images +
      rendered text), deck widgets
- [ ] Server: registry entries for all deck/loot/modifier commands + ported tests

**Milestone M4** — full card play in the browser.

### Phase 5 — Campaign meta, notes, special rules

- [ ] Note rows: add/remove, text/color/link editing, reorder
- [ ] Special scenario rules: timed spawns, battle goals, initial scenario message
- [ ] Campaign meta: Crimson Scales party cards, faction cards, sanctuary donations
- [ ] Special monster handling: Ice Wraith form change, Bad Omen, Corrosive Spew,
      standee tracking, summons
- [ ] Solo mode, ally deck (OG Gloom), auto-level adjustment, difficulty variants,
      unlock-special
- [ ] Remaining commands in the registry + ported tests; server feature list cross-checked
      against the reference app

**Milestone M5** — full game feature set.

### Phase 6 — Settings, saves, localization parity

- [ ] Settings split: **server-side, game-relevant** (noInit, noStandees, randomStandees,
      expireConditions, autoAddStandees/autoAddSpawns, hideLootDeck, style) vs
      **client-side** (UI scaling, full-screen, wake/Power-mode equivalents → browser
      `localStorage`)
- [ ] Multi-save save/load + character saves (load character save command)
- [ ] Undo/redo UI (player sessions)
- [ ] All 10 locales: port the gen-l10n `.arb` files to client i18n; server-localized
      command descriptions (ported `command_l10n`); locale selector in settings
- [ ] Settings menu (faithful)

**Milestone M6** — feature parity with the reference app.

### Phase 7 — Hardening and shipping

- [ ] E2E (Playwright): two players + one spectator, a full round including secret
      initiative, claim/re-claim, reconnect
- [ ] Resilience: stale tabs, late updates, slow networks, server restart mid-game
- [ ] Performance: state payload size, WS bandwidth under a full table, asset caching
      headers for the 66 MB image set
- [ ] `Dockerfile` (server + built web) + deployment notes
- [ ] User-facing quickstart/README, smoke-test list
- [ ] Final cross-check pass against the reference app (feature list from Phase 5)

**Milestone M7** — release.

## 5. Test strategy

- **Server** (Dart `test`): ported command/state tests from the reference app; new tests for
  the command registry, sessions, seat claiming, per-connection serialization (secret
  gating), persistence, and WS integration (fake clients drive full rounds — mirroring the
  reference app's `network_sync_test.dart` approach, which already proved the protocol can
  be driven by an external client).
- **Client** (Vitest): protocol client (frame handling, reconnect, resync), state stores,
  i18n fallbacks.
- **E2E** (Playwright, Phase 7): the whole table experience in real browsers.

## 6. Progress log

| Date | Event |
|---|---|
| 2026-11-08 | Plan drafted. Decisions fixed: Dart server, TS+Svelte client, full parity, faithful UI. |
| 2026-11-08 | Plan approved. |
| 2026-11-08 | **Phase 0 complete** — server package (shelf + WS, hello/welcome handshake, smoke tests 5/5), web app (Svelte 5 + TS, protocol client, svelte-check clean, build OK), assets copied (73 MB), AGPL license, README, .gitignore, CI script passing end-to-end. |
| 2026-11-12 | **Phase 1 complete / M1 reached** — full engine ported to `server/lib/core/` (models, state + 18 part files, 7 methods classes, game_methods, 79 command files, enums, card_stack, stat_calculator, action_handler, disk-based game_data, l10n, minimal line_builder per conventions §8b). Command registry: 82 entries (wire name ↔ constructor + arg validation; enum/object args resolved against live state). Ported test suite: 81 test files, **562 tests green** (command tests 1:1 with the reference; resource/action-handler/stat-calculator/modifier-deck tests; registry smoke tests). New headless integration test drives a full round (setup → characters + standee → initiative gate → draw → every figure's turn incl. undo/redo → next round → round 2 → round 3). `dart analyze` warning-free. Porting conventions in `server/PORTING.md`. Notable porting fix found by tests: removable-card physical sync had to stay gated to the ten initial counters (reference listener semantics). |

## 7. Risks and open items

- **UI volume is the dominant cost.** ~19k lines of Flutter UI to reproduce faithfully in
  Svelte. Mitigation: faithful *flows and layout*, not pixel-perfect; menus are built once
  as a reusable dialog primitive.
- **Command args coverage.** Every command's constructor args must be fully serializable
  (e.g. `AddMonsterCommand` with standee selection). Resolved in Phase 1 by the registry:
  live-object args (loot card, ability card, character/monster lists) travel as
  id/name/nr and are resolved against live state; enums by name; injected singletons
  never serialize. The registry remains the enforcement point in Phase 2.
- **66 MB of images** — served statically with caching; no processing. Watch initial paint.
- **Concurrent players.** Sequential server-side execution resolves races deterministically;
  the losing side gets a clear `error` (e.g. "round already drawn").
- **License.** AGPLv3 inheritance is assumed; if the app is ever offered as a managed
  service, AGPL §13 source-availability applies to network interaction — a legal call for
  the project owner, not a build blocker.
- **Manual discrepancy** (found during survey): `docs/manual/09-multiplayer.html` §9.6 claims
  per-table configurable secrecy — no such setting exists in the code. The web version
  implements the actual behavior: initiative is always secret until draw.