From 808294adad3f378ad8d66b698acf8df7f49c2302 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Thu, 12 Nov 2026 00:28:50 +0100 Subject: Phase 1: headless game engine on the server (M1) Complete mechanical port of the reference app's game engine to server/lib/core/ so later phases are UI-only: - models/ (7), state/ (GameState + 18 part files), methods/ (7), game_methods, 79 command files, enums, card_stack, stat_calculator, action_handler (index, 250-deep history, save-per-action, undo/redo), disk-based game_data, l10n, translation_service, service_locator - ValueNotifier/ChangeNotifier removed in favor of plain fields with a minimal GameState listener hook for the Phase 2 broadcast layer; shared_preferences replaced by the SaveStore abstraction (InMemory for tests, File-backed for bin/main.dart) - command registry: 82 entries mapping wire names to constructors with arg validation; live-object args (loot/ability cards, figure lists) travel as id/name/nr and resolve against live state, enums by name, injected singletons never serialize - line_builder ported to Phase 1 scope: stat_applier + minimal LineBuilder (isElement, tokens); widget rendering deferred to Phase 4 - ported test suite: 81 test files, 562 tests green (command tests 1:1 with the reference, resource tests, registry smoke tests) - new headless integration test drives a full round: scenario setup, characters + standee, secret-initiative gate, draw, every figure's turn (incl. undo/redo), next round, round 2, round 3 - PORTING.md: the conventions contract used for the port - bin/main.dart boots the engine (file save store, assets/data) before serving; pubspec gains built_collection, collection, get_it, intl - dart format drift on pre-existing net/test files from the current formatter (whitespace only) dart analyze warning-free; dart test 562/562. --- server/PORTING.md | 317 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 317 insertions(+) create mode 100644 server/PORTING.md (limited to 'server/PORTING.md') diff --git a/server/PORTING.md b/server/PORTING.md new file mode 100644 index 0000000..cc5bdc2 --- /dev/null +++ b/server/PORTING.md @@ -0,0 +1,317 @@ +# Phase 1 Porting Conventions + +This document defines the exact rules for porting the reference app's game engine +(`FrosthavenAssistant/frosthaven_assistant/lib/` — **read-only**) into this package +(`server/lib/core/`). Every file in `lib/core/` and `test/` must follow these rules. + +## 1. Path and import mapping + +| Reference (`package:frosthaven_assistant/...`) | New (`package:x_haven_server/...`) | +|---|---| +| `lib/Model/.dart` | `lib/core/models/.dart` | +| `lib/Resource/state/game_state.dart` (+ part files) | `lib/core/state/game_state.dart` (+ part files, **same part structure**) | +| `lib/Resource/state/.dart` (part files) | `lib/core/state/.dart` | +| `lib/Resource/_methods.dart` (part files) | `lib/core/methods/_methods.dart` | +| `lib/Resource/commands/.dart` | `lib/core/commands/.dart` | +| `lib/Resource/line_builder/.dart` | `lib/core/line_builder/.dart` | +| `lib/Resource/.dart` (top-level) | `lib/core/.dart` | +| `lib/l10n/.dart` | `lib/core/l10n/.dart` | +| `lib/services/service_locator.dart` | `lib/core/service_locator.dart` | +| `lib/services/translation_service.dart` | `lib/core/translation_service.dart` | + +Import rewrites (apply to every ported file): + +- `package:frosthaven_assistant/Resource/...` → `package:x_haven_server/core/...` + (`Resource/state/x.dart` → `core/state/x.dart`, `Resource/commands/x.dart` → + `core/commands/x.dart`, `Model/x.dart` → `core/models/x.dart`, `l10n/x.dart` → + `core/l10n/x.dart`) +- `package:flutter/foundation.dart`, `package:flutter/material.dart`, + `package:flutter/widgets.dart`, `package:flutter/cupertino.dart`, + `package:flutter/services.dart` → **delete** (and delete the symbols they + provide: `ValueNotifier`, `ValueListenable`, `ChangeNotifier`, `kDebugMode`, + `debugPrint`, `rootBundle`, `WidgetsFlutterBinding`, `@immutable`) +- `package:shared_preferences/shared_preferences.dart` → **delete** (see §6) +- `dart:developer` (`log`) → `package:logging` (`Logger`), keep the messages +- `../../services/service_locator.dart` → the ported `package:x_haven_server/core/service_locator.dart` + +**Part files keep their part structure exactly.** `core/state/game_state.dart` +declares the same 18 `part` directives as the reference (the 7 `*_methods.dart` +files now live in `core/methods/` — part paths become +`part '../methods/character_methods.dart'` etc.). Part files start with +`part of 'game_state.dart';` unchanged. Part files share the library's imports, +so the main `game_state.dart` import list must keep everything the parts use. + +## 2. ValueNotifier / ChangeNotifier removal + +The server has no local observers — state goes out over the network later. +Conversion rules (apply everywhere, including in part files and commands): + +- `final _x = ValueNotifier(v);` + `ValueListenable get x => _x;` + → `T _x = v;` + `T get x => _x;` +- `final x = ValueNotifier(v);` (public field, e.g. in `Settings`, + `ActionHandler`) → `T x = v;` +- Reads: `x.value` → `x`, `_x.value` → `_x` +- Writes: `_x.value = v` → `_x = v`, `x.value = v` → `x = v` +- `ValueNotifier` values inside `Map` → plain + `ElementState` +- `elementStateFor(Elements e)` returns `ElementState`, not a listenable +- `ChangeNotifier` subclasses: drop `extends ChangeNotifier`, drop + `notifyListeners()` calls and `addListener`/`removeListener` from UI code. + `CardStack` becomes a plain class (its `notifyListeners()` calls are deleted). +- `ListUpdateNotifier` is deleted; `ActionHandler.updateList` is deleted and its + `notify()` call sites become `gameState.notifyListeners()`. +- `GameState` gains a minimal observer hook (used by the network layer in + Phase 2, harmless now): + ```dart + final List _listeners = []; + void addListener(void Function() listener) => _listeners.add(listener); + void removeListener(void Function() listener) => _listeners.remove(listener); + void notifyListeners() => [..._listeners].forEach((l) => l()); + ``` + Keep `_notifyCurrentList()` (it does real note-row reflow) — it now ends with + `notifyListeners()`. Keep `notifyAllMonsterInstances()`; the per-item + `_notifyMonsterInstances()` / `_notifySummonList()` calls become no-op stubs + (keep the method bodies empty with a `// UI-only in the reference app` comment, + or delete the calls — but do NOT delete the `notifyAllMonsterInstances` loop). +- `GameState.pendingAutoAddDialog` → plain `List?` +- `GameState.currentListNotifier` → **deleted** (UI-only); keep the + `currentList` getter returning `BuiltList.of(_currentList)`. +- `built_collection` stays (`BuiltList`/`BuiltMap`/`BuiltSet` getters unchanged). + +## 3. What is kept verbatim + +- **All public API signatures** of commands, state classes, and method classes — + constructor argument order (positional vs named), parameter names, method + names — so the ported test suite works with minimal edits. Example: + `AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1)` keeps its + positional constructor. +- `Command` abstract class and the `_StateModifier` capability token (they live + in `game_state.dart` as in the reference). +- All `toJson()` / `toString()` / `fromJson` / `updateFromJson` serialization + code — this is the wire/snapshot format. Do not rename keys. +- `GameSaveState` structure and behavior, including the quirk that + `GameState.load()` appends a (possibly empty) save state + (`gameSaveStates.length` grows by 2 across `save()` + `load()`). +- `ActionHandler` history semantics: 250-deep undo, command + description + + save-state lists, redo truncation, `getCurrent()`, `resetCommandHistory()`, + `clearLocalCommands()`, `insertReceivedDescription`. +- `GameEvent` sealed hierarchy + `toJsonString` — unchanged. +- `describe()` strings still come from `commandL10n` (ported, see §5). +- `enums.dart` — port as-is (no flutter deps). + +## 4. What is stripped + +- **UI calls inside engine code:** + - `MainList.scrollToTop()` (in `draw_command.dart`, `next_round_command.dart`, + `scenario_methods.dart`) → delete the call and the import. + - `Future.delayed(Duration(milliseconds: 600), () { _gameState.updateList.notify(); MainList.scrollToTop(); })` + blocks → delete entirely (draw_command, next_round_command). + - `WidgetsFlutterBinding.ensureInitialized()` → delete. +- **Network-awareness in `ActionHandler` / `Settings`:** the + `isServer` / `isClient` branching in `ActionHandler.action/undo/redo` is + removed — the new server is *always* the server. There is no + `Communication`, `Network`, or `Client` object. `Settings` drops the + `server`, `client`, `lastKnownConnection`, `lastKnownPort`, + `lastKnownHostIP`, `connectClientOnStartup` fields and the `init()`/ + `setFullscreen()`/window-manager code. + - `ActionHandler` constructor: `ActionHandler({required GameState gameState})`. + - After executing a command (and after undo/redo), instead of the network + send, call an optional hook so the Phase 2 layer can broadcast: + ```dart + /// Set by the network layer (Phase 2); null in tests. + void Function(int index, String description, String eventJson)? onAction; + ``` + - `Settings.loadSave/saveState/deleteSave/loadCharacterSave/saveCharacterState/ + deleteCharacterSave` and the `saves` / `characterSaves` maps stay (plain + `Map` now). +- **Disk persistence via `shared_preferences`** → replaced by `SaveStore` (§6). + `Settings` disk persistence is dropped entirely for now (Phase 6); keep + `toString()` and add `loadFromData(String json)` with the same field parsing + as the reference `loadFromDisk` (minus network fields). +- **`app_constants.dart` and `scaling.dart` are NOT ported in Phase 1** + (pure UI). Remove the `setMaxWidth()` call from Settings. +- `ui_utils.dart` is ported **minimally**: only `reducePowerEnabled()` + (reads `settings.powerMode`), used by `line_builder`. +- `theme_switcher.dart` — not ported (UI). +- `translation_service.dart` is ported with **disk loading** of + `server/assets/i18n/.json` (see `game_data.dart` for the disk + pattern); drop `ChangeNotifier` + `updateAllUI` calls. + +## 5. l10n and `commandL10n` + +- Port `lib/l10n/app_localizations*.dart` to `core/l10n/` as generated pure-Dart + files. The per-locale files are copied essentially verbatim (they are string + classes; keep the `initializeMessages` functions and `intl` usage). +- `app_localizations.dart`: keep the `AppLocalizations` class, the + `AppLocalizationsEn`/`...De` etc. classes, `supportedLocales`, and + `lookupAppLocalizations(Locale)`. **Delete** the `LocalizationsDelegate`, + `WidgetsBinding`, `AppLocalizations.of(context)` machinery. +- `dart:ui`'s `Locale` is not available in pure Dart — define it once in + `core/l10n/app_localizations.dart`: + ```dart + class Locale { + const Locale(this.languageCode, [this.countryCode]); + final String languageCode; + final String? countryCode; + @override + String toString() => countryCode == null ? languageCode : '$languageCode-$countryCode'; + } + ``` + and use it in `lookupAppLocalizations`. +- `commands/command_l10n.dart` ports as in the reference (reads + `getIt().locale`, falls back to English) but uses the local `Locale`. + +## 6. Save store (replaces shared_preferences) + +New file `core/save_store.dart`: + +```dart +/// Persistent store for the authoritative game-state snapshot. +abstract class SaveStore { + String? read(); + void write(String data); + void clear(); +} + +class InMemorySaveStore implements SaveStore { ... } // plain String? + +class FileSaveStore implements SaveStore { // sync file under saves/ + FileSaveStore(String directory) : _file = File(p.join(directory, 'game.json')); + void write(String data) => _file.writeAsString(data, flush: true); + String? read() => _file.existsSync() ? _file.readAsStringSync() : null; + void clear() { if (_file.existsSync()) _file.deleteSync(); } +} +``` + +- `GameSaveState.saveToDisk` / `loadFromDisk` become **synchronous** + (`void`), reading/writing through `getIt()`. + (`GameState.save()` / `load()` remain sync as in the reference — in the + reference these were fire-and-forget async prefs writes; the sync file store + preserves observable behavior and is what Phase 2 needs: save-before-broadcast.) +- Tests register `InMemorySaveStore`; `bin/main.dart` registers + `FileSaveStore('saves')`. + +## 7. `GameData` — disk-based + +`GameData.loadData(String root)` keeps its signature (`root` is a directory +path, e.g. `'assets/testData/'` in tests, `'assets/data/'` in production) but +reads with `dart:io` instead of `rootBundle`: + +- `rootBundle.loadString('${root}summons.json')` → `File(p.join(root, 'summons.json')).readAsString()` +- same for `${root}editions/editions.json` and `${root}rooms/$campaign.json` +- drop `evict(...)` / `cache: false` (file reads are fresh every time) +- `modelData` → plain `Map modelData = {}` + +## 8. `service_locator.dart` + +```dart +final getIt = GetIt.instance; + +void setupCore({SaveStore? saveStore, Settings? settings, GameData? gameData, GameState? gameState}) { + getIt.unregister... // not needed — keep the simple version: +} +``` + +Keep the reference shape but register only what exists server-side: + +```dart +void setupCore({SaveStore? saveStore}) { + getIt.registerLazySingleton(() => saveStore ?? InMemorySaveStore()); + getIt.registerLazySingleton(() => GameData()); + getIt.registerLazySingleton(() => Settings()); + getIt.registerLazySingleton(() => GameState()); + getIt.registerLazySingleton(() => TranslationService()); +} +``` + +(`GameState()` constructs its own `ActionHandler` — see the ported +`game_state.dart` constructor: `GameState({Settings? settings})`.) + +Tests may call `setupCore()` once in `setUpAll` and then re-register singletons +between tests if a test file needs fresh state — port test files keep whatever +pattern the reference tests use (`setupGetIt()` → `setupCore()`). + +## 8b. line_builder — Phase 1 scope + +The reference `line_builder/` produces Flutter widgets (`RichText`, +`AnimatedText`, `BoxDecoration`) to render ability lines in the app. The web +client re-implements that rendering in Phase 4. In Phase 1, only the +**game-logic** parts are ported to `core/line_builder/`: + +- `stat_applier.dart` — ported in full (pure logic: `applyMonsterStats` and + friends return `List`, resolved against game state). +- `line_builder.dart` — minimal port: the `LineBuilder` class with the + `tokens` map, `isElement(String)`, and any other pure-logic helpers that + `stat_applier.dart` needs. Do NOT port the widget-building methods + (`createLines`, `createAbilityText`, padding/margin metrics). +- `line_styles.dart`, `token_applier.dart`, `frosthaven_converter.dart` — + **not ported** (pure UI styling/rendering). + +Corresponding tests: port `stat_applier_test.dart` and the `isElement` group +of `line_builder_test.dart`; skip the widget/metrics tests +(`token_applier_test.dart`, `frosthaven_converter_test.dart`, +`should_animate_line_test.dart`, `TextStyle`-metric groups). + +## 9. Commands and the command registry (new) + +- Every command file ports with its exact API (see §3). +- **New file** `core/commands/command_registry.dart` (written last, after all + commands exist): a wire-name → constructor map used by the Phase 2 network + layer. + +```dart +/// One entry: wire name, arg parsing/validation, and command construction. +class CommandDescriptor { + const CommandDescriptor(this.name, this.construct); + final String name; // e.g. 'draw', 'addMonster', 'changeHealth' + final Command Function(GameState gameState, Map args) construct; +} + +class CommandRegistryError implements Exception { final String message; ... } + +Command buildCommand(String name, Map args, GameState gameState); +// throws CommandRegistryError with a human-readable message for unknown +// names or invalid/missing args. +String commandName(Command command); // reverse lookup (for describe/tests) +``` + +Wire names: camelCase of the class name minus the `Command` suffix +(`DrawCommand` → `draw`, `AddMonsterCommand` → `addMonster`, +`ChangeHealthCommand` → `changeHealth`; acronym runs lower-cased in full, +e.g. `ChangeXPCommand` → `changeXP`). Args: the command's constructor +parameters by name; positional-arg commands map positional args from a +`List`-free convention: pass them as named keys in the same order as the +positional parameters (e.g. `AddCharacterCommand(id, edition, display, level)` +→ `{'id': ..., 'edition': ..., 'display': ..., 'level': ...}`). +Every parameter type must be one of: `int`, `bool`, `String`, `double`, +`List`, `List`, `List`, `Map`, +`String?`, `int?`, `bool?`, `double?`, `List?`, `List?`, `Map`, +or another constructor argument. If a command takes a constructor param that is +not JSON-serializable, flag it in the report (do not invent a workaround). + +## 10. Tests + +- `package:flutter_test` → `package:test`; `testWidgets` → `test`. +- `test/command/test_helpers.dart` is rewritten (provided in this repo): + - `setUpGame()` → `setupCore(saveStore: InMemorySaveStore())`, + `gameState = getIt()`, `gameState.init()`, + `await getIt().loadData('assets/testData/')`, `gameState.load()`. + - keep `checkSaveState()` and `checkNoSideEffects()` as-is (uses `json_diff`). + - drop `testApp()`, `ignoreOverflowErrors()`, `SharedPreferences`, + `TestWidgetsFlutterBinding`, l10n delegates. +- Engine tests (everything under `test/command/` and the non-UI tests under + `test/resource/`) port 1:1 otherwise: same assertions, same command + invocations. Only import paths, `.value` removals, and the helpers import + change. +- UI tests (`test/Layout/`, `test/widget/`, most `test/services/`) are **not** + ported in Phase 1. + +## 11. Style + +- `dart format` (default page width 80) on all new files. +- Lints per `analysis_options.yaml` (`unawaited_futures`, + `avoid_dynamic_calls`, `prefer_final_locals`) — the CI script + (`scripts/ci.sh`) runs `dart analyze` and must be warning-free. +- Keep the reference app's doc comments where they explain behavior. +- Do not add behavior. Do not "improve" the ported logic. Mechanical + translation only, plus the explicit conversions in this document. -- cgit v1.3.1